Structured Query Lang.
Structured Query Lang.
Schema Definition
Basic Constraints
Queries
SQL - The Relational Database Standard
• In SQL terminology ,
• A relation is called a table
Example:
In general , not all users are authorized to create schema and schema elements .
The privilege for these must be given by Database Administrator (DBA)
SQL Data Definition : Schema and Catalog Concepts
SQL catalog
A named collection of schemas in an SQL environment.
• The attributes are specified first, and each attribute is given a name
• Syntax :
CREATE TABLE COMPANY.EMPLOYEE… OR
Advantage :
• Easier to change data type for s domain
• Improves readability
SQL Data Definition : The CREATE TABLE Command
• The relations declared through CREATE TABLE statements are called base
tables (or base relations)
• The relations declared through CREATE VIEW statements are called virtual
tables (or virtual relations)
• Character-string 2 types
1. Fixed-length
2. Varying-length
2. Varying length
• Literal bit strings are placed between single quotes but precede by a B ;
Example B’10101’
SQL DATA Types
• Boolean
• Traditional Values: TRUE or FALSE
DATE’2002-09-27’ or TIME’09:12:47’
• The < (less than) comparison can be used with dates or times.
SQL DATA Types
• Timestamp
• A timestamp data type (TIMESTAMP) includes both the DATE and
TIME fields, plus a maximum number of six positions for decimal
fractions of seconds and an optional WITH TIME ZONE qualifier
• Interval
• Also for any other attributes whose values are required not to
be NULL.
2. DEFAULT Constraints:
3. CHECK :
Example :
DNUMBER INT NOT NULL CHECK (DNUMBER > 0 AND DNUMBER < 21 )
Specifying Key and Referential Integrity Constraints:
1. The PRIMARY KEY clause
• Specifies one or more attributes that make up the primary
key of a relation.
• If primary key single attribute then the clause can follow the
attribute directly
Example:
Example :
CONSTRAINT DEPTPK PRIMARY KEY(DNUMBER)
– The names all the constraints must be unique within a schema.
– CASCADE option , when dropping a table , will remove table and all its
be executed.
The ALTER TABLE Command
Examples:
1. ALTER TABLE EMPLOYEE ADD JOB VARCHAR(12);
General form :
SELECT <attribute list>
FROM <table list>
WHERE <condition>
Populated Database
The SELECT-FROM-WHERE : Examples
Query 1: Retrieve the name and address of all employees who work for
the 'Research' department.
Query 2: For every project located in 'Stafford', list the project number, the
controlling department number, and the department manager's last name,
address, and birthdate.
In Q2, there are two join conditions and one select condition
Example:
Suppose that LNAME and DNO attributes of EMPLOYEE table were called NAME
and DNUMBER, and DNAME attribute of the DEPARTMENT was also called
NAME. then Query1 must be restated as follows.
• Ambiguity also arises if some queries need to refer to the same relation
twice
• In this case, aliases are given to the relation name using AS
Query 8: For each employee, retrieve the employee's name, and the
name of his or her immediate supervisor.
WHERE E.SUPERSSN=S.SSN
Aliasing and Tuple Variables
• In Q8, the alternative relation names E and S are called aliases or tuple
role of supervisors
• Use of AS is optional.
Query 9 and Query 10: Retrieve the SSN values for all employees.
Q9: SELECT SSN
FROM EMPLOYEE
Q1C : SELECT *
FROM EMPLOYEE
WHERE DNO=5;
Q1D : SELECT *
FROM EMPLOYEE, DEPARTMENT
WHERE DNAME=‘Research’ AND DNO=DNUMBER;
Q10A : SELECT *
FROM EMPLOYEE, DEPARTMENT;
• SQL does not treat a relation as a set; duplicate tuples can appear
Query 11 : Retrieve the salary of every employee (Q11) and all distinct salary values (Q11A)
•The relations resulting from these operations are set of tuples ; duplicates tuples
QUERY 4 : Make a list of all project numbers for projects that involve an employee whose last
name is 'Smith', either as a worker or as a manager of the department that controls the
project.
Q4: (SELECT DISTINCT PNUMBER FROM PROJECT, DEPARTMENT, EMPLOYEE WHERE
DNUM=DNUMBER AND MGRSSN=SSN AND LNAME='Smith')
UNION
Examples
Figure 8.5 The results of SQL multiset operations. (a) Two tables, R(A)
and S(A). (b) R(A) UNION ALL S(A). (c) R(A) EXCEPT ALL S(A).
(d) R(A) INTERSECT ALL S(A).
4.5 Basic Queries in SQL
Substring Pattern Matching and Arithmetic Operators
• The LIKE comparison operator can be used for string pattern matching.
•Partial strings are specified using two reserved characters:
1. % replaces an arbitrary number of zero or more characters
QUERY 12A : Find all employees who were born during the 1950s.
Q12A: SELECT FROM WHERE
FNAME, LNAME EMPLOYEE
BDATE LIKE ‘195 _ _ _ _ _ _ _';
[YYYY-MM-DD]
4.5 Basic Queries in SQL
Substring Pattern Matching and Arithmetic Operators
For example:
'AB\_CD\%EF' ESCAPE '\' represents the literal string ‘AB_CD%EF',
because \ is specified as the escape character
• The standard arithmetic operators for addition (+), subtraction (-), multiplication
(*), and division (/) can be applied to numeric values or attributes with numeric
domains.
Example :
QUERY 13 : Show the resulting salaries if every employee working on the
'ProductX' project is given a 10 percent raise.
Note : The condition (SALARY BETWEEN 30000 AND 40000) in Q14 is equivalent
to the condition ((SALARY >= 30000) AND (SALARY <= 40000)
4.5 Basic Queries in SQL
Ordering of Query Results
• SQL allows the user to order the tuples in the result of a query by the values of
QUERY 15 : Retrieve a list of employees and the projects they are working on,
order of values.
4.6 More Complex SQL Queries
Comparisons Involving NULL and Three-Valued Logic
• SQL uses a three-valued logic with values TRUE, FALSE, and UNKNOWN
• Table 8.1 shows the result of three-valued logic when logical connectives
AND, OR, and NOT are used .
4.6 More Complex SQL Queries
Comparisons Involving NULL and Three-Valued Logic
• Comparison operator IN, which compares a value v with a set of values V and
Example :
OR
PNUMBER IN (SELECT PNO FROM WORKS_ON, EMPLOYEE
WHERE ESSN=SSN AND LNAME='Smith');
4.6 More Complex SQL Queries
•This query will select the social security numbers of all employees who work the
same (project, hours) combination on some project that employee 'John Smith'
(whose SSN ='123456789') works on.
•In this example, the IN operator compares the subtuple of values in parentheses
(PNO, HOURS) for each tuple in WORKS_ON with the set of union-compatible tuples
produced by the nested query.
4.6 More Complex SQL Queries
• ANY , SOME , ALL can be used with =, >,>=, <, <=, and < >.
Example : Retrieve names of employees whose salary is greater than the salary of
all the employees in department 5:
• The = ANY (or = SOME) operator returns TRUE if the value v is equal to some
value in the set V and is hence equivalent to IN.
4.6 More Complex SQL Queries
faced with possible ambiguity among attribute names if attributes of the same
name exist-one in a relation in the FROM clause of the outer query, and another in
a relation in the FROM clause of the nested query.
•To refer to an attribute of the PROJECT relation specified in the outer query, we
can specify and refer to an alias (tuple variable) for that relation.
4.6 More Complex SQL Queries
Nested Queries and Set Comparisons
• To illustrate the potential ambiguity of attribute names in nested queries, consider
Query 16.
QUERY 16 : Retrieve the name of each employee who has a dependent with the
same first name and same sex as the employee.
Q16: SELECT E.FNAME, E.LNAME FROM EMPLOYEE AS E
WHERE E.SSN IN (SELECT ESSN FROM DEPENDENT WHERE
E.FNAME=DEPENDENT_NAME AND E.SEX=SEX);
•In the nested query of Q16, we must qualify E. SEX because it refers to the SEX attribute
of EMPLOYEE from the outer query, and DEPENDENT also has an attribute called SEX.
•All unqualified references to SEX in the nested query refer to SEX of DEPENDENT.
•However, we do not have to qualify FNAME and SSN because the DEPENDENT relation does not
have attributes called FNAME and SSN, so there is no ambiguity.
4.6 More Complex SQL Queries
attribute of a relation declared in the outer query, the two queries are said to be
correlated.
•We can understand a correlated query better by considering that the nested query
is evaluated once for each tuple (or combination of tuples) in the outer query
•The EXISTS function in SQL is used to check whether the result of a correlated
nested query is empty (contains no tuples) or not. If the result of a correlated
nested query contains at least one tuple , it returns TRUE . Otherwise returns
FALSE
Query 16 in an alternative form that uses EXISTS. This is shown as QI6B:
Q16B: SELECT E.FNAME, E.LNAME
FROM EMPLOYEE AS E
WHERE EXISTS (SELECT * FROM DEPENDENT WHERE E.SSN=ESSN
AND E.SEX=SEX AND E.FNAME=DEPENDENT_NAME);
•In general, EXISTS(Q) returns TRUE if there is at least one tuple in the result of the
nested query Q, and it returns FALSE otherwise.
4.6 More Complex SQL Queries
The EXISTS and UNIQUE Functions in SQL
•On the other hand, NOTEXISTS(Q) returns TRUE if there are no tuples in the
result of nested query Q, and it returns FALSE otherwise
QUERY 7 : List the names of managers who have at least one dependent.
First selects all DEPENDENT tuples related to an EMPLOYEE, and the second selects all
DEPARTMENT tuples managed by the EMPLOYEE. . If at least one of the first and at least one
of the second exists, we select the EMPLOYEE tuple.
4.6 More Complex SQL Queries
The EXISTS and UNIQUE Functions in SQL
• Query 3 can be stated using EXISTS and NOT EXISTS in SQL systems.
("Retrieve the name of each employee who works on all the projects
controlled by department number 5,” )
EXCEPT
(SELECT PNO FROM WORKS_ON WHERE
SSN=ESSN) );
4.6 More Complex SQL Queries
Explicit Sets and Renaming of Attributes in SQL
• It is also possible to use an explicit set of values in the WHERE clause, rather
than a nested query. Such a set is enclosed in parentheses in SQL.
WHERE E.SUPERSSN=S.SSN;
4.6 More Complex SQL Queries
Joined Tables in SQL
• The concept of a joined table (or joined relation) is used to specify a table
resulting from a join operation in the FROM clause of a query.
•For example
consider query1, which retrieves the name and address of every employee
who works for the 'Research' department. It may be easier first to specify the
join of the EMPLOYEE and DEPARTMENT relations, and then to select the desired
tuples and attributes.
WHERE DNAME='Research';
4.7 Aggregate Functions in SQL
•These functions can be used in the SELECT clause or in a HAVING clause (which
we introduce later).
•The functions MAX and MIN can also be used with attributes that have
nonnumeric domains
4.7 Aggregate Functions in SQL
QUERY 19
Find the sum of the salaries of all employees, the maximum salary, the minimum
salary, and the average salary.
Q19: SELECT SUM (SALARY), MAX (SALARY), MIN (SALARY),AVG (SALARY)
FROM EMPLOYEE;
QUERY 20 : Find the sum of the salaries of all employees of the 'Research'
department, as well as the maximum salary, the minimum salary, and the
average salary in this department.
Q20: SELECT SUM (SALARY), MAX (SALARY), MIN (SALARY), AVG (SALARY)
FROM EMPLOYEE ,DEPARTMENT WHERE DNO=DNUMBER and
DNAME='Research';
4.7 Aggregate Functions in SQL
QUERIES 21 AND 22
Retrieve the total number of employees in the company (Q21) and the number
of employees in the 'Research' department (Q22).
Here the asterisk (*) refers to the rows (tuples), so COUNT (*) returns the number of
rows in the result of the query
4.7 Aggregate Functions in SQL
•We may also use the COUNT function to count values in a column rather than
tuples, as in the next example.
QUERY 23
Count the number of distinct salary values in the database.
Q23: SELECT COUNT (DISTINCT SALARY) FROM EMPLOYEE;
• We can specify a correlated nested query with an aggregate function, and then
use the nested query in the WHERE clause of an outer query.
For example, to retrieve the names of all employees who have two or
more dependents (Query 5), we can write the following:
•The GROUP BY clause specifies the grouping attributes, which should also
appear in the SELECT clause, so that the value resulting from applying each
aggregate function to a group of tuples appears along with the value of the
grouping attributes.
QUERY 24 : For each department, retrieve the department number, the number
• In Q24, the EMPLOYEE tuples are partitioned into groups-each group having the same
value for the grouping attribute DNO.
• The COUNT and AVG functions are applied to each such group of tuples.
4.8 Grouping: The GROUP BY and HAVING Clauses
QUERY 24 :
• If NULLs exist in the grouping attribute, then a separate group is created for all tuples
with a NULL value in the grouping attribute.
QUERY 25 : For each project, retrieve the project number, the project name,
QUERY 26 : For each project on which more than two employees work, retrieve
the project number, the project name, and the number of employees who work
on the project.
QUERY 26 : After applying the WHERE clause but before applying HAVING
4.8 Grouping: The GROUP BY and HAVING Clauses
QUERY 27
For each project, retrieve the project number, the project name, and the
number of employees from department 5 who work on the project.
QUERY 28
For each department that has more than five employees, retrieve the
department number and the number of its employees who are making more
than $40,000.
•A second form of the INSERT statement allows the user to specify explicit
command.
•This is useful if a relation has many attributes but only a few of those
•However, the values must include all attributes with NOT NULL
•Attributes with NULL allowed or DEFAULT values are the ones that can be
left out.
4.9 INSERT, DELETE, AND UPDATE
STATEMENTS IN SQL
For example, to enter a tuple for a new EMPLOYEE for whom we know only the FNAME,
• For example, to create a temporary table that has the name, number of
employees, and total salaries for each department, we can write the statements
in U3A and U3B:
GROUP BY DNAME;
• A table DEPTS_INFO is created by U3A and is loaded with the summary information
retrieved from the database by the query in U3B.
4.9 INSERT, DELETE, AND UPDATE
STATEMENTS IN SQL
• The DELETE command removes tuples from a relation. It can include WHERE
•A missing WHERE clause specifies that all tuples in the relation are to be
deleted;
4.9 INSERT, DELETE, AND UPDATE
STATEMENTS IN SQL
FROM DEPARTMENT
WHERE DNAME='Research');
• However, updating a primary key value may propagate to the foreign key
values of tuples in other relations if such a referential triggered action is
specified in the referential integrity constraints of the DDL