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 key, entity integrity, and referential integrity constraints can be specified
—within the CREATE TABLE statement—after the attributes are declared.
• Syntax :
CREATE TABLE COMPANY.EMPLOYEE… OR
Advantage :
• Easier to change data type for 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
1. Fixed 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
• 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
2. DEFAULT Constraint:
• To define a default value for an attribute
3. CHECK Constraint :
• To restrict the attribute or domain values.
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:
FOREIGN KEY (DNO) REFERENCES DEPARTMENT(DNUMBER)
ON DELETE SET DEFAULT ON UPDATE CASCADE.
Specifying Key and Referential Integrity Constraints:
Example :
CONSTRAINT DEPTPK PRIMARY KEY(DNUMBER)
– The names all the constraints must be unique within a schema.
– Constraints can be dropped or replaced with another constraint.
– Giving names to constraints is optional.
Specifying Constraints on Tuples Using CHECK
– CASCADE option , when dropping a table , will remove table and all its
be executed.
he ALTER TABLE Command
Examples:
General form :
SELECT <attribute list>
FROM <table list>
WHERE <condition>
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.
SELECT SSN
FROM EMPLOYEE
Unspecified WHERE-clause
Q1C : SELECT *
FROM EMPLOYEE
WHERE DNO=5;
Q1D : SELECT *
FROM EMPLOYEE, DEPARTMENT
WHERE DNAME=‘Research’ AND DNO=DNUMBER;
Q10A : SELECT *
FROM EMPLOYEE, DEPARTMENT;
Query 11 : Retrieve the salary of every employee (Q11) and all distinct salary values (Q11A)
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).
Substring Pattern Matching
QUERY 12A : Find all employees who were born during the
1950s.
For example:
'AB\_CD\%EF' ESCAPE '\' represents the literal string ‘AB_CD%EF',
because \ is specified as the escape character
Note : The condition (SALARY BETWEEN 30000 AND 40000) in Q14 is equivalent
QUERY 15 : Retrieve a list of employees and the projects they are working
order of values.
Use of ORDER BY
Example
SELECT * FROM People ORDER BY FirstName,
YearOfBirth, LastName
Use of ORDER BY
Example
Result:
More Complex
SQL Queries
NULL value and Three-Valued Logic
2. Unavailable values :
• 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 .
Use of IS or IS NOT
SELECT attribute_list
FROM table_list Outer Query
WHERE attr_list_1 IN (
SELECT attr_list_1
Nested
FROM table_list1
Query
WHERE condition (inner query)
)
Nested Queries - IN operator
'Smith', either as a worker or as a manager of the department that controls the project.)
OR
PNUMBER IN (SELECT PNO FROM WORKS_ON, EMPLOYEE
WHERE ESSN=SSN AND LNAME='Smith');
Nested Queries - IN operator
Nested Queries - IN operator
• The IN operator can also compare a tuple of values in parentheses with a set or
multiset of union-compatible tuples.
QUERY: select the SSNs of all employees who work the same (project, hours)
combination on some project that employee 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 is compared with the set of union-compatible tuples produced by the nested
query.
Nested Queries - ANY , SOME and ALL
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.
Nested Queries and Ambiguity
relation in the FROM clause of the outer query, and another in a relation
QUERY 16 : Retrieve the name of each employee who has a dependent with the
same first name and same sex as the employee.
•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.
Correlated Nested Queries
attribute of a relation declared in the outer query, the two queries are said to
be correlated.
query is evaluated once for each tuple (or combination of tuples) in the outer
query
Correlated Nested Queries
values for all DEPENDENT tuples with the same sex and name as that EMPLOYEE
tuple; if the SSN value of the EMPLOYEE tuple is in the result of the nested query,
• In general, a query written with nested select-from-where blocks and using the
= or IN comparison operators can always be expressed as a single block query.
For example, Q16 may be written as in Q16A:
E.FNAME=D.DEPENDENT_NAME;
Correlated Nested Queries - EXISTS Function
•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.
Correlated Nested Queries - EXISTS Function
FROM EMPLOYEE AS E
•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.
Correlated Nested Queries - NOT EXISTS Function
• NOT EXISTS(Q) returns TRUE if there are no tuples in the result of nested query
Q, and it returns FALSE otherwise
For each EMPLOYEE tuple, the correlated nested query selects all DEPENDENT
tuples whose ESSN value matches the EMPLOYEE SSN; if the result is empty,
QUERY 7 : List the names of managers who have at least one dependent.
WHERE
AND
EXCEPT
(SELECT PNO FROM WORKS_ON WHERE
SSN=ESSN) );
• The SQL EXCEPT clause/operator is used to
combine two SELECT statements and returns
rows from the first SELECT statement that are
not returned by the second SELECT statement
• 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.
Q8A: (Retrieving the employee's name, and the name of his or her
immediate supervisor.)
WHERE E.SUPERSSN=S.SSN;
Joined Tables in SQL
• Used to specify a table resulting from a join operation in the FROM clause of
a query.
First specify the join of the EMPLOYEE and DEPARTMENT relations using JOIN
WHERE DNAME='Research';
Joined Tables in SQL
WHERE DNAME='Research;
Joined Tables in SQL
WHERE PLOCATION='Stafford';
Aggregate Functions
in SQL-99
COUNT, SUM, MAX, MIN, and AVG functions.
• SUM, MAX, MIN, and AVG return sum, maximum value, minimum value,
• All the functions can be used in the SELECT clause or in a HAVING clause
• The functions MAX and MIN can also be used with attributes that have
nonnumeric domains
COUNT, SUM, MAX, MIN, and AVG functions.
QUERY 19 : Find the sum of the salaries of all employees, the maximum
salary, the minimum salary, and the average salary.
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';
COUNT, SUM, MAX, MIN, and AVG functions.
Here the asterisk (*) refers to the rows (tuples), so COUNT (*) returns the number of
rows in the result of the query
COUNT, SUM, MAX, MIN, and AVG functions.
• 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 we can write the following:
QUERY 24 : For each department, retrieve the department number, the number
• If NULLs exist in the grouping attribute, then a separate group is created for
all tuples with a NULL value in the grouping attribute.
The GROUP BY Clauses
QUERY 25 : For each project, retrieve the project number, the project name,
WHERE PNUMBER=PNO
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
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.
• We must specify the relation name and a list of values for the tuple.
• The values should be listed in the same order in which the corresponding
UI: INSERT INTO EMPLOYEE VALUES ('Richard', 'K', 'Marini', '653298653', '1962-
• This allows the user to specify explicit attribute names that correspond to
• 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 specification
• Attributes with NULL allowed or DEFAULT values are the ones that can be
left out.
Another form of the INSERT Command :
For example, to enter a tuple for a new EMPLOYEE for whom we know only
the FNAME, LNAME, DNO, and SSN attributes, we can use U1A:
• 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:
WHERE DNUMBER=DNO
GROUP BY DNAME;
• A table DEPTS_INFO is created by U3A and is loaded with the summary information
DDL
• A missing WHERE clause specifies that all tuples in the relation are to be
deleted;
The DELETE Command
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
PLOCATION = 'Bellaire‘;
The UPDATE Command
frequently
Why a View in SQL?
• Suppose that we frequently issue queries that retrieve the employee
name and the project names that the employee works on.
Rather than having to specify the join of the EMPLOYEE, WORKS_ON, and
PROJECT tables every time we issue that query , we can define a view that is a
result of these joins. We can then issue queries on the view
Specification of Views in SQL
• the command to specify a view is CREATE VIEW.
• The view is given a
1. view name,
2. a list of attribute names (Optional)
3. and a query to specify the contents of the view.
Specification of Views in SQL
Specification of Views in SQL
We can now specify SQL queries on a view-or virtual table-in the same way we
specify queries involving base tables.
Example : to retrieve the last name and first name Of all employees who work on
'ProjectX',
Student(snum: integer, sname: string, major: string, level: string, age: integer)
1. Find the names of all Juniors (Level = JR) who are enrolled
in a class taught by John Borg.
2. Find the age of the oldest student who is either a History
major or is enrolled in a course taught by John Borg.
3. Find the names of all classes that either meet in room R128
or have five or more students enrolled.
4. Find the names of all students who are enrolled in two
classes that meet at the same time.
5. Find the names of faculty members who teach in every
room in which some class is taught.
6. Find the names of faculty members for whom the combined
enrollment of the courses that they teach is less than five.
Exercise
Write the following queries in SQL.
7. Print the Level and the average age of students for that
Level, for each Level.
8. Print the Level and the average age of students for that
Level, for all Levels except JR.
9. Find the names of students who are enrolled in the
maximum number of classes.
10. Find the names of students who are not enrolled in any
class.
11. For each age value that appears in Students, nd the level
value that appears most often. For example, if there are
more FR level students aged 18 than SR, JR, or SO
students aged 18, you should print the pair (18, FR).
Exercise
Write the output of the following queries specified on the given table.
People
FirstName LastName YearOfBirth
Thomas Alva Edison 1847
Benjamin Franklin 1706
Thomas More 1478
Thomas Jefferson 1826
Benjamin Britten 1767
Benjamin Burnley 1845