QL SQL1 4

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

SQL Overview (cont)

Data definition component


• CREATE TABLE table-name (col-defs, constraints)
• DROP TABLE table-name
SQL - Basics • ALTER TABLE table-name action
modifies the definition of a table where action is
ADD (col-def)
MODIFY (col-def)
Davood Rafiei ADD costraint
etc.
Data update component
• INSERT INTO table-name …
• DELETE FROM table-name …
• UPDATE table-name …
Query Language
1 3

SQL Overview Example Tables


Structured Query Language branch (bname, address, city, assets)
• standard query language for relational system. customer(cname, street, city)
• developed in IBM Almaden (system R) deposit(accno, cname, bname, balance)
Some features loan(accno, cname, bname, amount)
• Declarative: specify the properties that should hold
in the result, not how to obtain the result
• Complex queries have procedural elements CREATE TABLE branch (
Oracle command
• Set/Bag semantics bname CHAR(20),
address CHAR(30), (in Oracle, a semicolon
International Standards city CHAR(15), always marks the end of a
• SQL1 (1986) asset NUMBER(38) SQL statement.)
• SQL2 (SQL-92) );
• SQL3 (pieces have started to appear)

2 4
Simple Queries Queries With Tuple Variables
branch (bname, address, city, assets) loan(accno, cname, bname, amount)
deposit(accno, cname, bname, balance)
Find the names of all branches with assets
greater than $2,500,000. Find customers who have both loans and deposits.
SELECT bname
FROM branch SELECT loan.cname
WHERE assets > 2500000 FROM loan, deposit
WHERE loan.cname = deposit.cname

Find the names of all branches in Edmonton Equivalently using tuple variables:
with assets greater than $2,500,000.
SELECT bname SELECT l.cname
FROM branch FROM loan l, deposit d
WHERE l.cname = d.cname
WHERE assets>2500000 AND city=‘Edmonton’

Range variables are really needed if the same relation


Simple predicates can be combined using appears twice in the FROM clause.
AND, OR, NOT.
5 7

Querying two Relations A Simple Evaluation Alg.


SELECT …
customer(cname, street, city)
FROM R1 r1, R2 r2, …
deposit(accno, cname, bname, balance) WHERE C
Tuple variables r1, r2, … respectively range over rows of R1, R2, ...
..
List the name and the city of every customer who has Evaluation strategy:
an account with balance over $2,000. • FROM clause produces Cartesian product of listed tables
• WHERE clause produces table containing only rows satisfying condition
SELECT customer.cname, city • SELECT clause retains listed columns
FROM customer, deposit
WHERE balance > 2000
AND customer.cname = deposit.cname for every tuple r1 in R1, r2 in R2, …
let r := r1, r2, …
if C(r) then
output the desired columns
6 8
Duplicates
From SQL to Relational Algebra
SELECT l.cname
Duplicate rows not allowed in a relation
FROM loan l, deposit d
WHERE l.cname = d.cname
However, duplicate elimination from query result
is costly and not automatically done; it must be
explicitly requested:
Equivalent to:
temp = loan × deposit [a1,cn1,bn1,b1,a2,cn2,bn2,a2]
πcn1 σcn1 = cn2 (temp)
SELECT DISTINCT …..
This is a simple evaluation algorithm for SELECT. FROM …..

9 11

Queries With Set/Bag Results Working with Strings

Find all cities of customers. Equality and comparison operators apply to


• SELECT city strings (based on lexical ordering)
FROM customer WHERE cname < ‘P’
Result? Concatenate operator applies to strings
WHERE bname || ‘--’ || address = ….
To get rid of duplicates, we need
Expressions can also be used in SELECT clause:
• SELECT DISTINCT city
FROM customer SELECT bname || ‘--’ || address AS NameAdd
FROM branch

10 12
Working with Strings (cont) Ordering the Results
customer(cname, street, city) branch (bname, address, city, assets)
Find the names and assets of all
Find every customer whose address starts branches with assets greater than
with “Computing Science”. $2,500,000 and order the result in
SELECT *
FROM customer ascending order of asset values.
WHERE address LIKE ‘Computing Science%’
SELECT bname, assets
Expression: col-name [NOT] LIKE pattern FROM branch
• Pattern may include wildcard characters ‘%’ WHERE assets > 2500000
matching any string and ‘_’ (underscore) matching ORDER BY assets
any single character.

Default is ascending order; a descending


order can be specified by the DESC keyword.
13 15

Naming the Results Queries Involving Set Operators

deposit(accno, cname, bname, balance) set union : Q1 UNION Q2


• the set of tuples in Q1 or Q2
set difference : Q1 MINUS Q2
For every deposit holder who has over
• the set of tuples in Q1 but not in Q2
$1000, find the customer name and the
balance over $1000. set intersection : Q1 INTERSECT Q2
SELECT cname, (balance - 1000)as bal • the set of tuples in both Q1 and Q2
FROM deposit
WHERE balance > 1000
Q1 and Q2 must be union-compatibles
• same number/types of attributes.

14 16
Queries With Set Operators Queries Over Multiple Relations
List deposit-holders who have no loans.
branch (bname, address, city, assets)
(SELECT cname
FROM deposits) customer(cname, street, city)
deposit(accno, cname, bname, balance)
MINUS

(SELECT cname SELECT brach.bname, assets


FROM loan) FROM branch,customer,deposit
List cities where there is either a customer or WHERE customer.city = ‘Jasper’
a branch. AND customer.cname = deposit.cname
(SELECT city AND deposit.bname = branch.bname
FROM customer)
What does the query do?
UNION

(SELECT city Find the names and assets of any branch which has
FROM branch) deposit account holders living in Jasper.
17 19

Queries With Set Operators Queries With Nested Structures


Find all cities that have both customers
and branches in. Queries within the WHERE clause of an outer
(SELECT city query
FROM customer) SELECT
FROM
WHERE OPERATOR(SELECT … FROM … WHERE)
INTERSECT
There can be multiple levels of nesting
(SELECT city Operators: IN, (NOT) EXISTS, < ALL, …
FROM branch)
Avoid nesting as much as possible.
Find every city that has a branch but no
customer.
18 20
Nested Structures Using “IN” The Same Example Without
Nesting
SELECT deposit(accno, cname, bname, balance)
FROM
WHERE expr|(expr list) IN
(set of values)
SELECT d1.cname
FROM deposit d1, deposit d2
E.g. WHERE d2.cname = ‘John Doe’
… WHERE province IN (‘AB’,‘BC’)
… WHERE province NOT IN (‘AB’,’BC’) AND d1.bname = d2.bname
… WHERE (name,city) IN ((‘John Doe’,
‘Edmonton’), (‘John Doe’, ‘New York’))

NOTE: avoid nesting as much as possible.


21 23

Nested Structures Using


Example
“< ALL”,…
deposit(accno, cname, bname, balance) SELECT
FROM
WHERE expr < ALL (set of values)
SELECT cname
FROM deposit Other forms: “<= ALL”, “= ALL”, “>= ALL”,
WHERE bname IN “> ALL”
(SELECT bname Op ALL (set of values) evaluates to true iff the
FROM deposit
WHERE cname = ‘John Doe’) comparison evaluates to true for every value in
the set.
What does the query do? Op SOME (set of values) evaluates to true iff
Find every customer who has a deposit in some branch the the comparison evaluates to true for at
at which John Doe has a deposit. least one value in the set.

22 24
Nested Structures Using
“EXISTS” Construct Example
“>ALL”, …
branch (bname, address, city, assets)
customer(cname, street, city)
branch (bname, address, city, assets) Find the names of customers who live in a city with
no bank branches.
Find branches that have assets greater than SELECT cname
FROM customer
the assets of all branches in Calgary. WHERE NOT EXISTS (SELECT *
FROM branch
SELECT bname WHERE customer.city=branch.city)
FROM branch
WHERE assets > ALL Find the names of customers who live in a city
(SELECT assets which has a bank branch.
FROM branch
WHERE city = ‘Calgary’) • Change NOT EXISTS to EXISTS.
(can also write it using join)
25 27

Nested Structures Using Division


“EXISTS” Query type: Find the subset of items in one set
SELECT that are related to all items in another set
FROM Example: Find customers who have deposits
WHERE (NOT) EXISTS(SELECT … ) accounts in all branches.

EXISTS (SELECT …) cname bname bname


Contains row All branch names
evaluates to true iff the result of the subquery <c,b> if customer
contains at least one row. c has a deposit
account in
The expression is evaluated for every branch b
iteration of the outer query.

πcname, bname (deposit) / πbname(branch)

26 28
Division Division – 2nd SQL Solution
Find customers who have deposit accounts in all
branches.
Strategy for implementing division in SQL: • Same as “find all customers such that there is no
branch where they do not have deposits in.”
• Find set, A, of all branches in which a particular
customer, c, has a deposit account. SELECT c.cname
FROM customer c
• Find set, B, of all branches. WHERE NOT EXISTS
• Output c if A ⊇ B, or, equivalently, if B–A is (SELECT bname
FROM branch b branches where
empty WHERE NOT EXISTS c has no deposits in
(SELECT *
Deposits of c in FROM deposit
branch b WHERE b.bname=deposit.bname
AND c.cname = deposit.cname))

29 31

Division – Another Example


Division – SQL Solution
branch (bname, address, city, assets)
deposit(accno, cname, bname, balance) Find professors who have taught courses in all
departments.
SELECT c.cname
FROM customer c
WHERE NOT EXISTS Strategy for implementing division in SQL:
(SELECT b.bname -- set B of all branches
FROM branch b
• Find set, A, of all departments in which a
MINUS particular professor, p, has taught a course
SELECT d.bname -- set A of branches in which • Find set, B, of all departments
-- customer c has a deposit account
FROM deposit d
• Output p if A ⊇ B, or, equivalently, if B–A is
WHERE d.cname=c.cname -- global variable empty
)
30 32
Division – SQL Solution Basic Data Types in Oracle
Professor (Id, Name, DeptId)
Department (DeptId, Name)
Course (DeptId, CrsCode, CrsName, Descr) NUMBER(m,n) decimal number (precision, scale)
Teaching (ProfId, CrsCode, Semester) (no parameters means floating point)
DATE century,year,month,day, hh.mm.ss
SELECT P.Id
FROM Professor P CHAR(n) fixed-length char string (n <= 2000)
WHERE NOT EXISTS VARCHAR2(n) var-length char string (n <= 4000)
(SELECT D.DeptId -- set B of all dept Ids
FROM Department D LONG var-length char string (up to 2 gigabytes)
MINUS RAW(n) fixed-lengh raw binary data (n <= 2000)
SELECT C.DeptId -- set A of dept Ids of depts in
LONG RAW var-length raw binary data (max 2 gigs)
-- which P has taught a course
FROM Teaching T, Course C
WHERE T.ProfId=P.Id -- global variable
AND T.CrsCode=C.CrsCode)
33 35

SQL and Oracle Other Data Types in Oracle


Oracle
• the first commercial relational database system. VARCHAR(n) same as VARCHAR2(n)
• based on the system R prototype.
LONG VARCHAR(n) same as LONG
Will be using Oracle V9i.
Many supporting products: DECIMAL(m,n) same as NUMBER(m,n)
• SQL Plus: interactive SQL interface FLOAT same as NUMBER
• SQL Precompilers (C, C++)
INTEGER same as NUMBER(38,0)
• SQL Loader: tool for mass loading of data
• PL/SQL: Oracle’s Procedural Language extension SMALLINT same as NUMBER(38,0)
• JDBC support REAL same as NUMBER
• Oracle Forms: tool for creating forms interfaces
• Oracle Report Writer: report definition and formatting
DOUBLE PRECISION same as NUMBER
• …

34 36

You might also like