0% found this document useful (0 votes)
17 views46 pages

WCU Lab Exercise

This document provides an introduction to the SQL language, including: 1) A brief history of SQL and its standards. 2) An overview of the SQL data definition language for specifying schema, domains, and integrity constraints. 3) Examples of creating tables with attributes of different domains, primary keys, and foreign keys.

Uploaded by

Seyo Kasaye
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views46 pages

WCU Lab Exercise

This document provides an introduction to the SQL language, including: 1) A brief history of SQL and its standards. 2) An overview of the SQL data definition language for specifying schema, domains, and integrity constraints. 3) Examples of creating tables with attributes of different domains, primary keys, and foreign keys.

Uploaded by

Seyo Kasaye
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 46

SEng4031 Advanced Database Systems

Introduction to SQL

Software Engineering Program


School of Computing and Informatics

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

▶ Set Operations • Commercial systems offer most, if not all, SQL-92


▶ Null Values features, plus varying feature sets from later
▶ Aggregate
▶ Modification of DB standards and special proprietary features.
Functions
• Not all examples here may work on your particular
system
Soft.Eng Program @ SoCI, WCU 2
Course SEng4031: Advanced Database Systems Lesson Introduction to SQL

Data Definition Language


INDEX
▶ Overview of SQL
• The SQL data-definition language (DDL)
▶ Data Definition
Domain Types
allows the specification of information about
Create Table relations, including:
Updates to Table

▶ 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.

Soft.Eng Program @ SoCI, WCU 3


Course SEng4031: Advanced Database Systems Lesson Introduction to SQL

Domain Types in SQL


INDEX • char(n). Fixed length character string, with user-specified
▶ Overview of SQL
length n.
▶ Data Definition
Domain Types • varchar(n). Variable length character strings, with user-
Create Table specified maximum length n.
Updates to Table

▶ 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

▶ More Basic Ops


integer domain type).
Rename Operation • numeric(p,d). Fixed point number, with user-specified
String Operations precision of p digits, with d digits to the right of decimal point.
Ordering
Duplicates
(ex., numeric(3,1), allows 44.5 to be stores exactly, but not
▶ Set Operations
444.5 or 0.32)
▶ Null Values • real, double precision. Floating point and double-precision
▶ Aggregate floating point numbers, with machine-dependent precision.
▶ Modification of DB
Functions • float(n). Floating point number, with user-specified precision of
at least n digits.
Soft.Eng Program @ SoCI, WCU 4
Course SEng4031: Advanced Database Systems Lesson Introduction to SQL

Create Table Construct


INDEX • An SQL relation is defined using the create table command:
▶ Overview of SQL
▶ Data Definition CREATE TABLE r (A1 D1, A2 D2, ..., An Dn,
Domain Types
Create Table
(integrity-constraint1),
Updates to Table ...,
▶ Query Structure (integrity-constraintk))
Select Clause
• r is the name of the relation
Where Clause
From Clause • each Ai is an attribute name in the schema of relation r
▶ More Basic Ops • Di is the data type of values in the domain of attribute Ai
Rename Operation
String Operations
Ordering • Example:
Duplicates

▶ 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

More Relation Definitions


INDEX • CREATE TABLE student (
▶ Overview of SQL
▶ Data Definition
ID varchar(5),
Domain Types Name varchar(20) not null,
Create Table dept_name varchar(20),
Updates to Table tot_cred numeric(3,0),
▶ Query Structure PRIMARY KEY (ID),
Select Clause
FOREIGN KEY (dept_name) REFERENCES department);
Where Clause
From Clause
• CREATE TABLE takes (
▶ More Basic Ops ID varchar(5),
Rename Operation course_id varchar(8),
String Operations sec_id varchar(8),
Ordering Semester varchar(6),
Duplicates
Year numeric(4,0),
▶ Set Operations
▶ Null Values
Grade varchar(2),
▶ Aggregate
PRIMARY KEY (ID, course_id, sec_id, semester, year) ,
▶ Modification of DB FOREIGN KEY (ID) REFERENCES student(ID),
Functions
FOREIGN KEY (course_id, sec_id, semester, year) REFERENCES
section (course_id, sec_id, semester, year) );
Soft.Eng Program @ SoCI, WCU 7
Course SEng4031: Advanced Database Systems Lesson Introduction to SQL

More Relation Definitions …


INDEX
▶ Overview of SQL
• CREATE TABLE course (
▶ Data Definition
course_id varchar(8),
Domain Types
Create Table Title varchar(50),
dept_name varchar(20),
Updates to Table

▶ 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

Soft.Eng Program @ SoCI, WCU 8


Course SEng4031: Advanced Database Systems Lesson Introduction to SQL

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

Basic Query Structure


INDEX
▶ Overview of SQL
• A typical SQL query has the form:
▶ Data Definition
Domain Types
Create Table SELECT A1, A2, ..., An
Updates to Table

▶ Query Structure FROM r1, r2, ..., rm


Select Clause
Where Clause
WHERE P
From Clause

▶ More Basic Ops


Rename Operation • Ai represents an attribute
String Operations
Ordering
• Ri represents a relation
Duplicates

▶ Set Operations
• P is a predicate.
▶ Null Values
▶ Aggregate
• The result of an SQL query is a relation.
▶ Modification of DB
Functions

Soft.Eng Program @ SoCI, WCU 10


Course SEng4031: Advanced Database Systems Lesson Introduction to SQL

The SELECT Clause


INDEX
▶ Overview of SQL
• The SELECT clause lists the attributes desired
▶ Data Definition in the result of a query
Domain Types
Create Table • corresponds to the projection operation of the
Updates to Table
relational algebra
▶ Query Structure
Select Clause
Where Clause
• Example: find the names of all instructors:
From Clause

▶ More Basic Ops


SELECT name
Rename Operation
String Operations
FROM instructor
Ordering
Duplicates
• NOTE: SQL names are case insensitive (i.e.,
▶ Set Operations you may use upper- or lower-case letters.)
▶ Null Values
▶ Aggregate • E.g., Name ≡ NAME ≡ name
▶ Modification of DB
Functions • Some people use upper case wherever we use
bold font.
Soft.Eng Program @ SoCI, WCU 11
Course SEng4031: Advanced Database Systems Lesson Introduction to SQL

The SELECT Clause …


INDEX
▶ Overview of SQL
• SQL allows duplicates in relations as well as in
▶ Data Definition query results.
Domain Types
Create Table • To force the elimination of duplicates, insert
Updates to Table

▶ Query Structure the keyword distinct after select.


Select Clause
Where Clause • Find the department names of all instructors,
From Clause

▶ More Basic Ops


and remove duplicates
Rename Operation
String Operations
SELECT DISTINCT dept_name
Ordering FROM instructor
Duplicates

▶ Set Operations • The keyword all specifies that duplicates should


▶ Null Values
▶ Aggregate
not be removed.
▶ Modification of DB
Functions SELECT ALL dept_name
FROM instructor
Soft.Eng Program @ SoCI, WCU 12
Course SEng4031: Advanced Database Systems Lesson Introduction to SQL

The SELECT Clause …


INDEX • An asterisk in the select clause denotes “all
▶ Overview of SQL
▶ Data Definition attributes”
SELECT *
Domain Types
Create Table
Updates to Table FROM instructor
▶ Query Structure
Select Clause • An attribute can be a literal with no from clause
SELECT ‘437’
Where Clause
From Clause

▶ 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

The SELECT Clause …


INDEX
▶ Overview of SQL
• The SELECT clause can contain arithmetic
▶ Data Definition expressions involving the operation, +, –, ,
and /, and operating on constants or
Domain Types
Create Table
Updates to Table

▶ 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

Soft.Eng Program @ SoCI, WCU 14


Course SEng4031: Advanced Database Systems Lesson Introduction to SQL

The WHERE Clause


INDEX • The WHERE clause specifies conditions that the result
▶ Overview of SQL
▶ Data Definition
must satisfy
Domain Types • Corresponds to the selection predicate of the relational algebra.
Create Table
Updates to Table
• To find all instructors in Comp. Sci. dept
▶ Query Structure SELECT name
Select Clause
Where Clause
FROM instructor
From Clause WHERE dept_name = ‘Comp. Sci.'
▶ More Basic Ops
• Comparison results can be combined using the logical
Rename Operation
String Operations
connectives and, or, and not
Ordering • To find all instructors in Comp. Sci. dept with salary > 80000
Duplicates
SELECT name
▶ Set Operations FROM instructor
▶ Null Values
WHERE dept_name = ‘Comp. Sci.' and salary > 80000
▶ Aggregate
▶ Modification of DB • Comparisons can be applied to results of arithmetic
Functions
expressions

Soft.Eng Program @ SoCI, WCU 15


Course SEng4031: Advanced Database Systems Lesson Introduction to SQL

The FROM Clause


INDEX • The FROM clause lists the relations involved in the
▶ Overview of SQL
▶ Data Definition query
Domain Types • Corresponds to the Cartesian product operation of the
Create Table
Updates to Table
relational algebra.
▶ Query Structure • Find the Cartesian product instructor X teaches
Select Clause
Where Clause SELECT 
From Clause
FROM instructor, teaches
▶ More Basic Ops
Rename Operation
• generates every possible instructor – teaches pair, with all
String Operations attributes from both relations.
Ordering
• For common attributes (e.g., ID), the attributes in the
Duplicates

▶ 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

Cartesian Product teaches


INDEX
▶ Overview of SQL
Instructor Teaches
▶ Data Definition
Domain Types
Create Table
Updates to Table

▶ Query Structure
Select Clause
Where Clause
From Clause

▶ More Basic Ops


Rename Operation
String Operations
Ordering
Duplicates

▶ Set Operations
▶ Null Values
▶ Aggregate
▶ Modification of DB
Functions

Soft.Eng Program @ SoCI, WCU 17


Course SEng4031: Advanced Database Systems Lesson Introduction to SQL

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

Soft.Eng Program @ SoCI, WCU 18


Course SEng4031: Advanced Database Systems Lesson Introduction to SQL

The Rename Operation


INDEX
▶ Overview of SQL
• The SQL allows renaming relations and
▶ Data Definition attributes using the as clause:
Domain Types
Create Table • old-name as new-name
Updates to Table

▶ Query Structure • Find the names of all instructors who have a


Select Clause
Where Clause
higher salary than some instructor in ‘Comp.
From Clause Sci’.
▶ More Basic Ops
Rename Operation • SELECT DISTINCT T.name
FROM instructor AS T, instructor AS S
String Operations
Ordering
Duplicates

▶ 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

Cartesian Product Example


INDEX • Relation emp-super
▶ Overview of SQL
▶ Data Definition
Domain Types
• Cartesian Product Example
Create Table
Updates to Table

▶ Query Structure
Select Clause
Where Clause
From Clause

▶ More Basic Ops


Rename Operation
String Operations • Find the supervisor of “Bob”
Ordering
Duplicates • Find the supervisor of the supervisor of “Bob”
▶ Set Operations
• SELECT f.supervisor FROM employee e, employee f WHERE
▶ Null Values
▶ Aggregate
e.person = 'Bob' And e.supervisor = f.person
▶ Modification of DB
Functions • Find ALL the supervisors (direct and indirect) of
“Bob
Soft.Eng Program @ SoCI, WCU 20
Course SEng4031: Advanced Database Systems Lesson Introduction to SQL

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

▶ Set Operations • Match the string “100%”


▶ Null Values
▶ Aggregate
like ‘100 \%' escape '\'
▶ Modification of DB
Functions
in that above we use backslash (\) as the escape
character.
Soft.Eng Program @ SoCI, WCU 21
Course SEng4031: Advanced Database Systems Lesson Introduction to SQL

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

▶ More Basic Ops


• ‘_ _ _ %’ matches any string of at least three
Rename Operation characters.
String Operations
Ordering
Duplicates
• SQL supports a variety of string operations such as
▶ Set Operations
▶ Null Values • concatenation (using “||”)
▶ Aggregate • converting from upper to lower case (and vice versa)
▶ Modification of DB
Functions • finding string length, extracting substrings, etc.

Soft.Eng Program @ SoCI, WCU 22


Course SEng4031: Advanced Database Systems Lesson Introduction to SQL

Ordering the Display of Tuples


INDEX
▶ Overview of SQL
• List in alphabetic order the names of all
▶ Data Definition instructors
Domain Types
Create Table SELECT DISTINCT name
Updates to Table
FROM instructor
▶ Query Structure
Select Clause ORDER BY name
Where Clause
From Clause • We may specify desc for descending order or
▶ More Basic Ops
Rename Operation
asc for ascending order, for each attribute;
String Operations ascending order is the default.
Ordering
Duplicates • Example: ORDER BY name DESC
▶ Set Operations
▶ Null Values • Can sort on multiple attributes
▶ Aggregate
▶ Modification of DB
• Example: ORDER BY dept_name, name
Functions

Soft.Eng Program @ SoCI, WCU 23


Course SEng4031: Advanced Database Systems Lesson Introduction to SQL

Where Clause Predicates


INDEX
▶ Overview of SQL
• SQL includes a between comparison operator
▶ Data Definition
Domain Types
• Example: Find the names of all instructors
Create Table
Updates to Table
with salary between $90,000 and $100,000
▶ Query Structure (that is,  $90,000 and  $100,000)
Select Clause
Where Clause
• SELECT name
From Clause FROM instructor
▶ More Basic Ops
WHERE salary BETWEEN 90000 AND 100000
Rename Operation
String Operations
Ordering
• Tuple comparison
Duplicates • SELECT name, course_id
▶ Set Operations
▶ Null Values
FROM instructor, teaches
▶ Aggregate WHERE (instructor.ID, dept_name) = (teaches.ID,
▶ Modification of DB
Functions
’Biology’);

Soft.Eng Program @ SoCI, WCU 24


Course SEng4031: Advanced Database Systems Lesson Introduction to SQL

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

Soft.Eng Program @ SoCI, WCU 25


Course SEng4031: Advanced Database Systems Lesson Introduction to SQL

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

Soft.Eng Program @ SoCI, WCU 26


Course SEng4031: Advanced Database Systems Lesson Introduction to SQL

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)

Soft.Eng Program @ SoCI, WCU 27


Course SEng4031: Advanced Database Systems Lesson Introduction to SQL

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

▶ More Basic Ops


• Find all the salaries of all instructors
Rename Operation • SELECT DISTINCT salary
String Operations
Ordering
FROM instructor
Duplicates

▶ 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

Set Operations (Cont.)


INDEX
▶ Overview of SQL
• Set operations union, intersect, and except
▶ Data Definition • Each of the above operations automatically
eliminates duplicates
Domain Types
Create Table

• To retain all duplicates use the corresponding


Updates to Table

▶ 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

Soft.Eng Program @ SoCI, WCU 29


Course SEng4031: Advanced Database Systems Lesson Introduction to SQL

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

▶ Set Operations • Example: Find all instructors whose salary is null.


▶ Null Values
▶ Aggregate SELECT name
▶ Modification of DB
Functions FROM instructor
WHERE salary IS NULL
Soft.Eng Program @ SoCI, WCU 30
Course SEng4031: Advanced Database Systems Lesson Introduction to SQL

Three Valued Logic


INDEX • Three values – true, false, unknown
▶ Overview of SQL
▶ Data Definition • Any comparison with null returns unknown
Domain Types
Create Table
• Example: 5 < null or null <> null or null = null
Updates to Table

▶ 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

▶ More Basic Ops


• Find all instructors earning the highest salary
Rename Operation (there may be more
String Operations
than one with the same salary)
Ordering
Duplicates

▶ Set Operations
▶ Null Values
▶ Aggregate
▶ Modification of DB
Functions

Soft.Eng Program @ SoCI, WCU 32


Course SEng4031: Advanced Database Systems Lesson Introduction to SQL

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

Soft.Eng Program @ SoCI, WCU 33


Course SEng4031: Advanced Database Systems Lesson Introduction to SQL

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

Soft.Eng Program @ SoCI, WCU 34


Course SEng4031: Advanced Database Systems Lesson Introduction to SQL

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;

Soft.Eng Program @ SoCI, WCU 35


Course SEng4031: Advanced Database Systems Lesson Introduction to SQL

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

▶ More Basic Ops


Rename Operation
String Operations
Ordering
Duplicates

▶ Set Operations
▶ Null Values
▶ Aggregate
▶ Modification of DB
Functions

Soft.Eng Program @ SoCI, WCU 36


Course SEng4031: Advanced Database Systems Lesson Introduction to SQL

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

Soft.Eng Program @ SoCI, WCU 37


Course SEng4031: Advanced Database Systems Lesson Introduction to SQL

Null Values and Aggregates


INDEX
▶ Overview of SQL
• Total all salaries
▶ Data Definition SELECT SUM (salary )
Domain Types
FROM instructor
Create Table
Updates to Table • Above statement ignores null amounts
▶ Query Structure
Select Clause
• Result is null if there is no non-null amount
Where Clause
From Clause
• All aggregate operations except COUNT(*)
▶ More Basic Ops ignore tuples with null values on the
Rename Operation
String Operations
aggregated attributes
• What if collection has only null values?
Ordering
Duplicates

▶ Set Operations
▶ Null Values
• count returns 0
▶ Aggregate • all other aggregates return null
▶ Modification of DB
Functions

Soft.Eng Program @ SoCI, WCU 38


Course SEng4031: Advanced Database Systems Lesson Introduction to SQL

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

▶ More Basic Ops


Rename Operation
String Operations
Ordering
Duplicates

▶ Set Operations
▶ Null Values
▶ Aggregate
▶ Modification of DB
Functions

Soft.Eng Program @ SoCI, WCU 39


Course SEng4031: Advanced Database Systems Lesson Introduction to SQL

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

• Solution used in SQL:


String Operations
Ordering

1. First, compute AVG (salary) and find all tuples to


Duplicates

▶ 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)

Soft.Eng Program @ SoCI, WCU 41


Course SEng4031: Advanced Database Systems Lesson Introduction to SQL

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

• Add a new tuple to student with tot_creds set


Ordering
Duplicates

▶ Set Operations
▶ Null Values
to null
▶ Aggregate INSERT INTO student VALUES (’3003’, ’Green’,
▶ Modification of DB
Functions ’Finance’, null);

Soft.Eng Program @ SoCI, WCU 42


Course SEng4031: Advanced Database Systems Lesson Introduction to SQL

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

Soft.Eng Program @ SoCI, WCU 43


Course SEng4031: Advanced Database Systems Lesson Introduction to SQL

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

Soft.Eng Program @ SoCI, WCU 44


Course SEng4031: Advanced Database Systems Lesson Introduction to SQL

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

Soft.Eng Program @ SoCI, WCU 45


Course SEng4031: Advanced Database Systems Lesson Introduction to SQL

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

Soft.Eng Program @ SoCI, WCU 46

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy