WCU Lab Exercise
WCU Lab Exercise
Introduction to SQL
P.by Abdiwak T. 1
Course SEng4031: Advanced Database Systems Lesson Introduction to SQL
History
INDEX
▶ Overview of SQL
• IBM Sequel language developed as part of System R
▶ Data Definition project at the IBM San Jose Research Laboratory
Domain Types
Create Table • Renamed Structured Query Language (SQL)
Updates to Table
▶ Query Structure
• ANSI and ISO standard SQL:
Select Clause • SQL-86
Where Clause
From Clause
• SQL-89
▶ More Basic Ops • SQL-92
Rename Operation
String Operations
• SQL:1999 (language name became Y2K compliant!)
Ordering • SQL:2003
Duplicates
▶ Query Structure
• The schema for each relation.
Select Clause • The domain of values associated with each
Where Clause
From Clause attribute.
▶ More Basic Ops • Integrity constraints
Rename Operation
String Operations • And as we will see later, also other information
Ordering
Duplicates
such as
▶ Set Operations
• The set of indices to be maintained for each relations.
▶ Null Values • Security and authorization information for each
▶ Aggregate relation.
▶ Modification of DB
Functions • The physical storage structure of each relation on disk.
▶ Query Structure
• int. Integer (a finite subset of the integers that is machine-
Select Clause dependent).
Where Clause
• smallint. Small integer (a machine-dependent subset of the
From Clause
▶ Set Operations
CREATE TABLE instructor (
▶ Null Values ID char(5),
▶ Aggregate name varchar(20),
▶ Modification of DB
Functions dept_name varchar(20),
salary numeric(8,2))
Soft.Eng Program @ SoCI, WCU 5
Course SEng4031: Advanced Database Systems Lesson Introduction to SQL
Integrity Constraints
INDEX
▶ Overview of SQL
• not null
▶ Data Definition
Domain Types
• primary key (A1, ..., An )
Create Table
Updates to Table • foreign key (Am, ..., An ) references r
▶ Query Structure
Select Clause • Example:
Where Clause
From Clause
• CREATE TABLE instructor (
▶ More Basic Ops ID char(5),
Rename Operation Name varchar(20) not null,
String Operations dept_name varchar(20),
Ordering
Salary numeric(8,2),
Duplicates
▶ Set Operations
PRIMARY KEY (ID),
▶ Null Values FOREIGN KEY (dept_name) REFERENCES
▶ Aggregate department(dept_name);
▶ Modification of DB
Functions • primary key declaration on an attribute
automatically ensures not null
Soft.Eng Program @ SoCI, WCU 6
Course SEng4031: Advanced Database Systems Lesson Introduction to SQL
▶ Query Structure
Select Clause Credits numeric(2,0),
Where Clause
From Clause PRIMARY KEY (course_id),
▶ More Basic Ops
FOREIGN KEY (dept_name) references
department(dept_name);
Rename Operation
String Operations
Ordering
Duplicates
▶ Set Operations
▶ Null Values
▶ Aggregate
▶ Modification of DB
Functions
Updates to Tables
INDEX • Insert
▶ Overview of SQL
• INSERT INTO instructor
▶ Data Definition
Domain Types VALUES (‘10211’, ’Smith’, ’Biology’, 66000);
Create Table
• Delete
Updates to Table
• Remove all tuples from the student relation
▶ Query Structure
Select Clause
• DELETE FROM student
Where Clause • Drop Table
From Clause
• DROP TABLE r
▶ More Basic Ops
Rename Operation • Alter
String Operations • ALTER TABLE r ADD A D
Ordering
• where A is the name of the attribute to be added to relation r and D
Duplicates
is the domain of A.
▶ Set Operations
▶ Null Values
• All exiting tuples in the relation are assigned null as the value for the
▶ Aggregate
new attribute.
▶ Modification of DB • ALTER TABLE r DROP A
Functions
• where A is the name of an attribute of relation r
• Dropping of attributes not supported by many databases.
Soft.Eng Program @ SoCI, WCU 9
Course SEng4031: Advanced Database Systems Lesson Introduction to SQL
▶ Set Operations
• P is a predicate.
▶ Null Values
▶ Aggregate
• The result of an SQL query is a relation.
▶ Modification of DB
Functions
▶ More Basic Ops • Results is a table with one column and a single row with
Rename Operation value “437”
String Operations
Ordering
• Can give the column a name using:
Duplicates SELECT ‘437’ as FOO
▶ Set Operations
▶ Null Values
• An attribute can be a literal with from clause
▶ Aggregate • SELECT ‘A’
▶ Modification of DB FROM instructor
Functions
• Result is a table with one column and N rows (number of
tuples in the instructors table) each row with value “A”
Soft.Eng Program @ SoCI, WCU 13
Course SEng4031: Advanced Database Systems Lesson Introduction to SQL
▶ Query Structure
attributes of tuples.
Select Clause
Where Clause
• The query:
From Clause SELECT ID, name, salary/12 FROM instructor
▶ More Basic Ops
Rename Operation
would return a relation that is the same as the
String Operations instructor relation, except that the value of the
Ordering
Duplicates
attribute salary is divided by 12.
▶ Set Operations • Can rename “salary/12” using the as clause:
▶ Null Values
▶ Aggregate SELECT ID, name, salary/12 AS monthly_salary
▶ Modification of DB
Functions
▶ Set Operations
resulting table are renamed using the relation name (e.g.,
▶ Null Values
instructor.ID)
▶ Aggregate
▶ Modification of DB
• Cartesian product not very useful directly, but useful
Functions combined with where-clause condition (selection
operation in relational algebra).
Soft.Eng Program @ SoCI, WCU 16
Course SEng4031: Advanced Database Systems Lesson Introduction to SQL
▶ Query Structure
Select Clause
Where Clause
From Clause
▶ Set Operations
▶ Null Values
▶ Aggregate
▶ Modification of DB
Functions
Examples
INDEX
▶ Overview of SQL
• Find the names of all instructors who have
▶ Data Definition taught some course and the course_id
Domain Types
Create Table SELECT name, course_id
Updates to Table
FROM instructor , teaches
▶ Query Structure
Select Clause
WHERE instructor.ID = teaches.ID
Where Clause
From Clause
• Find the names of all instructors in the Art
▶ More Basic Ops department who have taught some course
and the course_id
Rename Operation
String Operations
Ordering
Duplicates
SELECT name, course_id
▶ Set Operations FROM instructor , teaches
▶ Null Values WHERE instructor.ID = teaches.ID AND instructor.
▶ Aggregate
▶ Modification of DB
dept_name = ‘Art’
Functions
▶ Set Operations
where T.salary > S.salary AND S.dept_name =
▶ Null Values ‘Comp. Sci.’
▶ Aggregate
▶ Modification of DB
Functions
• Keyword AS is optional and may be omitted
instructor AS T ≡ instructor T
Soft.Eng Program @ SoCI, WCU 19
Course SEng4031: Advanced Database Systems Lesson Introduction to SQL
▶ Query Structure
Select Clause
Where Clause
From Clause
String Operations
INDEX • SQL includes a string-matching operator for comparisons
▶ Overview of SQL
▶ Data Definition
on character strings. The operator like uses patterns
Domain Types that are described using two special characters:
Create Table
Updates to Table
• percent ( % ). The % character matches any substring.
▶ Query Structure
• underscore ( _ ). The _ character matches any character.
Select Clause
Where Clause
• Find the names of all instructors whose name includes
From Clause the substring “dar”.
▶ More Basic Ops
SELECT name
Rename Operation
String Operations
FROM instructor
Ordering WHERE name like '%dar%'
Duplicates
String Operations …
INDEX
▶ Overview of SQL
• Patterns are case sensitive.
▶ Data Definition
Domain Types
• Pattern matching examples:
Create Table • ‘Intro%’ matches any string beginning with “Intro”.
Updates to Table
▶ Query Structure
• ‘%Comp%’ matches any string containing “Comp” as a
Select Clause
substring.
Where Clause • ‘_ _ _’ matches any string of exactly three characters.
From Clause
Duplicates
INDEX
▶ Overview of SQL
• In relations with duplicates, SQL can define how
▶ Data Definition many copies of tuples appear in the result.
Domain Types
Create Table • Multiset versions of some of the relational algebra
operators – given multiset relations r1 and r2:
Updates to Table
▶ Query Structure
Select Clause 1. (r1): If there are c1 copies of tuple t1 in r1, and t1
Where Clause
From Clause satisfies selections ,, then there are c1 copies of t1 in
▶ More Basic Ops (r1).
Rename Operation
String Operations 2. A (r ): For each copy of tuple t1 in r1, there is a copy of
Ordering tuple A (t1) in A (r1) where A (t1) denotes the
Duplicates
▶ Set Operations
projection of the single tuple t1.
▶ Null Values
3. r1 x r2: If there are c1 copies of tuple t1 in r1 and c2
▶ Aggregate
▶ Modification of DB copies of tuple t2 in r2, there are c1 x c2 copies of the
Functions
tuple t1. t2 in r1 x r2
Duplicates
INDEX
▶ Overview of SQL
• Example: Suppose multiset relations r1 (A, B) and r2 (C)
▶ Data Definition are as follows:
Domain Types
Create Table r1 = {(1, a) (2,a)} r2 = {(2), (3), (3)}
Updates to Table
▶ Query Structure • Then B(r1) would be {(a), (a)}, while B(r1) x r2 would
Select Clause
Where Clause
be
From Clause {(a,2), (a,2), (a,3), (a,3), (a,3), (a,3)}
▶ More Basic Ops
Rename Operation • SQL duplicate semantics:
String Operations
Ordering select A1,, A2, ..., An
Duplicates
▶ Set Operations
from r1, r2, ..., rm
▶ Null Values where P
A1to , An ( P ( r1 r2version
rmof))the expression:
▶ Aggregate
▶ Modification of DB is equivalent the
, A2 , multiset
Functions
Set Operations
INDEX • Find courses that ran in Fall 2009 or in Spring 2010
▶ Overview of SQL
▶ Data Definition
• (SELECT course_id FROM section WHERE sem = ‘Fall’ AND year =
Domain Types
2009)
Create Table
UNION
Updates to Table
(SELECT course_id FROM section WHERE sem = ‘Spring’ AND year =
2010)
▶ Query Structure
Select Clause • Find courses that ran in Fall 2009 and in Spring 2010
Where Clause
• (SELECT course_id FROM section WHERE sem = ‘Fall’ AND year =
From Clause
2009)
▶ More Basic Ops INTERSECT
Rename Operation (SELECT course_id FROM section WHERE sem = ‘Spring’ AND year =
String Operations 2010)
Ordering
Duplicates • Find courses that ran in Fall 2009 but not in Spring 2010
▶ Set Operations • (SELECT course_id FROM section WHERE sem = ‘Fall’ AND year =
▶ Null Values 2009)
▶ Aggregate EXCEPT
▶ Modification of DB (SELECT course_id FROM section WHERE sem = ‘Spring’ AND year =
Functions 2010)
Set Operations …
INDEX
▶ Overview of SQL
• Find the salaries of all instructors that are less
▶ Data Definition than the largest salary.
Domain Types
Create Table
• SELECT DISTINCT T.salary
Updates to Table FROM instructor AS T, instructor AS S
▶ Query Structure where T.salary < S.salary
Select Clause
Where Clause
From Clause
▶ Set Operations
▶ Null Values • Find the largest salary of all instructors.
▶ Aggregate
▶ Modification of DB
• (SELECT “second query” )
Functions EXCEPT
(SELECT “first query”)
Soft.Eng Program @ SoCI, WCU 28
Course SEng4031: Advanced Database Systems Lesson Introduction to SQL
▶ Query Structure
Select Clause
Where Clause
multiset versions union all, intersect all and
From Clause except all.
▶ More Basic Ops
Rename Operation • Suppose a tuple occurs m times in r and n
String Operations
Ordering
times in s, then, it occurs:
Duplicates
• m + n times in r union all s
▶ Set Operations
▶ Null Values • min(m,n) times in r intersect all s
▶ Aggregate
▶ Modification of DB • max(0, m – n) times in r except all s
Functions
NULL Values
INDEX
▶ Overview of SQL
• It is possible for tuples to have a null value,
▶ Data Definition denoted by NULL, for some of their attributes
Domain Types
Create Table • NULL signifies an unknown value or that a value
Updates to Table
▶ Query Structure
does not exist.
Select Clause
Where Clause
• The result of any arithmetic expression involving
From Clause NULL is NULL
▶ More Basic Ops
• Example: 5 + NULL returns NULL
Rename Operation
String Operations • The predicate IS NULL can be used to check for
null values.
Ordering
Duplicates
▶ Query Structure
• Three-valued logic using the value unknown:
Select Clause • OR: (unknown or true) = true,
Where Clause (unknown or false) = unknown
From Clause
(unknown or unknown) = unknown
▶ More Basic Ops
Rename Operation
• AND: (true and unknown) = unknown,
String Operations (false and unknown) = false,
Ordering (unknown and unknown) = unknown
Duplicates
• NOT: (not unknown) = unknown
▶ Set Operations
▶ Null Values
• “P is unknown” evaluates to true if predicate P evaluates
▶ Aggregate to unknown
▶ Modification of DB
Functions • Result of where clause predicate is treated as false if
it evaluates to unknown
Soft.Eng Program @ SoCI, WCU 31
Course SEng4031: Advanced Database Systems Lesson Introduction to SQL
Practice Exercises
INDEX
▶ Overview of SQL
• Use the University Database and Write SQL
▶ Data Definition Queries for the following
Domain Types
Create Table • Find the IDs of all students who were taught by an
Updates to Table
instructor named
▶ Query Structure
Select Clause
Einstein; make sure there are no duplicates in the
Where Clause result.
From Clause
▶ Set Operations
▶ Null Values
▶ Aggregate
▶ Modification of DB
Functions
More Practice
INDEX
▶ Overview of SQL
• Use the Bank Database from the Previous
▶ Data Definition Lesson
Domain Types
Create Table • Find all customers of the bank who have an
Updates to Table
account but not a loan.
▶ Query Structure
Select Clause • Find the names of all customers who live on the
Where Clause
same street and in the same city as “Smith”.
From Clause
▶ More Basic Ops • Find the names of all branches with customers
Rename Operation who have an account
String Operations
Ordering
in the bank and who live in “Harrison”.
Duplicates
▶ Set Operations
▶ Null Values
▶ Aggregate
▶ Modification of DB
Functions
Aggregate Functions
INDEX
▶ Overview of SQL
• These functions operate on the multiset of
▶ Data Definition values of a column of a relation, and return a
value
Domain Types
Create Table
Updates to Table
▶ Query Structure
avg: average value
Select Clause min: minimum value
Where Clause
From Clause max: maximum value
▶ More Basic Ops
sum: sum of values
Rename Operation
String Operations count: number of values
Ordering
Duplicates
▶ Set Operations
▶ Null Values
▶ Aggregate
▶ Modification of DB
Functions
Aggregate Functions …
INDEX
▶ Overview of SQL
• Find the average salary of instructors in the
▶ Data Definition Computer Science department
Domain Types
Create Table • SELECT AVG (salary)
Updates to Table FROM instructor
▶ Query Structure
Select Clause
WHERE dept_name= ’Comp. Sci.’;
Where Clause
From Clause
• Find the total number of instructors who teach
▶ More Basic Ops a course in the Spring 2010 semester
Rename Operation
String Operations
• SELECT COUNT (DISTINCT ID)
Ordering FROM teaches
Duplicates
WHERE semester = ’Spring’ AND year = 2010;
▶ Set Operations
▶ Null Values • Find the number of tuples in the course relation
▶ Aggregate
▶ Modification of DB • SELECT COUNT (*)
Functions
FROM course;
Group By Clause
INDEX
▶ Overview of SQL
• Find the average salary of instructors in each
▶ Data Definition department
Domain Types
Create Table • SELECT dept_name, AVG (salary) AS avg_salary
Updates to Table
FROM instructor
▶ Query Structure
Select Clause
GROUP BY dept_name;
Where Clause
From Clause
▶ Set Operations
▶ Null Values
▶ Aggregate
▶ Modification of DB
Functions
Having Clause
INDEX
▶ Overview of SQL
• Find the names and average salaries of all
▶ Data Definition departments whose average salary is greater
than 42000
Domain Types
Create Table
Updates to Table SELECT dept_name, AVG (salary)
▶ Query Structure FROM instructor
Select Clause
GROUP BY dept_name
Where Clause
From Clause
HAVING AVG (salary) > 42000;
▶ More Basic Ops
Rename Operation
• Note: predicates in the having clause are
String Operations applied after the formation of groups whereas
Ordering
Duplicates
predicates in the where clause are applied
▶ Set Operations before forming groups
▶ Null Values
▶ Aggregate
▶ Modification of DB
Functions
▶ Set Operations
▶ Null Values
• count returns 0
▶ Aggregate • all other aggregates return null
▶ Modification of DB
Functions
Modification of Database
INDEX
▶ Overview of SQL
• Deletion of tuples from a given relation.
▶ Data Definition
Domain Types
• Insertion of new tuples into a given relation
Create Table
Updates to Table • Updating of values in some tuples in a given
▶ Query Structure
Select Clause
relation
Where Clause
From Clause
▶ Set Operations
▶ Null Values
▶ Aggregate
▶ Modification of DB
Functions
Deletion
INDEX
▶ Overview of SQL
• Delete all instructors
▶ Data Definition DELETE FROM instructor
Domain Types
Create Table
Updates to Table
• Delete all instructors from the Finance
▶ Query Structure department
Select Clause
Where Clause
DELETE FROM instructor
From Clause WHERE dept_name= ’Finance’;
▶ More Basic Ops
Rename Operation
• Delete all tuples in the instructor relation for
String Operations those instructors associated with a department
located in the Watson building.
Ordering
Duplicates
▶ Set Operations
▶ Null Values
DELETE FROM instructor
▶ Aggregate WHERE dept name IN (SELECT dept name
▶ Modification of DB
Functions FROM department
WHERE building = ’Watson’);
Soft.Eng Program @ SoCI, WCU 40
Course SEng4031: Advanced Database Systems Lesson Introduction to SQL
Deletion
INDEX
▶ Overview of SQL
• Delete all instructors whose salary is less than
▶ Data Definition the average salary of instructors
Domain Types
Create Table DELETE FROM instructor
WHERE salary < (SELECT AVG (salary)
Updates to Table
▶ Query Structure
Select Clause FROM instructor);
Where Clause
From Clause • Problem: as we delete tuples from deposit,
the average salary changes
▶ More Basic Ops
Rename Operation
▶ Set Operations
▶ Null Values delete
▶ Aggregate
▶ Modification of DB
2. Next, delete all tuples found above (without re-
Functions
computing AVG or retesting the tuples)
Insertion
INDEX
▶ Overview of SQL
• Add a new tuple to course
▶ Data Definition
INSERT INTO course
Domain Types
Create Table VALUES (’CS-437’, ’Database Systems’, ’Comp. Sci.’,
Updates to Table
4);
▶ Query Structure
Select Clause
Where Clause
• or equivalently
From Clause INSERT INTO course (course_id, title, dept_name,
▶ More Basic Ops
credits) VALUES (’CS-437’, ’Database Systems’,
’Comp. Sci.’, 4);
Rename Operation
String Operations
▶ Set Operations
▶ Null Values
to null
▶ Aggregate INSERT INTO student VALUES (’3003’, ’Green’,
▶ Modification of DB
Functions ’Finance’, null);
Insertion
INDEX
▶ Overview of SQL
• Add all instructors to the student relation
▶ Data Definition with tot_creds set to 0
Domain Types
Create Table INSERT INTO student
SELECT ID, name, dept_name, 0
Updates to Table
▶ Query Structure
Select Clause FROM instructor
Where Clause
From Clause • The SELECT FROM WHERE statement is
evaluated fully before any of its results are
▶ More Basic Ops
Rename Operation
String Operations
Ordering
inserted into the relation.
Duplicates
▶ Set Operations
Otherwise queries like
▶ Null Values
▶ Aggregate
INSERT INTO table1 SELECT * FROM table1
would cause problem
▶ Modification of DB
Functions
Updates
INDEX
▶ Overview of SQL
• Increase salaries of instructors whose salary is
▶ Data Definition over $100,000 by 3%, and all others by a 5%
Domain Types
Create Table • Write two UPDATE statements:
UPDATE instructor
Updates to Table
▶ Query Structure
Select Clause SET salary = salary * 1.03WHERE salary > 100000
Where Clause
From Clause UPDATE instructor
▶ More Basic Ops
SET salary = salary * 1.05
Rename Operation
String Operations WHERE salary <= 100000;
Ordering
Duplicates • The order is important
▶ Set Operations
▶ Null Values
▶ Aggregate
▶ Modification of DB
Functions
Practice Problems
INDEX
▶ Overview of SQL
SELECT course id, semester, year, sec id, AVG
▶ Data Definition (tot cred)
FROM takes NATURAL JOIN student
Domain Types
Create Table
Updates to Table
▶ Query Structure
WHERE year = 2009
Select Clause GROUP BY course id, semester, year, sec id
Where Clause
From Clause
HAVING COUNT (ID) >= 2;
▶ More Basic Ops
Rename Operation
String Operations
Ordering
Explain why joining section as well in the from
Duplicates clause would not change
▶ Set Operations
▶ Null Values
the result.
▶ Aggregate
▶ Modification of DB
Functions
More Practice
INDEX • Using University Database Write queries for the following
▶ Overview of SQL
▶ Data Definition • Create a new course “SE-001”, titled “Weekly Seminar”, with 0
Domain Types credits.
Create Table • Create a section of this course in Autumn 2022, with sec id of
Updates to Table
1.
▶ Query Structure
Select Clause
• Enroll every student in the Soft.Engineering department in the
Where Clause above section.
From Clause • Delete enrolments in the above section where the student’s
▶ More Basic Ops name is Ebtihal.
Rename Operation
• Delete the course CS-001. What will happen if you run this
String Operations
Ordering
delete statement without first deleting offerings (sections) of
Duplicates this course.
▶ Set Operations • Delete all takes tuples corresponding to any section of any
▶ Null Values course with the word “database” as a part of the title; ignore
▶ Aggregate case when matching the word with the title.
▶ Modification of DB
Functions