Download sql – structured query language

Document related concepts

Oracle Database wikipedia , lookup

Extensible Storage Engine wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

Database wikipedia , lookup

DBase wikipedia , lookup

Microsoft Access wikipedia , lookup

Btrieve wikipedia , lookup

Tandem Computers wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

Relational algebra wikipedia , lookup

Clusterpoint wikipedia , lookup

Database model wikipedia , lookup

Null (SQL) wikipedia , lookup

Open Database Connectivity wikipedia , lookup

Microsoft SQL Server wikipedia , lookup

Relational model wikipedia , lookup

SQL wikipedia , lookup

PL/SQL wikipedia , lookup

Transcript
SQL – STRUCTURED QUERY LANGUAGE
Dr. Raj Sunderraman
Computer Science Department
Georgia State University
.
TABLE OF CONTENTS
SQL – Structured Query Language
Table Of Contents
* DATABASE APPROACH
o Database/Database Management System
o Database Approach vs. Traditional File Processing
* RELATIONAL MODEL OF DATA
o Terminology
o Sample Database Instance
o Integrity Constraints
o Relational Rules
o Relational Algebra
o Querying database using Relational Algebra
* DATA DEFINITION IN SQL
o Schema Definition in SQL
o Simple Inserts
o Data Types
Dr. Raj Sunderraman
2
SQL – Structured Query Language
Table Of Contents
* QUERYING IN SQL
o Simple Select Statements
o Subselects
o Union and For All Queries
o Aggregates/Group By/Having
o Group By/ Having clauses
o Full Select Statement Syntax
o Conceptual Order of Evaluation of a Select Statement
* UPDATES IN SQL
o Database Updates (insert, delete, update)
* ADDITIONAL FEATURES OF SQL
o Views
o Indexes
o Tips to increase query efficiency
o Transactions
o Triggers
o Catalog
o Security and Sharing
* APPLICATION PROGRAMMING
o Embedded-SQL (E-SQL)
Dr. Raj Sunderraman
3
DATABASE APPROACH
SQL – Structured Query Language
DATABASE APPROACH
This slide intentionally left blank.
Dr. Raj Sunderraman
5
SQL – Structured Query Language
DATABASE APPROACH
Database/Database Management System
• A database is a large collection of persistent inter-related data.
• A database management system (DBMS) is the software that maintains and
provides access to the database. It allows the user to
– Define the structure of the database, and
– Manipulate the database (query and update)
Dr. Raj Sunderraman
6
SQL – Structured Query Language
DATABASE APPROACH
Database Approach vs. Traditional File Processing
• Self contained nature of database systems (database contains both data and
meta-data).
• Data Independence: application programs and queries are independent of
how data is actually stored.
• Data sharing.
• Controlling redundancies and inconsistencies.
• Secure access to database; Restricting unauthorized access.
• Enforcing Integrity Constraints.
• Backup and Recovery from system crashes.
• Support for multiple-users and concurrent access.
Dr. Raj Sunderraman
7
RELATIONAL MODEL OF DATA
SQL – Structured Query Language
RELATIONAL MODEL OF DATA
Terminology
• Relation Scheme: list of attribute names.
Example: R = (CID, CNAME, CITY, DISCOUNT).
• Domain: set of values.
Example: set of integers, set of character strings of length 10, set of real
numbers.
• With each attribute name A, we associate a domain referred to as domain(A).
Example: domain(CID)=char4, domain(CNAME)=char13,
domain(DISCOUNT)=integer
• A Tuple over the relation scheme (A1, ..., An) is (a1, ..., an) where each ai is
an element of domain(Ai) or null.
Example: (’c001’,’TipTop’, ’Duluth’,10) is a tuple over scheme R.
• Relation: over a relation scheme (A1, ..., An) is a finite set of tuples over the
same scheme.
Example: {(’c001’,’TipTop’, ’Duluth’,10),(’c002’,’Basics’, ’Dallas’,null)} is a
relation over scheme R.
Dr. Raj Sunderraman
9
SQL – Structured Query Language
RELATIONAL MODEL OF DATA
Basically,
• A relation over scheme R=(A1, ..., An) can be viewed as a table consisting of n
columns and a finite set of rows.
• Each column corresponds to an attribute name and
• Each row corresponds to a tuple within the relation.
Relation
Attribute Name
Tuple
Dr. Raj Sunderraman
--- Table
--- Column Name
--- Row
10
SQL – Structured Query Language
RELATIONAL MODEL OF DATA
Sample Database Instance
customers
CID CNAME
---- ------------c001 Tiptop
c002 Basics
c003 Allied
c004 ACME
c006 ACME
Dr. Raj Sunderraman
CITY
DISCNT
-------------------- ---------Duluth
10
Dallas
12
Dallas
8
Duluth
8
Kyoto
0
11
SQL – Structured Query Language
agents
AID ANAME
--- ------------a01 Smith
a02 Jones
a03 Brown
a04 Gray
a05 Otasi
a06 Smith
Dr. Raj Sunderraman
RELATIONAL MODEL OF DATA
CITY
PERCENT
-------------------- ---------New York
6
Newark
6
Tokyo
7
New York
6
Duluth
5
Dallas
5
12
SQL – Structured Query Language
products
PID PNAME
--- ------------p01 comb
p02 brush
p03 razor
p04 pen
p05 pencil
p06 folder
p07 case
Dr. Raj Sunderraman
RELATIONAL MODEL OF DATA
CITY
QUANTITY
PRICE
-------------------- ---------- ---------Dallas
111400
.5
Newark
203000
.5
Duluth
150600
1
Duluth
125300
1
Dallas
221400
1
Dallas
123100
2
Newark
100500
1
13
SQL – Structured Query Language
orders
ORDNO MON
----- --1011 jan
1012 jan
1019 feb
1017 feb
1018 feb
1023 mar
1022 mar
1025 apr
1013 jan
1026 may
1015 jan
1014 jan
1021 feb
1016 jan
1020 feb
1024 mar
CID
---c001
c001
c001
c001
c001
c001
c001
c001
c002
c002
c003
c003
c004
c006
c006
c006
Dr. Raj Sunderraman
AID
--a01
a01
a02
a06
a03
a04
a05
a05
a03
a05
a03
a03
a06
a01
a03
a06
RELATIONAL MODEL OF DATA
PID
QTY
DOLLARS
--- ---------- ---------p01
1000
450
p01
1000
450
p02
400
180
p03
600
540
p04
600
540
p05
500
450
p06
400
720
p07
800
720
p03
1000
880
p03
800
704
p05
1200
1104
p05
1200
1104
p01
1000
460
p01
1000
500
p07
600
600
p01
800
400
14
SQL – Structured Query Language
RELATIONAL MODEL OF DATA
Integrity Constraints
Integrity Constraints are conditions that must be satisfied by the database at all
times. Some commonly used Integrity Constraints are:
• not null: Certain columns in a table may be prohibited from having null values.
• primary key: is a set of column names which uniquely identify each row.
Example: {CID} is the primary key for customers table.
The primary key constraint indicates that the table cannot contain two different
rows with the same values under primary key columns.
Dr. Raj Sunderraman
15
SQL – Structured Query Language
RELATIONAL MODEL OF DATA
• candidate key: A relation (table) may contain more than one key.
In this case, one of the keys is selected as the primary key and the remaining
keys are called candidate keys.
The candidate key constraint indicates that the table cannot contain two
different rows with the same values under candidate key columns.
• foreign keys (referential integrity): Many a times, it is necessary to include
column names from one table in another table.
Example: CID, AID and PID are included in the orders table.
CID is a primary key of the customers table and its inclusion in the orders table
makes it a foreign key in the orders table.
This constraint forces every CID value in the orders table to be also present in
the customers table.
Dr. Raj Sunderraman
16
SQL – Structured Query Language
RELATIONAL MODEL OF DATA
Relational Rules
1. First Normal Form: Domains must be atomic. i.e multi-valued fields are not
allowed. Example: The following relation is not in First Normal Form:
Emp-Id Name Phones
Dept.
1001
Smith {689-3922,689-3919} Computer Science
...
...
...
...
2. Access rows by content: There is no ordering to the rows of a table, i.e., we
cannot access the first row or the fifth row or the last row etc.
3. Unique row rule: Since a relation was defined as a SET of tuples (rows), there
should be no duplicates.
4. Entity integrity rule: Primary Key columns in a table CANNOT contain null
values.
Dr. Raj Sunderraman
17
SQL – Structured Query Language
RELATIONAL MODEL OF DATA
Relational Algebra
• Set Operations:
– union
– difference
– product
– intersection
• Relational Operations:
– select (horizontal slicing)
– project (vertical slicing)
– join
– division
Dr. Raj Sunderraman
18
SQL – Structured Query Language
R
A B C
------a b c
d a f
c b d
RELATIONAL MODEL OF DATA
S
D E F
------b g a
d a f
R intersection S
A B C
------d a f
Dr. Raj Sunderraman
R union S
A B C
------a b c
d a f
c b d
b g a
R - S
A B C
------a b c
c b d
R x S
A B C D E F
---------------a b c b g a
a b c d a f
d a f b g a
d a f d a f
c b d b g a
c b d d a f
19
SQL – Structured Query Language
R
A B C D
---------a b c d
a b e f
b c e f
e d c d
e d e f
a b d e
RELATIONAL MODEL OF DATA
S
C D E
------c d e
c d f
d e f
project[A,B](R)
A B
---a b
b c
e d
Dr. Raj Sunderraman
T
C D
---c d
e f
R join S
A B C D E
------------a b c d e
a b c d f
e d c d e
e d c d f
a b d e f
select[B="b"](R)
A B C D
---------a b c d
a b e f
a b d e
R div T
A B
---a b
e d
20
SQL – Structured Query Language
RELATIONAL MODEL OF DATA
Querying database using Relational Algebra
(1) Get cnames of customers who live in "New York" and
order product "p01".
T1 = customers join orders
T2 = select[city="New York" and pid="p01"](T2)
RESULT = project[cname](T3)
(2) Get cids of customers who do not order part "p01".
T1 = project[cid](select[pid="p01"](orders))
T2 = project[cid](customers)
RESULT = T2 - T1
Dr. Raj Sunderraman
21
SQL – Structured Query Language
RELATIONAL MODEL OF DATA
(3) Get cids of customers who order "p01" and "p02".
T1 = project[cid](select[pid="p01"](orders))
T2 = project[cid](select[pid="p02"](orders))
RESULT = T1 intersection T2
(4) Get pids of products for which orders have been placed
by agents in "Dallas" or "Duluth"
T1 = agents join orders
T2 = project[pid](select[city="Dallas"](T1))
T3 = project[pid](select[city="Duluth"](T1))
RESULT = T2 union T3
Dr. Raj Sunderraman
22
SQL – Structured Query Language
RELATIONAL MODEL OF DATA
(5) Get cids of customers who place orders through ALL
agents located in "New York".
T1 = project[cid,aid](orders)
T2 = project[aid](select[city="New York"](agents))
RESULT = T1 div T2
Dr. Raj Sunderraman
23
DATA DEFINITION IN SQL
SQL – Structured Query Language
DATA DEFINITION IN SQL
Schema Definition in SQL
drop table customers;
create table customers (
cid
char(4) not null,
cname varchar(13),
city
varchar(20),
discnt real check(discnt >= 0.0 and discnt <= 15.0),
primary key (cid));
drop table agents;
create table agents (
aid
char(3) not null,
aname
varchar(13),
city
varchar(20),
percent number(6) check(percent >= 0 and percent <= 100),
primary key (aid));
Dr. Raj Sunderraman
25
SQL – Structured Query Language
DATA DEFINITION IN SQL
drop table products;
create table products (
pid
char(3) not null,
pname
varchar(13),
city
varchar(20),
quantity number(10) check(quantity > 0),
price
real check(price > 0.0),
primary key (pid));
Dr. Raj Sunderraman
26
SQL – Structured Query Language
DATA DEFINITION IN SQL
drop table orders;
create table orders (
ordno
number(6) not null,
month
char(3),
cid
char(4) not null,
aid
char(3) not null,
pid
char(3) not null,
qty
number(6) not null check(qty > 0),
dollars float default 0.0 check(dollars >= 0.0),
primary key (ordno),
foreign key (cid) references customers,
foreign key (aid) references agents,
foreign key (pid) references products);
Dr. Raj Sunderraman
27
SQL – Structured Query Language
DATA DEFINITION IN SQL
Simple Inserts
insert into customers
values (’c001’,’Tiptop’,’Duluth’,10.00);
insert into customers
values (’c002’,’Basics’,’Dallas’,12.00);
insert into customers
values (’c003’,’Allied’,’Dallas’,8.00);
insert into customers
values (’c004’,’ACME’,’Duluth’,8.00);
insert into customers
values (’c006’,’ACME’,’Kyoto’,0.00);
Dr. Raj Sunderraman
28
SQL – Structured Query Language
DATA DEFINITION IN SQL
Data Types
CHAR[(n)]
VARCHAR
character string of length n
string of upto 256 characters; variable
length
SMALLINT
-32767 to + 32767
INTEGER or INT -2 billion to + 2 billion
DECIMAL[(m[,n])] decimal floating point numbers with m
digits (n decimal digits)
SMALLFLOAT
real numbers (upto 8 significant digits)
FLOAT[n]
double precision
DATE
dates (12-MAR-96)
MONEY[(m[,n])] money ($12.30)
TEXT
upto 2 GBytes of textual data
BYTE
upto 2 GBytes of binary data
Dr. Raj Sunderraman
29
QUERYING IN SQL
SQL – Structured Query Language
QUERYING IN SQL
Simple Select Statements
The simplest form of select statement has the following general syntax:
select [distinct] expression {, expression}
from tablename [corr_name] {, tablename [corr_name]}
[where search_condition];
Dr. Raj Sunderraman
31
SQL – Structured Query Language
QUERYING IN SQL
(1) Find aid values and names of agents that are
based in New York.
SQL> select aid, aname
from agents
where city = ’New York’;
AID
--a01
a04
ANAME
------------Smith
Gray
Dr. Raj Sunderraman
32
SQL – Structured Query Language
QUERYING IN SQL
(2) Print all rows in Customers table.
SQL> select *
from customers;
CID
---c001
c002
c003
c004
c006
CNAME
------------Tiptop
Basics
Allied
ACME
ACME
Dr. Raj Sunderraman
CITY
DISCNT
-------------------- ---------Duluth
10
Dallas
12
Dallas
8
Duluth
8
Kyoto
0
33
SQL – Structured Query Language
QUERYING IN SQL
(3) Get pid values for parts for which orders have
been placed. Eliminate duplicate answers.
SQL> select distinct pid
from orders;
PID
--p01
p02
p03
...
...
7 rows selected.
Dr. Raj Sunderraman
34
SQL – Structured Query Language
QUERYING IN SQL
(4) String Comparisons: Get customers whose name begin with
letter "A".
SQL> select *
from customers
where cname like ’A%’;
CID
---c003
c004
c006
CNAME
------------Allied
ACME
ACME
CITY
DISCNT
-------------------- ---------Dallas
8
Duluth
8
Kyoto
0
Underscore(_) : wildcard for any single character
Percent(%)
: wildcard for any sequence of zero or more
characters.
Dr. Raj Sunderraman
35
SQL – Structured Query Language
QUERYING IN SQL
(5) Get cname, aname pairs such that the customer
has placed an order through the agent.
SQL> select distinct cname, aname
from customers, orders, agents
where customers.cid = orders.cid and
orders.aid = agents.aid;
CNAME
------------ACME
ACME
...
...
ANAME
------------Brown
Smith
10 rows selected.
Dr. Raj Sunderraman
36
SQL – Structured Query Language
QUERYING IN SQL
(6) For each order, get ordno, cid, aid, pid
values along with profit made on that order.
Profit is calculated by selling price
minus customer discount and agent commission.
SQL>
select ordno, x.cid, x.aid, x.pid,
.40*(x.qty*p.price) .01*(c.discnt+a.percent)*(x.qty*p.price)
profit
from orders x, customers c, agents a, products p
where c.cid = x.cid and
a.aid = x.aid and
p.pid = x.pid;
Dr. Raj Sunderraman
37
SQL – Structured Query Language
ORDNO
---------1011
1012
1019
1025
1017
...
...
CID
---c001
c001
c001
c001
c001
QUERYING IN SQL
AID
--a01
a01
a02
a05
a06
PID
PROFIT
--- ---------p01
120
p01
120
p02
48
p07
200
p03
150
16 rows selected.
Dr. Raj Sunderraman
38
SQL – Structured Query Language
QUERYING IN SQL
(7) Get all pairs of cids for customers based in
the same city.
SQL> select c1.cid, c2.cid
from customers c1, customers c2
where c1.city = c2.city and c1.cid < c2.cid;
CID
---c002
c001
CID
---c003
c004
Dr. Raj Sunderraman
39
SQL – Structured Query Language
QUERYING IN SQL
(8) Get pid values for products that have been
ordered by at least two customers.
SQL> select distinct x1.pid
from orders x1, orders x2
where x1.pid = x2.pid and x1.cid < x2.cid;
PID
--p01
p03
p05
p07
Dr. Raj Sunderraman
40
SQL – Structured Query Language
QUERYING IN SQL
(9) Get cid values for customers who order a product
for which an order is placed by agent "a06".
SQL> select distinct y.cid
from orders x, orders y
where y.pid = x.pid and x.aid = ’a06’;
CID
---c001
c002
c004
c006
Dr. Raj Sunderraman
41
SQL – Structured Query Language
QUERYING IN SQL
(10) Get cid values of customers whose discount is between
5 and 10.
SQL> select cid
from customers
where discnt between 5 and 10;
CID
---c001
c003
c004
Dr. Raj Sunderraman
42
SQL – Structured Query Language
QUERYING IN SQL
Subselects
• The where clause search condition may contain a select statement.
• A select statement within a search condition is called a subselect statement.
• The whole structure is often referred to as a nested select statement.
• SQL supports several built-in predicates which will be used to test the
sub-selects for certain conditions.
• We shall consider the following predicates: in, not in, quantified comparison
θany and θall, exists, not exists.
Dr. Raj Sunderraman
43
SQL – Structured Query Language
QUERYING IN SQL
The general forms of in and not in predicates:
expr in (sub-select)
expr in (value {, value})
expr not in (sub-select)
expr not in (value {, value})
Dr. Raj Sunderraman
44
SQL – Structured Query Language
QUERYING IN SQL
(1) Get cid values of customers who place orders with
agents in "Dallas" or "Duluth".
First we get aids of agents in "Dallas" or
"Duluth":
SQL> select aid
from agents
where city = ’Duluth’ or city = ’Dallas’;
AID
--a05
a06
Dr. Raj Sunderraman
45
SQL – Structured Query Language
QUERYING IN SQL
Then we use the previous select in the search
condition of the following select statement:
SQL> select distinct cid
from orders
where aid in (select aid
from agents
where city = ’Duluth’ or
city = ’Dallas’);
CID
---c001
c002
c004
c006
Dr. Raj Sunderraman
46
SQL – Structured Query Language
QUERYING IN SQL
(2) Get all information about agents in "Dallas" or
"Duluth".
SQL> select *
from agents
where city in (’Duluth’, ’Dallas’);
AID
--a05
a06
ANAME
------------Otasi
Smith
Dr. Raj Sunderraman
CITY
PERCENT
-------------------- ---------Duluth
5
Dallas
5
47
SQL – Structured Query Language
QUERYING IN SQL
(3) Multiple nesting: Get names and discounts of
customers who place orders through agents in
"Dallas" or "Duluth".
SQL> select cname, discnt
from customers
where cid in
(select cid
from orders
where aid in
(select aid
from agents
where city in
(’Duluth’, ’Dallas’)));
Dr. Raj Sunderraman
48
SQL – Structured Query Language
QUERYING IN SQL
CNAME
DISCNT
------------- ---------Tiptop
10
Basics
12
ACME
8
ACME
0
Dr. Raj Sunderraman
49
SQL – Structured Query Language
QUERYING IN SQL
(4) Correlated sub-select: subselect that uses data
from an outer select.
Get names of customers who order product "p05".
SQL> select cname
from customers
where ’p05’ in (select pid
from orders
where cid = customers.cid);
CNAME
------------Tiptop
Allied
Dr. Raj Sunderraman
50
SQL – Structured Query Language
QUERYING IN SQL
(5) Scope of variables: outer select cannot refer to
variables inside inner-selects.
SQL> select cname
from customers
where orders.aid = ’a03’ and
’p07’ in (select pid
from orders
where cid = customers.cid);
** ILLEGAL SQL SYNTAX ** as outer select refers to
orders.aid
Dr. Raj Sunderraman
51
SQL – Structured Query Language
QUERYING IN SQL
(6) Get ordno values for orders placed by customers
in "Duluth" through agents in "New York".
SQL> select ordno
from orders
where cid in (select cid
from customers
where city = ’Duluth’) and
aid in (select aid
from agents
where city = ’New York’);
ORDNO
---------1011
1012
1023
Dr. Raj Sunderraman
52
SQL – Structured Query Language
QUERYING IN SQL
The general forms of quantified comparison predicates:
expr
expr
expr
expr
expr
expr
<any
<=any
=any
<>any
>any
>=any
(sub-select)
(sub-select)
(sub-select)
(sub-select)
(sub-select)
(sub-select)
expr
expr
expr
expr
expr
expr
<all
<=all
=all
<>all
>all
>=all
(sub-select)
(sub-select)
(sub-select)
(sub-select)
(sub-select)
(sub-select)
Dr. Raj Sunderraman
53
SQL – Structured Query Language
QUERYING IN SQL
(7) Get aid values of agents with the smallest
percent commission.
SQL> select aid
from agents
where percent <=all (select percent
from agents);
AID
--a05
a06
Dr. Raj Sunderraman
54
SQL – Structured Query Language
QUERYING IN SQL
(8) Get names of customers who have the same discount
as that of any (one) of the customers in "Dallas"
or "Boston".
SQL> select cname
from customers
where discnt =any (select discnt
from customers
where city = ’Dallas’ or
city = ’Boston’);
CNAME
------------Allied
ACME
Basics
Dr. Raj Sunderraman
55
SQL – Structured Query Language
QUERYING IN SQL
(9) Get cid values of customers with smaller
discounts than every customer from "Duluth".
SQL> select cid
from customers
where discnt <all (select discnt
from customers
where city = ’Duluth’);
CID
---c006
Dr. Raj Sunderraman
56
SQL – Structured Query Language
QUERYING IN SQL
The general form of exists and not exists predicates:
exists (sub-select)
not exists (sub-select)
Dr. Raj Sunderraman
57
SQL – Structured Query Language
QUERYING IN SQL
(10) Get names of customers who have placed an order
through agent "a05".
SQL> select c.cname
from customers c
where exists (select *
from orders x
where c.cid = x.cid and
x.aid = ’a05’);
CNAME
------------Tiptop
Basics
Dr. Raj Sunderraman
58
SQL – Structured Query Language
QUERYING IN SQL
An equivalent SQL query without exists predicate:
SQL> select c.cname
from customers c, orders x
where c.cid = x.cid and x.aid = ’a05’;
Dr. Raj Sunderraman
59
SQL – Structured Query Language
QUERYING IN SQL
(11) Get cid values of customers who have placed an
order for both "p01" and "p07".
SQL> select cid
from orders x
where pid = ’p01’ and
exists (select *
from orders
where cid = x.cid and
pid = ’p07’);
CID
---c001
c001
c006
c006
Dr. Raj Sunderraman
60
SQL – Structured Query Language
QUERYING IN SQL
An equivalent SQL query without exists predicate:
SQL> select x.cid
from orders x, orders y
where x.pid = ’p01’ and
x.cid = y.cid and
y.pid = ’p07’;
Dr. Raj Sunderraman
61
SQL – Structured Query Language
QUERYING IN SQL
(12) Get names of customers who do not place orders
through agent "a05".
SQL> select c.cname
from customers c
where not exists (select *
from orders x
where c.cid = x.cid and
x.aid = ’a05’);
CNAME
------------Allied
ACME
ACME
Dr. Raj Sunderraman
62
SQL – Structured Query Language
QUERYING IN SQL
Two alternate solutions (using not in and <>all):
SQL> select c.cname
from customers c
where c.cid not in (select cid
from orders
where aid = ’a05’);
SQL> select c.cname
from customers c
where c.cid <>all (select cid
from orders
where aid = ’a05’);
Dr. Raj Sunderraman
63
SQL – Structured Query Language
QUERYING IN SQL
(13) Too many ways to write an SQL query!!
Get city names of customers who have placed
an order for "p01".
SQL> select distinct city
from customers
where cid in (select cid
from orders
where pid = ’p01’);
SQL> select distinct city
from customers
where cid =any (select cid
from orders
where pid = ’p01’);
Dr. Raj Sunderraman
64
SQL – Structured Query Language
QUERYING IN SQL
SQL> select distinct city
from customers c
where exists (select *
from orders
where cid = c.cid and
pid = ’p01’);
SQL> select distinct city
from customers c, orders x
where x.cid = c.cid and x.pid = ’p01’;
SQL> select distinct city
from customers c
where ’p01’ in (select pid
from orders
where cid = c.cid);
Dr. Raj Sunderraman
65
SQL – Structured Query Language
QUERYING IN SQL
Union and For All Queries
– Syntax for union:
(sub-select) union (sub-select)
(sub-select) union all (sub-select)
– No direct equivalent for division operation.
Dr. Raj Sunderraman
66
SQL – Structured Query Language
QUERYING IN SQL
(1) Get cities in which customers or agents are
located.
SQL> select city
from customers
union
select city
from agents;
CITY
-------------------Dallas
Duluth
Kyoto
New York
Newark
Tokyo
Dr. Raj Sunderraman
67
SQL – Structured Query Language
QUERYING IN SQL
The following will not eliminate duplicates:
SQL> select city
from customers
union all
select city
from agents;
CITY
-------------------Duluth
Dallas
Dallas
Duluth
...
11 rows selected.
Dr. Raj Sunderraman
68
SQL – Structured Query Language
QUERYING IN SQL
(2) Get cid values of customers who place orders
with ALL agents in "New York".
Get cid values of customers such that
(the set of agents from "New York"
through whom the customer has NOT
placed an order) is EMPTY.
SQL> select c.cid
CID
from customers c
---where not exists
c001
(select *
from agents a
where a.city = ’New York’ and
not exists (select *
from orders x
where x.cid = c.cid and
x.aid = a.aid));
Dr. Raj Sunderraman
69
SQL – Structured Query Language
QUERYING IN SQL
(3) Get aid values of agents from "New York" or "Duluth" who
place orders for ALL products priced over one dollar.
Get aid values of agents from "New York" or "Duluth" such
that (the set of products priced over one dollar
that the agent has NOT ordered) is EMPTY.
SQL>select a.aid
AID
from agents a
--where (a.city in (’New York’,’Duluth’)) and
a05
not exists (select p.pid
from products p
where p.price > 1.00 and
not exists (select *
from orders x
where x.pid = p.pid
and x.aid = a.aid));
Dr. Raj Sunderraman
70
SQL – Structured Query Language
QUERYING IN SQL
(4) Get cid values for customers who order ALL products
ordered by customer "c006".
Get cid values of customers (call them C) such that
(the set of products ordered by customer
"c006" and NOT ordered by the customer C) is EMPTY
SQL> select cid
CID
from customers c
---where not exists
c001
(select p.pid
c006
from products p
where p.pid in (select pid
from orders x
where x.cid = ’c006’) and
not exists (select *
from orders y
where y.pid = p.pid and
y.cid = c.cid));
Dr. Raj Sunderraman
71
SQL – Structured Query Language
QUERYING IN SQL
A variant is:
SQL> select cid
from customers c
where not exists
(select z.pid
from orders z
where z.cid = ’c006’ and
not exists
(select *
from orders y
where y.pid = z.pid and
y.cid = c.cid));
Dr. Raj Sunderraman
72
SQL – Structured Query Language
QUERYING IN SQL
(5) Get pid values of products that are supplied to
all customers in "Duluth".
Get pid values of products such that
(the set of customers from "Duluth"
to whom the product is NOT supplied) is EMPTY.
SQL> select pid
PID
from products p
--where not exists
p01
(select c.cid
from customers c
where c.city = ’Duluth’ and
not exists
(select *
from orders x
where x.pid = p.pid and
x.cid = c.cid));
Dr. Raj Sunderraman
73
SQL – Structured Query Language
QUERYING IN SQL
Aggregates/Group By/Having
SQL supports count, sum, avg, max, min functions.
Name
count
sum
avg
max
min
Dr. Raj Sunderraman
Argument Type
any (can be *)
numeric
numeric
char or numeric
char or numeric
Result Type
numeric
numeric
numeric
same as argument
same as argument
Description
count of occurrences
sum of arguments
average of arguments
maximum value
minimum value
74
SQL – Structured Query Language
QUERYING IN SQL
(1) Get total dollar amounts of all orders.
SQL> select sum(dollars)
from orders;
SUM(DOLLARS)
-----------9802
Dr. Raj Sunderraman
75
SQL – Structured Query Language
QUERYING IN SQL
(2) Get total quantity of product "p03" that has been ordered.
SQL> select sum(qty) TOTAL
from orders
where pid = ’p03’;
TOTAL
---------2400
Dr. Raj Sunderraman
76
SQL – Structured Query Language
QUERYING IN SQL
(3) Get total number of customers.
SQL> select count(cid)
from customers;
COUNT(CID)
---------5
Alternate solution:
SQL> select count(*)
from customers;
COUNT(*)
---------5
Dr. Raj Sunderraman
77
SQL – Structured Query Language
QUERYING IN SQL
(4) Get number of cities in which customers are based.
SQL> select count(distinct city)
from customers;
COUNT(DISTINCTCITY)
------------------3
If distinct keyword was not used, we would get an
incorrect result:
SQL> select count(city)
from customers;
COUNT(CITY)
----------5
Dr. Raj Sunderraman
78
SQL – Structured Query Language
QUERYING IN SQL
(5) Get cid values of customers who have a discount less than
the maximum discount.
SQL> select cid
from customers
where discnt < (select max(discnt)
from customers);
CID
---c001
c003
c004
c006
Dr. Raj Sunderraman
79
SQL – Structured Query Language
QUERYING IN SQL
(6) Get pids of products ordered by at least two customers.
SQL> select p.pid
from products p
where 2 <= (select count(distinct cid)
from orders
where pid = p.pid);
PID
--p01
p03
p05
p07
Dr. Raj Sunderraman
80
SQL – Structured Query Language
QUERYING IN SQL
(7) Null Values and Aggregate Operations:
SQL> insert into customers (cid, cname, city)
values (’c007’, ’Windix’, ’Dallas’);
1 row created.
SQL> select *
from customers
where discnt <= 10 or discnt > 10;
CID
---c001
c002
c003
c004
c006
CNAME
------------Tiptop
Basics
Allied
ACME
ACME
CITY
DISCNT
-------------------- ---------Duluth
10
Dallas
12
Dallas
8
Duluth
8
Kyoto
0
Newly created row not in result!
Dr. Raj Sunderraman
81
SQL – Structured Query Language
QUERYING IN SQL
SQL> select *
from customers
where discnt is null;
CID CNAME
CITY
DISCNT
---- ------------- -------------------- ---------c007 Windix
Dallas
Newly created row is in result.
Dr. Raj Sunderraman
82
SQL – Structured Query Language
QUERYING IN SQL
All aggregate functions discard null values before evaluation.
Get average discount value for customers.
SQL> select avg(discnt)
from customers;
AVG(DISCNT)
----------7.6
This discarded the null value before calculating average.
Dr. Raj Sunderraman
83
SQL – Structured Query Language
QUERYING IN SQL
Group By/ Having clauses
select [distinct] expression {, expression}
from tablename [corr_name] {, tablename [corr_name]}
[where search_condition]
[group by column {, column}]
[having search_condition]
• Group By clause is used to form groups of rows of a resulting table based on
column values. Aggregate operations work on groups and not whole table.
• Having clause is used to eliminate certain groups from further considerations.
Dr. Raj Sunderraman
84
SQL – Structured Query Language
QUERYING IN SQL
(1) For each (aid,pid) pair get the sum of the orders
aid has placed for pid.
SQL> select pid, aid, sum(qty) TOTAL
from orders
group by pid, aid;
PID
--p01
p01
p02
p03
p03
...
...
AID
TOTAL
--- ---------a01
3000
a06
1800
a02
400
a03
1000
a05
800
12 rows selected.
Dr. Raj Sunderraman
85
SQL – Structured Query Language
QUERYING IN SQL
(2) Get agent name, agent id, product name, product id,
together with total quantity each agent supplies of
that product to customers "c002" and "c003".
SQL> select aname, a.aid, pname, p.pid, sum(qty)
from orders x, products p, agents a
where x.pid = p.pid and x.aid = a.aid and
x.cid in (’c002’, ’c003’)
group by a.aid, a.aname, p.pid, p.pname;
ANAME
------------Brown
Otasi
Brown
AID
--a03
a05
a03
PNAME
------------razor
razor
pencil
PID
SUM(QTY)
--- ---------p03
1000
p03
800
p05
2400
Note: The where clause is evaluated before groups are formed.
Dr. Raj Sunderraman
86
SQL – Structured Query Language
QUERYING IN SQL
(3) Get product ids and total quantity ordered for each
product when the total exceeds 1000.
SQL> select pid, aid, sum(qty) TOTAL
from orders
group by pid, aid
having sum(qty) > 1000;
PID
--p01
p01
p05
AID
TOTAL
--- ---------a01
3000
a06
1800
a03
2400
Dr. Raj Sunderraman
87
SQL – Structured Query Language
QUERYING IN SQL
(4) Get pids of products that are ordered by at least two
customers.
SQL> select pid from orders
group by pid
having count(distinct cid) >= 2;
PID
--p01
p03
p05
p07
Dr. Raj Sunderraman
88
SQL – Structured Query Language
QUERYING IN SQL
Full Select Statement Syntax
Subselect General Form:
select [all|distinct] expression {, expression}
from tablename [corr_name] {, tablename [corr_name]}
[where search_condition]
[group by column {, column}]
[having search_condition]
Full Select General Form:
Subselect
{union [all] Subselect}
[order by result_column [asc|desc]
{, result_column [asc|desc]}]
The order by clause comes at the end and is used to sort the result of a query
based on column values.
Dr. Raj Sunderraman
89
SQL – Structured Query Language
QUERYING IN SQL
Conceptual Order of Evaluation of a Select Statement
1. First the product of all tables in the from clause is formed.
2. The where clause is then evaluated to eliminate rows that do not satisfy the
search condition.
3. Next, the rows are grouped using the columns in the group by clause.
4. Then, Groups that do not satisfy the search condition in the having clause are
eliminated.
5. Next, the expressions in the select clause target list are evaluated.
6. If the distinct keyword in present in the select clause, duplicate rows are now
eliminated.
7. The union is taken after each sub-select is evaluated.
8. Finally, the resulting rows are sorted according to the columns specified in the
order by clause.
Dr. Raj Sunderraman
90
SQL – Structured Query Language
QUERYING IN SQL
(1) Get names and ids of customers and agents along with
total dollar sales for that pair. Order the result
from largest to smallest total sales. Also retain
only those pairs for which total dollar sales is
at least 900.00.
SQL> select c.cname, c.cid, a.aname, a.aid, sum(o.dollars)
from customers c, orders o, agents a
where c.cid = o.cid and o.aid = a.aid
group by c.cname, c.cid, a.aname, a.aid
having sum(o.dollars) >= 900.00
order by 5 desc;
CNAME
------------Allied
Tiptop
Tiptop
Dr. Raj Sunderraman
CID
---c003
c001
c001
ANAME
------------Brown
Otasi
Smith
AID SUM(O.DOLLARS)
--- -------------a03
2208
a05
1440
a01
900
91
UPDATES IN SQL
SQL – Structured Query Language
UPDATES IN SQL
Database Updates (insert, delete, update)
General Syntax:
insert into tablename [(column {, column})]
[values (expression {, expression})] | [Sub-select]
delete from tablename [corr_name]
[where search_condition]
update tablename [corr_name]
set column = expression {, column = expression}
[where search_condition]
Dr. Raj Sunderraman
93
SQL – Structured Query Language
UPDATES IN SQL
(1) Insert into the orders table.
SQL> insert into orders
values (1111,’sep’,’c003’,’a05’,’p02’,500,1000);
1 row created
SQL> insert into orders (ordno, month, cid, aid, pid)
values (1107, ’aug’, ’c006’, ’a04’, ’p01’);
1 row created.
Dr. Raj Sunderraman
94
SQL – Structured Query Language
UPDATES IN SQL
SQL> select *
from orders;
ORDNO
---------1011
1012
MON
--jan
jan
CID
---c001
c001
AID
--a01
a01
PID
QTY
DOLLARS
--- ---------- ---------p01
1000
450
p01
1000
450
...
...
1111 sep c003 a05 p02
500
1000
1107 aug c006 a04 p01
17 rows selected.
Note the two rows that were inserted in previous slide.
Dr. Raj Sunderraman
95
SQL – Structured Query Language
UPDATES IN SQL
(2) Create a new table "swcusts" with same fields as
customers and insert rows from "customers" table
with city field equals "Dallas" or "Austin".
SQL> select *
from customers;
CID
---c001
c002
c003
c004
c006
c007
CNAME
------------Tiptop
Basics
Allied
ACME
ACME
Windix
CITY
DISCNT
-------------------- ---------Duluth
10
Dallas
12 <<
Dallas
8 <<
Duluth
8
Kyoto
0
Dallas
<<
6 rows selected.
Dr. Raj Sunderraman
96
SQL – Structured Query Language
UPDATES IN SQL
SQL> create table swcusts (
cid
char(4) not null,
cname
varchar(13),
city
varchar(20),
discnt float);
Table created.
SQL> insert into swcusts
select *
from customers
where city in (’Dallas’,’Austin’);
3 rows created.
Dr. Raj Sunderraman
97
SQL – Structured Query Language
UPDATES IN SQL
SQL> select *
from swcust;
CID
---c002
c003
c007
CNAME
------------Basics
Allied
Windix
Dr. Raj Sunderraman
CITY
DISCNT
-------------------- ---------Dallas
12
Dallas
8
Dallas
98
SQL – Structured Query Language
UPDATES IN SQL
(3) Increase the percent commission by 50% for all
agents in "New York".
SQL> update agents
set percent = 1.5 * percent
where city = ’New York’;
2 rows updated.
SQL> select * from agents;
AID
--a01
a02
a03
a04
a05
a06
ANAME
------------Smith
Jones
Brown
Gray
Otasi
Smith
Dr. Raj Sunderraman
CITY
PERCENT
------------ ---------New York
9
Newark
6
Tokyo
7
New York
9
Duluth
5
Dallas
5
<< old value = 6
<< old value = 6
99
SQL – Structured Query Language
UPDATES IN SQL
(4) Delete all agents from "New York".
SQL> delete from agents
where city = ’New York’;
2 rows deleted.
SQL> select *
from agents;
AID
--a02
a03
a05
a06
ANAME
------------Jones
Brown
Otasi
Smith
Dr. Raj Sunderraman
CITY
PERCENT
-------------------- ---------Newark
6
Tokyo
7
Duluth
5
Dallas
5
100
SQL – Structured Query Language
UPDATES IN SQL
(5) Delete all agents who have total orders of less than $600.
SQL> delete from agents
where aid in (select aid
from orders
group by aid
having sum(dollars) < 600);
1 row deleted.
SQL> select *
from agents;
AID
--a03
a05
a06
ANAME
------------Brown
Otasi
Smith
Dr. Raj Sunderraman
CITY
PERCENT
-------------------- ---------Tokyo
7
Duluth
5
Dallas
5
101
ADDITIONAL FEATURES OF SQL
SQL – Structured Query Language
ADDITIONAL FEATURES OF SQL
Views
• Views are dynamic windows into the database.
• Views provide users with different views of the database.
• A view may include columns from different tables and also may include
derived information such as aggregates.
• A view has a name and to a user it appears exactly as if it were a table.
• Views provide a mechanism to limit access to sensitive data by providing the
users to see only a part of the information.
CREATE VIEW view-name [(col-list)]
AS select-statement
DROP VIEW view-name
Dr. Raj Sunderraman
103
SQL – Structured Query Language
ADDITIONAL FEATURES OF SQL
SQL> CREATE VIEW dallas_cust AS
select *
from customers
where city = ’Dallas’;
View created.
SQL> select *
from dallas_cust;
CID
---c002
c003
CNAME
------------Basics
Allied
Dr. Raj Sunderraman
CITY
DISCNT
-------------------- ---------Dallas
12
Dallas
8
104
SQL – Structured Query Language
ADDITIONAL FEATURES OF SQL
SQL> CREATE VIEW tot_sales_per_agent AS
select agents.aid, aname, sum(dollars) TOT_SALES
from agents,orders
where agents.aid = orders.aid
group by agents.aid,aname;
View Created
SQL> select *
from tot_sales_per_agent;
AID
--a01
a02
a03
a04
a05
a06
ANAME
TOT_SALES
------------- ---------Smith
1400
Jones
180
Brown
4228
Gray
450
Otasi
2144
Smith
1400
Dr. Raj Sunderraman
105
SQL – Structured Query Language
ADDITIONAL FEATURES OF SQL
Indexes
Indexes are mechanisms to speed up retrieval of data.
CREATE [UNIQUE|CLUSTER] INDEX index-name
ON table-name (column-list)
DROP INDEX index-name
• unique index will ensure that two different rows do not have the same value
under the indexed columns
• clustered index will ensure that rows with same values are kept next to each
other on disk
CREATE
CREATE
CREATE
CREATE
CREATE
UNIQUE INDEX cust_index ON customers(cid);
UNIQUE INDEX agent_index ON agents(aid);
UNIQUE INDEX prod_index ON products(pid);
UNIQUE INDEX ord_index ON orders(ordno);
CLUSTER INDEX month_index ON orders(month);
Dr. Raj Sunderraman
106
SQL – Structured Query Language
ADDITIONAL FEATURES OF SQL
Tips to increase query efficiency
In general, we can speed up queries by changing it so that it
• Reads fewer rows
• Avoids a sort, sorts fewer rows, or sorts on a simpler key
• Reads rows sequentially rather than non-sequentially
Dr. Raj Sunderraman
107
SQL – Structured Query Language
ADDITIONAL FEATURES OF SQL
• Filter is the term used for conditions in the WHERE clause.
• Importance of table order in the from clause of a select statement with filters.
Tables with filters should appear first.
• Rewrite a join through views.
• Do not sort if the sort key (or any part of it) is not indexed.
• Provide indexes for join attributes
• Use UNION instead of OR condition
• Rebuild indexes after many updates
• Avoid correlated subqueries
• Avoid difficult regular expressions in the LIKE operation
• Use temporary tables to speed queries
Dr. Raj Sunderraman
108
SQL – Structured Query Language
ADDITIONAL FEATURES OF SQL
Transactions
create table account (
account_no integer;
owner char(20),
balance float,
primary key (account_no));
insert into account values (1111,’Smith’,500);
insert into account values (1112,’Smith’,600);
i.e. Customer "Smith" has two accounts;
Account 1111 with balance 500
Account 1112 with balance 600.
To qualify for a loan, a customer must have
at least $1000 in all of his accounts.
Dr. Raj Sunderraman
109
SQL – Structured Query Language
ADDITIONAL FEATURES OF SQL
Process I (Transfer Money)
s1: update account set balance = balance - 400
where account_id = 1111;
s2: update account set balance = balance + 400
where account_id = 1112;
Process II (Credit Check)
t1: sum = 0.0;
t2: select balance into :b where account_id = 1111;
t3: sum = sum + b;
t4: select balance into :b where account_id = 1112;
t5: sum = sum + b;
t6: if (sum < 1000) DENY LOAN else AUTHORIZE LOAN;
The execution sequence: s1;t1;t2;t3;t4;t5;s2;t6
will result in a DENY LOAN situation, which is erroneous.
Dr. Raj Sunderraman
110
SQL – Structured Query Language
ADDITIONAL FEATURES OF SQL
• Transaction System ensures such problems do not arise.
• A transaction is a set of statements which are guaranteed to execute as a
whole without interference from the effects of other transactions.
• Locking mechanism is employed by the system.
• A transaction begins with a BEGIN WORK statement
• A transaction ends with either COMMIT WORK or ROLLBACK WORK
statement.
BEGIN WORK
LOCK TABLE account
UPDATE account SET
WHERE account_id =
UPDATE account SET
WHERE account_id =
COMMIT WORK;
Dr. Raj Sunderraman
balance = balance - 400
1111;
balance = balance + 400
1112;
111
SQL – Structured Query Language
ADDITIONAL FEATURES OF SQL
Triggers
• An SQL Trigger is a mechanism that automatically executes a specified set of
SQL statements when a triggering event occurs on a table.
• Basically, a trigger consists of a triggered event and a triggered action.
• The triggering event may be one of INSERT, DELETE, UPDATE
• The triggered action may be one of INSERT, DELETE, UPDATE, EXECUTE
PROCEDURE
Dr. Raj Sunderraman
112
SQL – Structured Query Language
ADDITIONAL FEATURES OF SQL
General Syntax of SQL CREATE TRIGGER statement:
CREATE TRIGGER trigger_name
{INSERT ON table_name |
DELETE ON table_name |
UPDATE OF column_name ON table_name}
[REFERENCING NEW AS name OLD AS name]
{FOR EACH ROW | BEFORE | AFTER} (Action List);
Dr. Raj Sunderraman
113
SQL – Structured Query Language
ADDITIONAL FEATURES OF SQL
(1) Enforcing Referential Integrity Constraint.
Upon deleting a customer record, automatically
delete all orders for that customer from the
orders table.
CREATE TRIGGER del_cust
DELETE ON customers
REFERENCING OLD AS pre_del
FOR EACH ROW (DELETE FROM orders WHERE cid = pre_del.cid);
Dr. Raj Sunderraman
114
SQL – Structured Query Language
ADDITIONAL FEATURES OF SQL
(2) Creating an Audit Trail.
Each time someone updates the quantity of a particular
product, make an entry in a log file of this update
along with the name of the person doing the update and
the date of update.
CREATE TABLE log (
pid
varchar(3),
username
char(8),
update_date
date,
old_qty
integer,
new_qty
integer);
CREATE TRIGGER upd_prod
UPDATE OF quantity ON products
REFERENCING OLD AS pre_upd NEW AS post_upd
FOR EACH ROW (INSERT INTO log
values (pre_upd.pid,USER,CURRENT,
pre_upd.quantity,post_upd.quantity));
Dr. Raj Sunderraman
115
SQL – Structured Query Language
ADDITIONAL FEATURES OF SQL
(3) Implementing Business Rules:
Rule: NO single update SHALL increase the total
quantity of all products in stock by 50% or more.
CREATE PROCEDURE upd_prod_1()
DEFINE GLOBAL old_qty INT DEFAULT 0;
LET old_qty = (SELECT SUM(quantity) FROM products);
END PROCEDURE;
CREATE PROCEDURE upd_prod_2()
DEFINE GLOBAL old_qty INT DEFAULT 0;
DEFINE new_qty INT;
LET new_qty = (SELECT SUM(quantity) FROM products);
IF new_qty > 1.5 * old_qty THEN
RAISE EXCEPTION -746, 0, "Update Not Allowed";
ENDIF
END PROCEDURE
Dr. Raj Sunderraman
116
SQL – Structured Query Language
ADDITIONAL FEATURES OF SQL
CREATE TRIGGER upd_prod
UPDATE OF quantity ON products
BEFORE(EXECUTE PROCEDURE upd_prod_1())
AFTER(EXECUTE PROCEDURE upd_prod_2());
Note: If a trigger fails, INFORMIX automatically rollbacks all
changes.
Dr. Raj Sunderraman
117
SQL – Structured Query Language
ADDITIONAL FEATURES OF SQL
Catalog
• The system catalog contains a wealth of information about the database
structure.
• Information such as names of tables, their columns, who owns them, names of
views, view definitions, indexes, constraints, stored procedures, etc. are
commonly found in catalog tables.
• This information is stored in special tables (called catalog tables).
• Some catalog tables are:
– systables
– syscolumns
– sysindexes
– sysusers
Dr. Raj Sunderraman
118
SQL – Structured Query Language
ADDITIONAL FEATURES OF SQL
systables
tabname char(18)
tabid integer
owner char(8)
ncols smallint
nrows integer
created date
tabtype char(1) ; T = table, V = view
sysusers
username char(8)
usertype char(1) ; D = DBA, R = resource, C = connect
syscolumns
colname char(18)
tabid integer
colno smallint
coltype smallint ; 0 = CHAR, 1 = SMALLINT, ...
Dr. Raj Sunderraman
119
SQL – Structured Query Language
ADDITIONAL FEATURES OF SQL
select tabname, tabid
from systables
where owner = ’RAJ’;
select colname
from syscolumns
where tabid in (select tabid
from systables
where tabname = ’customers’);
Dr. Raj Sunderraman
120
SQL – Structured Query Language
ADDITIONAL FEATURES OF SQL
Other Useful Commands:
INFO TABLES
lists all tables owned by you
INFO COLUMNS FOR customers
lists all columns for customer table
INFO INDEXES FOR customers
lists all indexes for customers table
INFO STATUS FOR customers
lists status info for customers table
(owner, no. of rows, no. of columns,
date created etc.)
Dr. Raj Sunderraman
121
SQL – Structured Query Language
ADDITIONAL FEATURES OF SQL
Security and Sharing
Three levels of database privileges:
• Connect Privilege: allows users to query and modify tables (if they have
authority to).
• Resource Privilege: in addition to connect privileges, allows users to create
new tables, indexes, etc.
• DBA Privilege: highest level; grant privileges; create database; drop database;
create user-ids; The DBA grants privileges as follows:
GRANT connect TO smith;
GRANT resource TO jones;
Dr. Raj Sunderraman
122
SQL – Structured Query Language
ADDITIONAL FEATURES OF SQL
Table-level privileges:
GRANT [select|insert|delete|update(col-names)]
ON table_name
TO [user|PUBLIC];
REVOKE [select|insert|delete|update(col-names)|ALL]
ON table_name
FROM [user|PUBLIC];
Examples:
grant select on customers to public;
grant insert on orders to jones;
grant update(quantity) on products to jones,smith;
revoke all on customers from jones;
Dr. Raj Sunderraman
123
APPLICATION PROGRAMMING
SQL – Structured Query Language
APPLICATION PROGRAMMING
Embedded-SQL (E-SQL)
• Use a high-level programming language (Host Language) such as C, Pascal,
COBOL etc. to develop applications.
• Embed SQL commands within the high-level language programs to access the
database.
• Need a mechanism to communicate values between database server and
high-level program environment.
• Special variables (called host variables) are defined in the program for this
purpose.
• Precede these special variables by a colon (:) when used in a SQL statement.
• All the power of the host language can be used to develop applications.
Dr. Raj Sunderraman
125
SQL – Structured Query Language
APPLICATION PROGRAMMING
Declaring host variables and using them:
EXEC SQL BEGIN DECLARE SECTION;
char cid[5],cname[14],city[21];
float
discount;
EXEC SQL END DECLARE SECTION;
...
...
scanf("%s",cid);
EXEC SQL select cname
into :cname
from customers
where cid = :cid;
...
...
scanf("%s%S%S%f",cid,cname,city,&discount);
EXEC SQL insert into customers
values (:cid,:cname,:city,:discount);
Dr. Raj Sunderraman
126
SQL – Structured Query Language
APPLICATION PROGRAMMING
Indicator Variables: integer variables which are used to indicate if a null value is
fetched from the database or stored into the database.
EXEC SQL BEGIN DECLARE SECTION;
float cust_discount;
char cid[5];
short int cd_ind;
EXEC SQL END DECLARE SECTION;
To check if the value fetched from database is Null or not:
EXEC SQL select discnt
into :cust_discount:cd_ind
from customers
where cid = :cust_id;
if (cd_ind == -1)
printf("Customer discount is Null\n");
else if (cd_ind == 0)
printf("Customer discount is not Null\n");
Dr. Raj Sunderraman
127
SQL – Structured Query Language
APPLICATION PROGRAMMING
To store a null value into the database:
cd_ind = -1;
EXEC SQL update customers
set discnt = :cust_discount:cd_ind
where cid = :cust_id;
Dr. Raj Sunderraman
128
SQL – Structured Query Language
APPLICATION PROGRAMMING
SQL Communications Area (sqlca):
• Immediately after the Database Server executes an embedded SQL
statement, it reports the status of the execution in some variables defined in
sqlca.
• An important field in the sqlca structure is SQLCODE. The Database Server
returns a value of 0 if the execution was a success; a value of 100 if no more
data or not found; a negative values if error.
• To include the sqlca definition, the following must appear early in the program.
EXEC SQL INCLUDE sqlca;
Dr. Raj Sunderraman
129
SQL – Structured Query Language
APPLICATION PROGRAMMING
Use of sqlca.sqlcode variable to check for error:
void insert_customer()
{
printf("Type in Customer Id: "); scanf("%s",cid);
printf("Type in Customer Name: "); scanf("%s",cname);
printf("Type in City: "); scanf("%s",city);
printf("Type in Discount: "); scanf("%f",&discount);
EXEC SQL SET TRANSACTION READ WRITE;
EXEC SQL INSERT INTO customers
VALUES(:cid,:cname,:city,:discount);
if (sqlca.sqlcode < 0) {
printf("\n\nCUSTOMER (%s) ALREADY PRESENT\n",cname);
EXEC SQL ROLLBACK WORK;
return;
}
EXEC SQL COMMIT;
}
Dr. Raj Sunderraman
130
SQL – Structured Query Language
APPLICATION PROGRAMMING
Selecting more than one row using cursors:
void print_customers()
{
EXEC SQL DECLARE c2 CURSOR FOR
SELECT cid, cname, city, discnt
FROM customers;
EXEC SQL SET TRANSACTION READ ONLY;
EXEC SQL OPEN c2;
EXEC SQL FETCH c2 INTO :cid,:cname,:city,:discount;
while (sqlca.sqlcode == 0) {
cid[strlen(cid)] = ’\0’;
cname[strlen(cname)] = ’\0’;
city[strlen(city)] = ’\0’;
printf("%6s%15s%15s\t%f\n",cid,cname,city,discount);
EXEC SQL FETCH c2 INTO :cid,:cname,:city,:discount;
}
EXEC SQL CLOSE c2; EXEC SQL COMMIT;
}
Dr. Raj Sunderraman
131
SQL – Structured Query Language
APPLICATION PROGRAMMING
Delete and Update using cursors:
Delete all customers from the customers table who live in ”Duluth” and have
made no orders:
Without cursor:
EXEC SQL delete from customers c
where c.city = ’Duluth’ and
not exists (select *
from orders o
where c.cid = o.cid);
Dr. Raj Sunderraman
132
SQL – Structured Query Language
APPLICATION PROGRAMMING
With Cursor:
EXEC SQL declare del_cust cursor for
select cid
from customers c
where c.city = ’Duluth’ and
not exists (select *
from orders o
where c.cid = o.cid)
for update of cid;
...
...
EXEC SQL open del_cust;
EXEC SQL fetch del_cust into :cust_id;
while (sqlca.sqlcode <> 100) {
EXEC SQL delete from customers
where current of del_cust;
EXEC SQL fetch del_cust into :cust_id;
}
Dr. Raj Sunderraman
133
SQL – Structured Query Language
APPLICATION PROGRAMMING
Recursive Query:
SQL> create table employees (
eid integer,
mgrid integer);
SQL> select *
from employees;
EID
MGRID
---------- ---------2
1
3
1
4
2
5
2
6
4
7
6
Given a employee, print all the employees who work under that employee at all
levels.
Dr. Raj Sunderraman
134
SQL – Structured Query Language
APPLICATION PROGRAMMING
EXEC SQL BEGIN DECLARE SECTION;
int eid, a;
EXEC SQL END DECLARE SECTION;
EXEC SQL INCLUDE sqlca;
main()
{ int newrowadded;
exec sql create table answer(
a integer not null, primary key (a));
/* Cursor for employees at next level (Initial answers) */
exec sql declare c1 cursor for
select eid from employees where mgrid = :eid;
/* answer(X) if employees(X,Y) and answer(Y) */
exec sql declare c2 cursor for
select eid from employees,answer where mgrid = a;
/* Cursor to print the answers */
exec sql declare c3 cursor for select a from answer;
Dr. Raj Sunderraman
135
SQL – Structured Query Language
APPLICATION PROGRAMMING
Recursive Query Continued:
Get initial answers using Cursor c1:
printf("Type in employee id:");
scanf("%d",&eid);
exec sql open c1;
exec sql fetch c1 into :a;
while (sqlca.sqlcode == 0) {
exec sql insert into answer values (:a);
exec sql fetch c1 into :a;
}
exec sql close c1;
exec sql commit work;
Dr. Raj Sunderraman
136
SQL – Structured Query Language
APPLICATION PROGRAMMING
Recursive Query Continued:
Repeatedly process Cursor c2:
do {
newrowadded = FALSE;
exec sql open c2;
exec sql fetch c2 into :a;
while (sqlca.sqlcode == 0) {
exec sql insert into answer values (:a);
if (sqlca.sqlcode == 0)
newrowadded = TRUE;
exec sql fetch c2 into :a;
}
exec sql close c2;
} while (newrowadded);
exec sql commit work;
Dr. Raj Sunderraman
137
SQL – Structured Query Language
APPLICATION PROGRAMMING
Recursive Query Continued:
Print results from answer table:
printf("Answer is\n");
exec sql open c3;
exec sql fetch c3 into :a;
while (sqlca.sqlcode == 0) {
printf("%d\n",a);
exec sql fetch c3 into :a;
}
exec sql close c3;
exec sql commit work;
exec sql drop table answer;
exec sql commit work;
}/*end of main*/
Dr. Raj Sunderraman
138
SQL – Structured Query Language
APPLICATION PROGRAMMING
Assignment 1
1. Define the customers-agents-products-orders database in INFORMIX.
2. Populate the tables with the sample rows using the insert statement.
3. Write SQL queries for the following:
3.1. Get all (cid,aid,pid) triples for customer, agent, product combinations that are all in the same city.
3.2. Get all (cid,aid,pid) triples for customer, agent, product combinations that are all not in the same city (any two may be in
the same city but not all three).
3.3. Get all (cid,aid,pid) triples for customer, agent, product combinations such that no two of which are in the same city.
3.4. Get cities of agents booking an order from customer ”c002”.
3.5. Get product names of products ordered by at least one customer based in ”Dallas” through an agent based in ”Tokyo”.
3.6. Get pids of products ordered through any agent who makes at least one order for a customer in ”Kyoto”.
3.7. Get all pairs of pids for agents who live in the same city.
Dr. Raj Sunderraman
139
SQL – Structured Query Language
APPLICATION PROGRAMMING
Assignment 2
1. Implement the triggers discussed in the notes in Informix.
2. Write SQL queries for the following:
2.1. Get cids of customers who did not place an order through agent ”a03”.
2.2. Get cnames of customers who have the largest discount.
2.3. Get cids of customers who order all products.
2.4. Get pids of products ordered through agent ”a03” but not through agent ”a06”.
2.5. Get pnames and pids of products that are stored in the same city as one of the agents who sold these products.
2.6. Get aids and anames of agents whose names begin with the letter ”N” who do not place orders for any product in
”Newark”.
2.7. Get cids of customers who order both ”p01” and ”p07”.
2.8. Get names of agents who place orders for all products ordered by customer ”c002”.
2.9. For each agent taking an order, list the product id and the total quantity ordered by all customers from that agent.
2.10.Get aid values of agents not taking orders from any customer in ”Duluth” for any product in ”Dallas”.
2.11.Get cid values of customers who make orders only through agents ”a03” or ”a05”.
Dr. Raj Sunderraman
140
SQL – Structured Query Language
APPLICATION PROGRAMMING
This slide intentionally left blank.
Dr. Raj Sunderraman
141