142
SQL – STRUCTURED QUERY LANGUAGE Dr. Raj Sunderraman Computer Science Department Georgia State University .

TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

  • Upload
    others

  • View
    15

  • Download
    0

Embed Size (px)

Citation preview

Page 1: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – STRUCTURED QUERY LANGUAGE

Dr. Raj Sunderraman

Computer Science DepartmentGeorgia State University

.

Page 2: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

TABLE OF CONTENTS

Page 3: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language Table Of Contents

* DATABASE APPROACHo Database/Database Management Systemo Database Approach vs. Traditional File Processing

* RELATIONAL MODEL OF DATAo Terminologyo Sample Database Instanceo Integrity Constraintso Relational Ruleso Relational Algebrao Querying database using Relational Algebra

* DATA DEFINITION IN SQLo Schema Definition in SQLo Simple Insertso Data Types

Dr. Raj Sunderraman 2

Page 4: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language Table Of Contents

* QUERYING IN SQLo Simple Select Statementso Subselectso Union and For All Querieso Aggregates/Group By/Havingo Group By/ Having clauseso Full Select Statement Syntaxo Conceptual Order of Evaluation of a Select Statement

* UPDATES IN SQLo Database Updates (insert, delete, update)

* ADDITIONAL FEATURES OF SQLo Viewso Indexeso Tips to increase query efficiencyo Transactionso Triggerso Catalogo Security and Sharing

* APPLICATION PROGRAMMINGo Embedded-SQL (E-SQL)

Dr. Raj Sunderraman 3

Page 5: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

DATABASE APPROACH

Page 6: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language DATABASE APPROACH

This slide intentionally left blank.

Dr. Raj Sunderraman 5

Page 7: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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 andprovides 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

Page 8: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language DATABASE APPROACH

Database Approach vs. Traditional File Processing

• Self contained nature of database systems (database contains both data andmeta-data).

• Data Independence: application programs and queries are independent ofhow 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

Page 9: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

RELATIONAL MODEL OF DATA

Page 10: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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

• 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 isan 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 thesame scheme.Example: {(’c001’,’TipTop’, ’Duluth’,10),(’c002’,’Basics’, ’Dallas’,null)} is arelation over scheme R.

Dr. Raj Sunderraman 9

Page 11: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language RELATIONAL MODEL OF DATA

Basically,

• A relation over scheme R=(A1, ..., An) can be viewed as a table consisting of ncolumns and a finite set of rows.

• Each column corresponds to an attribute name and

• Each row corresponds to a tuple within the relation.

Relation --- TableAttribute Name --- Column NameTuple --- Row

Dr. Raj Sunderraman 10

Page 12: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language RELATIONAL MODEL OF DATA

Sample Database Instance

customersCID CNAME CITY DISCNT---- ------------- -------------------- ----------c001 Tiptop Duluth 10c002 Basics Dallas 12c003 Allied Dallas 8c004 ACME Duluth 8c006 ACME Kyoto 0

Dr. Raj Sunderraman 11

Page 13: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language RELATIONAL MODEL OF DATA

agentsAID ANAME CITY PERCENT--- ------------- -------------------- ----------a01 Smith New York 6a02 Jones Newark 6a03 Brown Tokyo 7a04 Gray New York 6a05 Otasi Duluth 5a06 Smith Dallas 5

Dr. Raj Sunderraman 12

Page 14: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language RELATIONAL MODEL OF DATA

productsPID PNAME CITY QUANTITY PRICE--- ------------- -------------------- ---------- ----------p01 comb Dallas 111400 .5p02 brush Newark 203000 .5p03 razor Duluth 150600 1p04 pen Duluth 125300 1p05 pencil Dallas 221400 1p06 folder Dallas 123100 2p07 case Newark 100500 1

Dr. Raj Sunderraman 13

Page 15: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language RELATIONAL MODEL OF DATA

ordersORDNO MON CID AID PID QTY DOLLARS----- --- ---- --- --- ---------- ----------1011 jan c001 a01 p01 1000 4501012 jan c001 a01 p01 1000 4501019 feb c001 a02 p02 400 1801017 feb c001 a06 p03 600 5401018 feb c001 a03 p04 600 5401023 mar c001 a04 p05 500 4501022 mar c001 a05 p06 400 7201025 apr c001 a05 p07 800 7201013 jan c002 a03 p03 1000 8801026 may c002 a05 p03 800 7041015 jan c003 a03 p05 1200 11041014 jan c003 a03 p05 1200 11041021 feb c004 a06 p01 1000 4601016 jan c006 a01 p01 1000 5001020 feb c006 a03 p07 600 6001024 mar c006 a06 p01 800 400

Dr. Raj Sunderraman 14

Page 16: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language RELATIONAL MODEL OF DATA

Integrity Constraints

Integrity Constraints are conditions that must be satisfied by the database at alltimes. 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 differentrows with the same values under primary key columns.

Dr. Raj Sunderraman 15

Page 17: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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 remainingkeys are called candidate keys.The candidate key constraint indicates that the table cannot contain twodifferent rows with the same values under candidate key columns.

• foreign keys (referential integrity): Many a times, it is necessary to includecolumn 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 tablemakes it a foreign key in the orders table.This constraint forces every CID value in the orders table to be also present inthe customers table.

Dr. Raj Sunderraman 16

Page 18: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language RELATIONAL MODEL OF DATA

Relational Rules

1. First Normal Form: Domains must be atomic. i.e multi-valued fields are notallowed. 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., wecannot 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), thereshould be no duplicates.

4. Entity integrity rule: Primary Key columns in a table CANNOT contain nullvalues.

Dr. Raj Sunderraman 17

Page 19: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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

Page 20: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language RELATIONAL MODEL OF DATA

R S R union S R - SA B C D E F A B C A B C------- ------- ------- -------a b c b g a a b c a b cd a f d a f d a f c b dc b d c b d

b g a

R intersection S R x SA B C A B C D E F------- ----------------d a f a b c b g a

a b c d a fd a f b g ad a f d a fc b d b g ac b d d a f

Dr. Raj Sunderraman 19

Page 21: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language RELATIONAL MODEL OF DATA

R S T select[B="b"](R)A B C D C D E C D A B C D---------- ------- ---- ----------a b c d c d e c d a b c da b e f c d f e f a b e fb c e f d e f a b d ee d c de d e fa b d e

project[A,B](R) R join S R div TA B A B C D E A B---- ------------- ----a b a b c d e a bb c a b c d f e de d e d c d e

e d c d fa b d e f

Dr. Raj Sunderraman 20

Page 22: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language RELATIONAL MODEL OF DATA

Querying database using Relational Algebra

(1) Get cnames of customers who live in "New York" andorder product "p01".

T1 = customers join ordersT2 = 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

Page 23: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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 placedby agents in "Dallas" or "Duluth"

T1 = agents join ordersT2 = project[pid](select[city="Dallas"](T1))T3 = project[pid](select[city="Duluth"](T1))RESULT = T2 union T3

Dr. Raj Sunderraman 22

Page 24: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language RELATIONAL MODEL OF DATA

(5) Get cids of customers who place orders through ALLagents 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

Page 25: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

DATA DEFINITION IN SQL

Page 26: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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

Page 27: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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

Page 28: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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

Page 29: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language DATA DEFINITION IN SQL

Simple Inserts

insert into customersvalues (’c001’,’Tiptop’,’Duluth’,10.00);

insert into customersvalues (’c002’,’Basics’,’Dallas’,12.00);

insert into customersvalues (’c003’,’Allied’,’Dallas’,8.00);

insert into customersvalues (’c004’,’ACME’,’Duluth’,8.00);

insert into customersvalues (’c006’,’ACME’,’Kyoto’,0.00);

Dr. Raj Sunderraman 28

Page 30: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language DATA DEFINITION IN SQL

Data Types

CHAR[(n)] character string of length nVARCHAR string of upto 256 characters; variable

lengthSMALLINT -32767 to + 32767INTEGER or INT -2 billion to + 2 billionDECIMAL[(m[,n])] decimal floating point numbers with m

digits (n decimal digits)SMALLFLOAT real numbers (upto 8 significant digits)FLOAT[n] double precisionDATE dates (12-MAR-96)MONEY[(m[,n])] money ($12.30)TEXT upto 2 GBytes of textual dataBYTE upto 2 GBytes of binary data

Dr. Raj Sunderraman 29

Page 31: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

QUERYING IN SQL

Page 32: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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

Page 33: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

(1) Find aid values and names of agents that arebased in New York.

SQL> select aid, anamefrom agentswhere city = ’New York’;

AID ANAME--- -------------a01 Smitha04 Gray

Dr. Raj Sunderraman 32

Page 34: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

(2) Print all rows in Customers table.

SQL> select *from customers;

CID CNAME CITY DISCNT---- ------------- -------------------- ----------c001 Tiptop Duluth 10c002 Basics Dallas 12c003 Allied Dallas 8c004 ACME Duluth 8c006 ACME Kyoto 0

Dr. Raj Sunderraman 33

Page 35: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

(3) Get pid values for parts for which orders havebeen placed. Eliminate duplicate answers.

SQL> select distinct pidfrom orders;

PID---p01p02p03......

7 rows selected.

Dr. Raj Sunderraman 34

Page 36: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

(4) String Comparisons: Get customers whose name begin withletter "A".

SQL> select *from customerswhere cname like ’A%’;

CID CNAME CITY DISCNT---- ------------- -------------------- ----------c003 Allied Dallas 8c004 ACME Duluth 8c006 ACME Kyoto 0

Underscore(_) : wildcard for any single characterPercent(%) : wildcard for any sequence of zero or more

characters.

Dr. Raj Sunderraman 35

Page 37: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

(5) Get cname, aname pairs such that the customerhas placed an order through the agent.

SQL> select distinct cname, anamefrom customers, orders, agentswhere customers.cid = orders.cid and

orders.aid = agents.aid;

CNAME ANAME------------- -------------ACME BrownACME Smith......

10 rows selected.

Dr. Raj Sunderraman 36

Page 38: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

(6) For each order, get ordno, cid, aid, pidvalues along with profit made on that order.Profit is calculated by selling priceminus 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 pwhere c.cid = x.cid and

a.aid = x.aid andp.pid = x.pid;

Dr. Raj Sunderraman 37

Page 39: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

ORDNO CID AID PID PROFIT---------- ---- --- --- ----------

1011 c001 a01 p01 1201012 c001 a01 p01 1201019 c001 a02 p02 481025 c001 a05 p07 2001017 c001 a06 p03 150

...

...

16 rows selected.

Dr. Raj Sunderraman 38

Page 40: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

(7) Get all pairs of cids for customers based inthe same city.

SQL> select c1.cid, c2.cidfrom customers c1, customers c2where c1.city = c2.city and c1.cid < c2.cid;

CID CID---- ----c002 c003c001 c004

Dr. Raj Sunderraman 39

Page 41: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

(8) Get pid values for products that have beenordered by at least two customers.

SQL> select distinct x1.pidfrom orders x1, orders x2where x1.pid = x2.pid and x1.cid < x2.cid;

PID---p01p03p05p07

Dr. Raj Sunderraman 40

Page 42: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

(9) Get cid values for customers who order a productfor which an order is placed by agent "a06".

SQL> select distinct y.cidfrom orders x, orders ywhere y.pid = x.pid and x.aid = ’a06’;

CID----c001c002c004c006

Dr. Raj Sunderraman 41

Page 43: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

(10) Get cid values of customers whose discount is between5 and 10.

SQL> select cidfrom customerswhere discnt between 5 and 10;

CID----c001c003c004

Dr. Raj Sunderraman 42

Page 44: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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 thesub-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

Page 45: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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

Page 46: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

(1) Get cid values of customers who place orders withagents in "Dallas" or "Duluth".

First we get aids of agents in "Dallas" or"Duluth":

SQL> select aidfrom agentswhere city = ’Duluth’ or city = ’Dallas’;

AID---a05a06

Dr. Raj Sunderraman 45

Page 47: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

Then we use the previous select in the searchcondition of the following select statement:

SQL> select distinct cidfrom orderswhere aid in (select aid

from agentswhere city = ’Duluth’ or

city = ’Dallas’);

CID----c001c002c004c006

Dr. Raj Sunderraman 46

Page 48: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

(2) Get all information about agents in "Dallas" or"Duluth".

SQL> select *from agentswhere city in (’Duluth’, ’Dallas’);

AID ANAME CITY PERCENT--- ------------- -------------------- ----------a05 Otasi Duluth 5a06 Smith Dallas 5

Dr. Raj Sunderraman 47

Page 49: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

(3) Multiple nesting: Get names and discounts ofcustomers who place orders through agents in"Dallas" or "Duluth".

SQL> select cname, discntfrom customerswhere cid in

(select cidfrom orderswhere aid in

(select aidfrom agentswhere city in

(’Duluth’, ’Dallas’)));

Dr. Raj Sunderraman 48

Page 50: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

CNAME DISCNT------------- ----------Tiptop 10Basics 12ACME 8ACME 0

Dr. Raj Sunderraman 49

Page 51: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

(4) Correlated sub-select: subselect that uses datafrom an outer select.Get names of customers who order product "p05".

SQL> select cnamefrom customerswhere ’p05’ in (select pid

from orderswhere cid = customers.cid);

CNAME-------------TiptopAllied

Dr. Raj Sunderraman 50

Page 52: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

(5) Scope of variables: outer select cannot refer tovariables inside inner-selects.

SQL> select cnamefrom customerswhere orders.aid = ’a03’ and

’p07’ in (select pidfrom orderswhere cid = customers.cid);

** ILLEGAL SQL SYNTAX ** as outer select refers toorders.aid

Dr. Raj Sunderraman 51

Page 53: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

(6) Get ordno values for orders placed by customersin "Duluth" through agents in "New York".

SQL> select ordnofrom orderswhere cid in (select cid

from customerswhere city = ’Duluth’) and

aid in (select aidfrom agentswhere city = ’New York’);

ORDNO----------

101110121023

Dr. Raj Sunderraman 52

Page 54: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

The general forms of quantified comparison predicates:

expr <any (sub-select)expr <=any (sub-select)expr =any (sub-select)expr <>any (sub-select)expr >any (sub-select)expr >=any (sub-select)

expr <all (sub-select)expr <=all (sub-select)expr =all (sub-select)expr <>all (sub-select)expr >all (sub-select)expr >=all (sub-select)

Dr. Raj Sunderraman 53

Page 55: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

(7) Get aid values of agents with the smallestpercent commission.

SQL> select aidfrom agentswhere percent <=all (select percent

from agents);

AID---a05a06

Dr. Raj Sunderraman 54

Page 56: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

(8) Get names of customers who have the same discountas that of any (one) of the customers in "Dallas"or "Boston".

SQL> select cnamefrom customerswhere discnt =any (select discnt

from customerswhere city = ’Dallas’ or

city = ’Boston’);CNAME-------------AlliedACMEBasics

Dr. Raj Sunderraman 55

Page 57: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

(9) Get cid values of customers with smallerdiscounts than every customer from "Duluth".

SQL> select cidfrom customerswhere discnt <all (select discnt

from customerswhere city = ’Duluth’);

CID----c006

Dr. Raj Sunderraman 56

Page 58: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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

Page 59: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

(10) Get names of customers who have placed an orderthrough agent "a05".

SQL> select c.cnamefrom customers cwhere exists (select *

from orders xwhere c.cid = x.cid and

x.aid = ’a05’);

CNAME-------------TiptopBasics

Dr. Raj Sunderraman 58

Page 60: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

An equivalent SQL query without exists predicate:

SQL> select c.cnamefrom customers c, orders xwhere c.cid = x.cid and x.aid = ’a05’;

Dr. Raj Sunderraman 59

Page 61: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

(11) Get cid values of customers who have placed anorder for both "p01" and "p07".

SQL> select cidfrom orders xwhere pid = ’p01’ and

exists (select *from orderswhere cid = x.cid and

pid = ’p07’);CID----c001c001c006c006

Dr. Raj Sunderraman 60

Page 62: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

An equivalent SQL query without exists predicate:

SQL> select x.cidfrom orders x, orders ywhere x.pid = ’p01’ and

x.cid = y.cid andy.pid = ’p07’;

Dr. Raj Sunderraman 61

Page 63: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

(12) Get names of customers who do not place ordersthrough agent "a05".

SQL> select c.cnamefrom customers cwhere not exists (select *

from orders xwhere c.cid = x.cid and

x.aid = ’a05’);CNAME-------------AlliedACMEACME

Dr. Raj Sunderraman 62

Page 64: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

Two alternate solutions (using not in and <>all):

SQL> select c.cnamefrom customers cwhere c.cid not in (select cid

from orderswhere aid = ’a05’);

SQL> select c.cnamefrom customers cwhere c.cid <>all (select cid

from orderswhere aid = ’a05’);

Dr. Raj Sunderraman 63

Page 65: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

(13) Too many ways to write an SQL query!!Get city names of customers who have placedan order for "p01".

SQL> select distinct cityfrom customerswhere cid in (select cid

from orderswhere pid = ’p01’);

SQL> select distinct cityfrom customerswhere cid =any (select cid

from orderswhere pid = ’p01’);

Dr. Raj Sunderraman 64

Page 66: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

SQL> select distinct cityfrom customers cwhere exists (select *

from orderswhere cid = c.cid and

pid = ’p01’);

SQL> select distinct cityfrom customers c, orders xwhere x.cid = c.cid and x.pid = ’p01’;

SQL> select distinct cityfrom customers cwhere ’p01’ in (select pid

from orderswhere cid = c.cid);

Dr. Raj Sunderraman 65

Page 67: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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

Page 68: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

(1) Get cities in which customers or agents arelocated.

SQL> select cityfrom customersunionselect cityfrom agents;

CITY--------------------DallasDuluthKyotoNew YorkNewarkTokyo

Dr. Raj Sunderraman 67

Page 69: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

The following will not eliminate duplicates:

SQL> select cityfrom customersunion allselect cityfrom agents;

CITY--------------------DuluthDallasDallasDuluth...

11 rows selected.

Dr. Raj Sunderraman 68

Page 70: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

(2) Get cid values of customers who place orderswith ALL agents in "New York".

Get cid values of customers such that(the set of agents from "New York"through whom the customer has NOTplaced an order) is EMPTY.

SQL> select c.cid CIDfrom customers c ----where not exists c001

(select *from agents awhere a.city = ’New York’ and

not exists (select *from orders xwhere x.cid = c.cid and

x.aid = a.aid));

Dr. Raj Sunderraman 69

Page 71: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

(3) Get aid values of agents from "New York" or "Duluth" whoplace orders for ALL products priced over one dollar.

Get aid values of agents from "New York" or "Duluth" suchthat (the set of products priced over one dollar

that the agent has NOT ordered) is EMPTY.

SQL>select a.aid AIDfrom agents a ---where (a.city in (’New York’,’Duluth’)) and a05

not exists (select p.pidfrom products pwhere p.price > 1.00 and

not exists (select *from orders xwhere x.pid = p.pidand x.aid = a.aid));

Dr. Raj Sunderraman 70

Page 72: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

(4) Get cid values for customers who order ALL productsordered 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 CIDfrom customers c ----where not exists c001

(select p.pid c006from products pwhere p.pid in (select pid

from orders xwhere x.cid = ’c006’) and

not exists (select *from orders ywhere y.pid = p.pid and

y.cid = c.cid));

Dr. Raj Sunderraman 71

Page 73: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

A variant is:

SQL> select cidfrom customers cwhere not exists

(select z.pidfrom orders zwhere z.cid = ’c006’ and

not exists(select *from orders ywhere y.pid = z.pid and

y.cid = c.cid));

Dr. Raj Sunderraman 72

Page 74: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

(5) Get pid values of products that are supplied toall 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 PIDfrom products p ---where not exists p01

(select c.cidfrom customers cwhere c.city = ’Duluth’ and

not exists(select *from orders xwhere x.pid = p.pid and

x.cid = c.cid));

Dr. Raj Sunderraman 73

Page 75: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

Aggregates/Group By/Having

SQL supports count, sum, avg, max, min functions.

Name Argument Type Result Type Descriptioncount any (can be *) numeric count of occurrencessum numeric numeric sum of argumentsavg numeric numeric average of argumentsmax char or numeric same as argument maximum valuemin char or numeric same as argument minimum value

Dr. Raj Sunderraman 74

Page 76: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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

Page 77: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

(2) Get total quantity of product "p03" that has been ordered.

SQL> select sum(qty) TOTALfrom orderswhere pid = ’p03’;

TOTAL----------

2400

Dr. Raj Sunderraman 76

Page 78: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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

Page 79: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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 anincorrect result:

SQL> select count(city)from customers;

COUNT(CITY)-----------

5

Dr. Raj Sunderraman 78

Page 80: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

(5) Get cid values of customers who have a discount less thanthe maximum discount.

SQL> select cidfrom customerswhere discnt < (select max(discnt)

from customers);

CID----c001c003c004c006

Dr. Raj Sunderraman 79

Page 81: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

(6) Get pids of products ordered by at least two customers.

SQL> select p.pidfrom products pwhere 2 <= (select count(distinct cid)

from orderswhere pid = p.pid);

PID---p01p03p05p07

Dr. Raj Sunderraman 80

Page 82: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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 customerswhere discnt <= 10 or discnt > 10;

CID CNAME CITY DISCNT---- ------------- -------------------- ----------c001 Tiptop Duluth 10c002 Basics Dallas 12c003 Allied Dallas 8c004 ACME Duluth 8c006 ACME Kyoto 0

Newly created row not in result!

Dr. Raj Sunderraman 81

Page 83: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

SQL> select *from customerswhere discnt is null;

CID CNAME CITY DISCNT---- ------------- -------------------- ----------c007 Windix Dallas

Newly created row is in result.

Dr. Raj Sunderraman 82

Page 84: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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

Page 85: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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 oncolumn 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

Page 86: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

(1) For each (aid,pid) pair get the sum of the ordersaid has placed for pid.

SQL> select pid, aid, sum(qty) TOTALfrom ordersgroup by pid, aid;

PID AID TOTAL--- --- ----------p01 a01 3000p01 a06 1800p02 a02 400p03 a03 1000p03 a05 800......

12 rows selected.

Dr. Raj Sunderraman 85

Page 87: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

(2) Get agent name, agent id, product name, product id,together with total quantity each agent supplies ofthat product to customers "c002" and "c003".

SQL> select aname, a.aid, pname, p.pid, sum(qty)from orders x, products p, agents awhere 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 AID PNAME PID SUM(QTY)------------- --- ------------- --- ----------Brown a03 razor p03 1000Otasi a05 razor p03 800Brown a03 pencil p05 2400

Note: The where clause is evaluated before groups are formed.

Dr. Raj Sunderraman 86

Page 88: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

(3) Get product ids and total quantity ordered for eachproduct when the total exceeds 1000.

SQL> select pid, aid, sum(qty) TOTALfrom ordersgroup by pid, aidhaving sum(qty) > 1000;

PID AID TOTAL--- --- ----------p01 a01 3000p01 a06 1800p05 a03 2400

Dr. Raj Sunderraman 87

Page 89: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

(4) Get pids of products that are ordered by at least twocustomers.

SQL> select pid from ordersgroup by pidhaving count(distinct cid) >= 2;

PID---p01p03p05p07

Dr. Raj Sunderraman 88

Page 90: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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 querybased on column values.

Dr. Raj Sunderraman 89

Page 91: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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 thesearch 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 areeliminated.

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

7. The union is taken after each sub-select is evaluated.

8. Finally, the resulting rows are sorted according to the columns specified in theorder by clause.

Dr. Raj Sunderraman 90

Page 92: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language QUERYING IN SQL

(1) Get names and ids of customers and agents along withtotal dollar sales for that pair. Order the resultfrom largest to smallest total sales. Also retainonly those pairs for which total dollar sales isat least 900.00.

SQL> select c.cname, c.cid, a.aname, a.aid, sum(o.dollars)from customers c, orders o, agents awhere c.cid = o.cid and o.aid = a.aidgroup by c.cname, c.cid, a.aname, a.aidhaving sum(o.dollars) >= 900.00order by 5 desc;

CNAME CID ANAME AID SUM(O.DOLLARS)------------- ---- ------------- --- --------------Allied c003 Brown a03 2208Tiptop c001 Otasi a05 1440Tiptop c001 Smith a01 900

Dr. Raj Sunderraman 91

Page 93: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

UPDATES IN SQL

Page 94: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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

Page 95: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language UPDATES IN SQL

(1) Insert into the orders table.

SQL> insert into ordersvalues (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

Page 96: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language UPDATES IN SQL

SQL> select *from orders;

ORDNO MON CID AID PID QTY DOLLARS---------- --- ---- --- --- ---------- ----------

1011 jan c001 a01 p01 1000 4501012 jan c001 a01 p01 1000 450

...

...1111 sep c003 a05 p02 500 10001107 aug c006 a04 p01

17 rows selected.

Note the two rows that were inserted in previous slide.

Dr. Raj Sunderraman 95

Page 97: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language UPDATES IN SQL

(2) Create a new table "swcusts" with same fields ascustomers and insert rows from "customers" tablewith city field equals "Dallas" or "Austin".

SQL> select *from customers;

CID CNAME CITY DISCNT---- ------------- -------------------- ----------c001 Tiptop Duluth 10c002 Basics Dallas 12 <<c003 Allied Dallas 8 <<c004 ACME Duluth 8c006 ACME Kyoto 0c007 Windix Dallas <<

6 rows selected.

Dr. Raj Sunderraman 96

Page 98: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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 swcustsselect *from customerswhere city in (’Dallas’,’Austin’);

3 rows created.

Dr. Raj Sunderraman 97

Page 99: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language UPDATES IN SQL

SQL> select *from swcust;

CID CNAME CITY DISCNT---- ------------- -------------------- ----------c002 Basics Dallas 12c003 Allied Dallas 8c007 Windix Dallas

Dr. Raj Sunderraman 98

Page 100: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language UPDATES IN SQL

(3) Increase the percent commission by 50% for allagents in "New York".

SQL> update agentsset percent = 1.5 * percentwhere city = ’New York’;

2 rows updated.SQL> select * from agents;

AID ANAME CITY PERCENT--- ------------- ------------ ----------a01 Smith New York 9 << old value = 6a02 Jones Newark 6a03 Brown Tokyo 7a04 Gray New York 9 << old value = 6a05 Otasi Duluth 5a06 Smith Dallas 5

Dr. Raj Sunderraman 99

Page 101: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language UPDATES IN SQL

(4) Delete all agents from "New York".

SQL> delete from agentswhere city = ’New York’;

2 rows deleted.

SQL> select *from agents;

AID ANAME CITY PERCENT--- ------------- -------------------- ----------a02 Jones Newark 6a03 Brown Tokyo 7a05 Otasi Duluth 5a06 Smith Dallas 5

Dr. Raj Sunderraman 100

Page 102: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language UPDATES IN SQL

(5) Delete all agents who have total orders of less than $600.

SQL> delete from agentswhere aid in (select aid

from ordersgroup by aidhaving sum(dollars) < 600);

1 row deleted.

SQL> select *from agents;

AID ANAME CITY PERCENT--- ------------- -------------------- ----------a03 Brown Tokyo 7a05 Otasi Duluth 5a06 Smith Dallas 5

Dr. Raj Sunderraman 101

Page 103: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

ADDITIONAL FEATURES OF SQL

Page 104: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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 includederived 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 theusers 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

Page 105: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language ADDITIONAL FEATURES OF SQL

SQL> CREATE VIEW dallas_cust ASselect *from customerswhere city = ’Dallas’;

View created.

SQL> select *from dallas_cust;

CID CNAME CITY DISCNT---- ------------- -------------------- ----------c002 Basics Dallas 12c003 Allied Dallas 8

Dr. Raj Sunderraman 104

Page 106: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language ADDITIONAL FEATURES OF SQL

SQL> CREATE VIEW tot_sales_per_agent ASselect agents.aid, aname, sum(dollars) TOT_SALESfrom agents,orderswhere agents.aid = orders.aidgroup by agents.aid,aname;

View CreatedSQL> select *

from tot_sales_per_agent;

AID ANAME TOT_SALES--- ------------- ----------a01 Smith 1400a02 Jones 180a03 Brown 4228a04 Gray 450a05 Otasi 2144a06 Smith 1400

Dr. Raj Sunderraman 105

Page 107: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language ADDITIONAL FEATURES OF SQL

Indexes

Indexes are mechanisms to speed up retrieval of data.

CREATE [UNIQUE|CLUSTER] INDEX index-nameON table-name (column-list)

DROP INDEX index-name

• unique index will ensure that two different rows do not have the same valueunder the indexed columns

• clustered index will ensure that rows with same values are kept next to eachother on disk

CREATE UNIQUE INDEX cust_index ON customers(cid);CREATE UNIQUE INDEX agent_index ON agents(aid);CREATE UNIQUE INDEX prod_index ON products(pid);CREATE UNIQUE INDEX ord_index ON orders(ordno);CREATE CLUSTER INDEX month_index ON orders(month);

Dr. Raj Sunderraman 106

Page 108: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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

Page 109: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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

Page 110: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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 500Account 1112 with balance 600.

To qualify for a loan, a customer must haveat least $1000 in all of his accounts.

Dr. Raj Sunderraman 109

Page 111: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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;t6will result in a DENY LOAN situation, which is erroneous.

Dr. Raj Sunderraman 110

Page 112: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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 awhole 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 WORKstatement.

BEGIN WORKLOCK TABLE accountUPDATE account SET balance = balance - 400WHERE account_id = 1111;UPDATE account SET balance = balance + 400WHERE account_id = 1112;COMMIT WORK;

Dr. Raj Sunderraman 111

Page 113: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language ADDITIONAL FEATURES OF SQL

Triggers

• An SQL Trigger is a mechanism that automatically executes a specified set ofSQL 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, EXECUTEPROCEDURE

Dr. Raj Sunderraman 112

Page 114: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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

Page 115: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language ADDITIONAL FEATURES OF SQL

(1) Enforcing Referential Integrity Constraint.Upon deleting a customer record, automaticallydelete all orders for that customer from theorders table.

CREATE TRIGGER del_custDELETE ON customersREFERENCING OLD AS pre_delFOR EACH ROW (DELETE FROM orders WHERE cid = pre_del.cid);

Dr. Raj Sunderraman 114

Page 116: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language ADDITIONAL FEATURES OF SQL

(2) Creating an Audit Trail.Each time someone updates the quantity of a particularproduct, make an entry in a log file of this updatealong with the name of the person doing the update andthe date of update.

CREATE TABLE log (pid varchar(3),username char(8),update_date date,old_qty integer,new_qty integer);

CREATE TRIGGER upd_prodUPDATE OF quantity ON productsREFERENCING OLD AS pre_upd NEW AS post_updFOR EACH ROW (INSERT INTO log

values (pre_upd.pid,USER,CURRENT,pre_upd.quantity,post_upd.quantity));

Dr. Raj Sunderraman 115

Page 117: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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

Page 118: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language ADDITIONAL FEATURES OF SQL

CREATE TRIGGER upd_prodUPDATE OF quantity ON productsBEFORE(EXECUTE PROCEDURE upd_prod_1())AFTER(EXECUTE PROCEDURE upd_prod_2());

Note: If a trigger fails, INFORMIX automatically rollbacks allchanges.

Dr. Raj Sunderraman 117

Page 119: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language ADDITIONAL FEATURES OF SQL

Catalog

• The system catalog contains a wealth of information about the databasestructure.

• Information such as names of tables, their columns, who owns them, names ofviews, view definitions, indexes, constraints, stored procedures, etc. arecommonly 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

Page 120: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language ADDITIONAL FEATURES OF SQL

systablestabname char(18)tabid integerowner char(8)ncols smallintnrows integercreated datetabtype char(1) ; T = table, V = view

sysusersusername char(8)usertype char(1) ; D = DBA, R = resource, C = connect

syscolumnscolname char(18)tabid integercolno smallintcoltype smallint ; 0 = CHAR, 1 = SMALLINT, ...

Dr. Raj Sunderraman 119

Page 121: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language ADDITIONAL FEATURES OF SQL

select tabname, tabidfrom systableswhere owner = ’RAJ’;

select colnamefrom syscolumnswhere tabid in (select tabid

from systableswhere tabname = ’customers’);

Dr. Raj Sunderraman 120

Page 122: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language ADDITIONAL FEATURES OF SQL

Other Useful Commands:

INFO TABLESlists all tables owned by you

INFO COLUMNS FOR customerslists all columns for customer table

INFO INDEXES FOR customerslists all indexes for customers table

INFO STATUS FOR customerslists status info for customers table(owner, no. of rows, no. of columns,date created etc.)

Dr. Raj Sunderraman 121

Page 123: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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 haveauthority to).

• Resource Privilege: in addition to connect privileges, allows users to createnew 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

Page 124: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language ADDITIONAL FEATURES OF SQL

Table-level privileges:

GRANT [select|insert|delete|update(col-names)]ON table_nameTO [user|PUBLIC];

REVOKE [select|insert|delete|update(col-names)|ALL]ON table_nameFROM [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

Page 125: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

APPLICATION PROGRAMMING

Page 126: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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

• Need a mechanism to communicate values between database server andhigh-level program environment.

• Special variables (called host variables) are defined in the program for thispurpose.

• 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

Page 127: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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 :cnamefrom customerswhere 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

Page 128: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language APPLICATION PROGRAMMING

Indicator Variables: integer variables which are used to indicate if a null value isfetched 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 discntinto :cust_discount:cd_indfrom customerswhere 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

Page 129: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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_indwhere cid = :cust_id;

Dr. Raj Sunderraman 128

Page 130: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language APPLICATION PROGRAMMING

SQL Communications Area (sqlca):

• Immediately after the Database Server executes an embedded SQLstatement, it reports the status of the execution in some variables defined insqlca.

• An important field in the sqlca structure is SQLCODE. The Database Serverreturns a value of 0 if the execution was a success; a value of 100 if no moredata 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

Page 131: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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

Page 132: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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, discntFROM 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

Page 133: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language APPLICATION PROGRAMMING

Delete and Update using cursors:Delete all customers from the customers table who live in ”Duluth” and havemade no orders:

Without cursor:

EXEC SQL delete from customers cwhere c.city = ’Duluth’ and

not exists (select *from orders owhere c.cid = o.cid);

Dr. Raj Sunderraman 132

Page 134: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language APPLICATION PROGRAMMING

With Cursor:

EXEC SQL declare del_cust cursor forselect cidfrom customers cwhere c.city = ’Duluth’ and

not exists (select *from orders owhere 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

Page 135: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language APPLICATION PROGRAMMING

Recursive Query:

SQL> create table employees (eid integer,mgrid integer);

SQL> select *from employees;

EID MGRID---------- ----------

2 13 14 25 26 47 6

Given a employee, print all the employees who work under that employee at alllevels.

Dr. Raj Sunderraman 134

Page 136: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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 forselect eid from employees where mgrid = :eid;

/* answer(X) if employees(X,Y) and answer(Y) */exec sql declare c2 cursor forselect 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

Page 137: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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

Page 138: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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

Page 139: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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

Page 140: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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 inthe 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

Page 141: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

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

Page 142: TABLE OF CONTENTS - Georgia State Universitytinman.cs.gsu.edu/~raj/sql/sqltut.pdfSQL – Structured Query Language RELATIONAL MODEL OF DATA Terminology Relation Scheme: list of attribute

SQL – Structured Query Language APPLICATION PROGRAMMING

This slide intentionally left blank.

Dr. Raj Sunderraman 141