0% found this document useful (0 votes)
96 views

BCI2023 Chapter7 SQL v1.2 PDF

Structured Query Language (SQL) is used to manipulate and retrieve data from relational databases. The main SQL commands are DDL for defining database schema, DML for manipulating data, and DCL for controlling access. DDL includes commands like CREATE, ALTER, DROP to work with tables, indexes, and databases. DML includes INSERT to add data, UPDATE and DELETE to modify data, and SELECT to query data. Integrity constraints must be satisfied for DML operations.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
96 views

BCI2023 Chapter7 SQL v1.2 PDF

Structured Query Language (SQL) is used to manipulate and retrieve data from relational databases. The main SQL commands are DDL for defining database schema, DML for manipulating data, and DCL for controlling access. DDL includes commands like CREATE, ALTER, DROP to work with tables, indexes, and databases. DML includes INSERT to add data, UPDATE and DELETE to modify data, and SELECT to query data. Integrity constraints must be satisfied for DML operations.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 102

Chapter 7:

Structured Query Language


(SQL)
Learning Outcomes
At the end of this chapter students SHOULD
be able to:
• Construct SQL commands to create tables
and indexes, insert/update/delete data,
and query data in a relational DBMS.
• Implement functions in SQL commands
• Construct data-intensive application using
DBMS.
Structured Query Language (SQL)
• SQL is a data manipulation language.
• SQL is not a programming language.
• SQL commands are interpreted by the DBMS
engine.
• SQL commands can be used interactively as a
query language within the DBMS.
• SQL commands can be embedded within
programming languages.
3 Types of SQL Commands
• Data Definition Language (DDL):
– Commands that define a database - Create, Alter,
Drop
• Data Manipulation Language (DML)
– Commands that maintain and query a database.
• Data Control Language (DCL)
– Commands that control a database, including
administering privileges and committing data.
Data Definition Language
(DDL)
Data Definition Language (DDL)
• Three basic commands:
• CREATE
• ALTER
• DROP
Create Database
• To define new database
• To create database
➢CREATE database {database_name}
• To use database
➢USE database {database_name}
Example:
➢CREATE database Company;
➢USE Company;
Create Tables
• To define new tables
• Steps in table creation:
➢Identify data types for attributes
➢Identify columns that can and cannot be null
➢Identify columns that must be unique (candidate keys)
➢Identify primary key–foreign key mates
➢Determine default values
➢Identify constraints on columns (domain specifications)
➢Create the table and associated indexes
General Syntax of Create Tables
Tables Creation for Data Model
Examples of Create Tables
Defining attributes & data types
Identifying Primary Key (PK)
Composite Primary Key (PK)
Establish Foreign Key (FK)
& Relationship

Foreign key of
dependent table
Controlling Attributes Values
SQL Data Types
Alter Tables
• ALTER TABLE statement allows you to change
column specifications:

• Table Actions:

• Example (adding a new column with a default value):


Drop Tables

• DROP TABLE statement allows you to


remove tables from your schema:

DROP TABLE {Table_Name};


E.g: DROP TABLE Company;
Data Manipulation Language
(DML)
Data Manipulation Language
(DML)

Four basic commands:


• INSERT
• UPDATE
• DELETE
• SELECT
Inserting Data into a Table

• INSERT INTO tablename (column-list) VALUES


(value-list)

• PUTS ONE ROW INTO A TABLE

• INSERT INTO COURSE


(COURSE_CODE, COURSE_NAME,
CREDIT_HOURS)
VALUES
(‘MIS499’,’ADVANCED ORACLE’,4);
More on Inserting Data
• INSERT INTO COURSE
VALUES (‘MIS499’,’ADVANCED ORACLE’,4);

COLUMN LIST IS OPTIONAL IF YOU PLAN TO


INSERT A VALUE IN EVERY COLUMN AND IN
THE SAME ORDER AS IN THE TABLE

• INSERT INTO COURSE


(COURSE_NAME, COURSE_CODE,
CREDIT_HOURS)
VALUES (’ADVANCED ORACLE’,‘MIS499’,4);
COLUMN LIST IS NEEDED
NOTE - TABLE STILL HAS THE
TO CHANGE THEORDER
ORIGINAL COLUMN ORDER
- MUST MATCH VALUE LIST
Inserting Null Data
• INSERT INTO COURSE
(COURSE_CODE, CREDIT_HOURS) VALUES (‘MIS499’,4);
COLUMN LIST IS NEEDED IF
YOU PLAN TO LEAVE OUT A
VALUE IN THE VALUE LIST

• INSERT INTO COURSE VALUES (‘MIS499’,’’,4);


COLUMN LIST CAN BE OMITTED
IF YOU PUT IN A BLANK VALUE

• INSERT INTO COURSE VALUES (‘MIS499’,NULL,4);


THE NULL KEYWORD CAN
BE USED TO CREATE A BLANK
COLUMN

ALL OF THESE ASSUME THAT THE DATABASE ALLOWS THE COLUMN TO


BE NULL. YOU CANNOT LEAVE PRIMARY KEYS AND FOREIGN KEYS BLANK
Inserting and Integrity Constraints
SQL> INSERT INTO SECTION VALUES
('1234','MIS333','10-12','MW','COPE101','200000000');
INSERT INTO SECTION
VALUES ('1234','MIS333','10-12','MW','COPE101',
*
ERROR at line 1:
ORA-02291: integrity constraint (ORA40.SYS_C00337)
violated - parent key not COURSE

found SECTION COURSE_CODE KEY


COURSE_NAME
CALL_NUMBER KEY CREDIT_HOURS
COURSE_CODE
SECTION_TIME INSTRUCTOR
SECTION_DAYS
SECTION_ROOM INSTRUCTOR_ID KEY
INSTRUCTOR_ID INSTRUCTOR_NAME
INSTRUCTOR_OFFICE
Entity Integrity Problems
SQL> INSERT INTO COURSE
VALUES ('MIS220','NEW',4);

insert into course values ('MIS220','NEW',4)


*
ERROR at line 1:
ORA-00001: unique constraint
(ORA40.SYS_C00335) violated
Deleting Data
Be careful, This deletes ALL of
the rows in your table. If you
DELETE COURSE; use this command in error, you
DELETES ALL ROWS can use ROLLBACK to undo
the changes.

DELETE COURSE WHERE COURSE_CODE =


‘MIS220’;
DELETES SPECIFIC ROWS (MORE TYPICAL)

DELETE COURSE WHERE HOURS=4;


DELETES A GROUP OF ROWS
DELETE COURSE WHERE HOURS<4;
Deleting and Integrity Constraints
SQL> DELETE COURSE
WHERE COURSE_CODE='MIS220';

DELETE COURSE WHERE


COURSE_CODE='MIS220'
*
ERROR at line 1:
ORA-02292: integrity constraint
(ORA40.SYS_C00341) violated - child record
found
Updating Data
UPDATE COURSE SET HOURS=5;
CHANGES EVERY ROW

UPDATE COURSE SET HOURS=5


WHERE COURSE_CODE=‘MIS220’
CHANGES ONE ROW (MORE TYPICAL)

UPDATE COURSE SET HOURS=3


WHERE COURSE_CODE LIKE ‘MIS%’
CHANGES A GROUP OF ROWS
Updating and Integrity Constraints

• You can change the value of a foreign key as


long as the new value also complies with
referential integrity constraints.

• Primary key values can be updated as long as


there are no rows in other tables with foreign
keys with the same value

• Does not matter if constraint is restricted or


cascaded
Integrity Error

SQL> UPDATE COURSE


SET COURSE_CODE='MIS221‘
WHERE COURSE_CODE='MIS220';
UPDATE COURSE
*
ERROR at line 1:
ORA-02292: integrity constraint (ORA40.SYS_C00341)
violated - child record found
Rollback and Commit
• Changes to data are temporary during your
mySQL session

• Does not apply to changes in database


structure - alter...

• Before leaving sqlplus, you can reverse them

Applies to inserts, updates, and deletes


Rollback and Commit

• SQL>ROLLBACK;
o Rollback complete.
o Reverses all changes to data made during your
session

• SQL>COMMIT;
o Makes all changes to this point permanent
o Points at which commit is issued, define extent of
rollback
o Rollback reverses every change since the last
commit
o Exiting sqlplus issues a commit
SQL for Retrieving Data from One Table

SELECT column_name, column_name, …


FROM table_name
WHERE condition/criteria;

• This statement will retrieve the specified field


values for all rows in the specified table that
meet the specified conditions.
• Every SELECT statement returns a recordset.
Conceptual Evaluation Strategy
• Semantics of an SQL query defined in terms of
the following conceptual evaluation strategy:
– Compute the cross-product of relation-list.
– Discard resulting tuples if they fail qualifications.
– Delete attributes that are not in target-list.
– If DISTINCT is specified, eliminate duplicate rows.
• This strategy is probably the least efficient way
to compute a query! An optimizer will find more
efficient strategies to compute the same
answers.
WHERE Conditions
SELECT * FROM COURSE
WHERE COURSE_CODE LIKE ‘MIS%’;
Use % to substitute for
Any string

SELECT * FROM COURSE


WHERE CREDIT HOURS BETWEEN 3 AND 5;
3 and 5 are included

SELECT * FROM CUSTOMER


WHERE BALANCE < CREDIT_LIMIT;
You can compare two columns
More WHERE Conditions

SELECT * FROM CUSTOMER


WHERE STATE IN (‘OH’,’WV’,’KY’);
List of specific values to
Look for

SELECT * FROM CUSTOMER


WHERE (CREDIT_LIMIT - BALANCE) <1000;

Can manipulate number


Values mathmatically
AND/OR/NOT Conditions
SELECT * FROM CUSTOMER
WHERE BALANCE >=500 Two comparisons
AND BALANCE<=1000; On the same column

SELECT * FROM CUSTOMER


WHERE STATE = ‘OH’ Two comparisons on the
OR CREDIT_LIMIT>1000; different columns

SELECT * FROM CUSTOMER


WHERE NOT (STATE=‘OH’); Same as State<>‘oh’
More on AND/OR/NOT
SELECT * FROM CUSTOMER
WHERE STATE = ‘OH’
OR (CREDIT_LIMIT=1000 Use parentheses to
AND BALANCE <500); make complex logic
more understandable.
CUST STATE LIMIT BAL
A OH 1000 600
B WV 1000 200
C OH 500 300
D OH 1000 200 Who will be selected??
E KY 1300 800
F KY 1000 700
G MA 200 100
H NB 1000 100
SQL - Other Features
• * - All columns in a table
• Aliases
– SELECT EmployeeID, LastName,
FirstName, BirthDate AS DOB FROM
Employee;
– SELECT EmployeeID, LastName,
FirstName, FROM Employee AS E;
• Dot Notation - ambiguous attribute names
– SELECT Customer.LName, E.Lname
FROM Customer, Employee AS E
WHERE ...
SQL - Other Features
• DISTINCT
• Arithmetic operators: +, -, *, /
• Comparison operators: =, >, >=, <, <=, <>
• Concatenation operator: ||
• Substring comparisons: %, _
• BETWEEN
• AND, OR
SQL - Other Features

• ORDER BY Clause
• UNION, EXCEPT, INTERSECT
• IN
SQL for Retrieving Data from
Two or More Tables
SQL provides two ways to retrieve data from related tables:
• Join - When two or more tables are joined by a common
field.
• Subqueries - When one Select command is nested within
another command.
JOINS TABLES
SQL - Joins
• The WHERE clause is used to specify the common
field.
• For every relationship among the tables in the
FROM clause, you need one WHERE condition (2
tables - 1 join, 3 tables - 2 joins…)
SELECT C.Cust_ID, Comp_Name, Country,OrderID
FROM Customer AS C, Order AS O
WHERE C.Cust_ID = O.Cust_ID
AND Country = ‘USA’;
SQL - Joins

• Inner Join - records from two tables are selected


only when the records have the same value in the
common field that links the tables (the default join).

• Outer Join - A join between two tables that returns


all the records from one table and, from the second
table, only those records in which there is a matching
value in the field on which the tables are joined.
Multi-Table Queries & Views
• Getting tables into 3NF eliminates
unnecessary redundancy, BUT now we
need data from multiple tables to create
some forms and reports.
TRANSCRIPT
STUDENT#: 444-44-4444
NAME: JOE STUDENT

CODE NAME HOURS GRADE QUAR/YR


MIS220 FILE PROC 4 A 389
ZOO100 BIOLOGY 3 B 288
PSY280 EXP PSY 4 B+ 190
Two-Table Query
DESIRED OUTPUT:
CALL-NUMBER 1234
REQUIRED NAVIGATION: COURSE_CODE MIS380
SECTION
SECTION_ROOM COPE012
INSTRUCTOR_ID 111111111
CALL_NUMBER INSTRUCTOR_NAME DAY
INSTRUCTOR
COURSE_CODE
SECTION_TIME
INSTRUCTOR_ID
SECTION_DAYS
INSTRUCTOR_NAME
SECTION_ROOM
INSTRUCTOR_OFFICE
INSTRUCTOR_ID JOIN

SECTION

1234 MIS380 8-10 WF COPE012 111111111

INSTRUCTOR

111111111 DAY COPE290A


SELECT Command with Join
SELECT CALL_NUMBER, COURSE_CODE,
SECTION_ROOM,
SECTION.INSTRUCTOR_ID, Two Tables
INSTRUCTOR_NAME ➔ One Join
FROM SECTION, INSTRUCTOR
WHERE SECTION.INSTRUCTOR_ID
= INSTRUCTOR.INSTRUCTOR_ID;
• The where clause is used to tell oracle how to match
rows between the two tables – requires a common key

• For column names whose location is ambiguous, you


must specify a table name - see instructor_id
Results
CALL COURS SECTION INSTRU INSTR_NAME
---- -------- -------- ---------- -------------------
0030 MIS300 COPE112 500000000 SUTHERLAND
0031 MIS300 COPE112 260000000 CHEN
0032 MKT301 COPE633 180000000 KIRCH
0033 MKT301 COPE107 180000000 KIRCH
0034 BUSL255 COPE001 260000000 CHEN
0035 OPN310 COPE107 190000000 CUTRIGHT
0036 OPN310 COPE108 240000000 JDAY
Joining More Than Two Tables
STUDENT#: 444-44-4444
NAME: JOE STUDENT

CODE NAME HOURS GRADE QUAR/YR


MIS220 FILE PROC 4 A 389
BIO100 BIOLOGY 3 B 288
PSY280 EXP PSY 4 B+ 190

TRANSCRIPT
STUDENT
STUDENT_NUMBER
STUDENT_NUMBER COURSE
COURSE_CODE
STUDENT_NAME GRADE
STUDENT_ADDRESS QUAR_YR COURSE_CODE
STUDENT_PHONE COURSE_NAME
MAJOR CREDIT_HOURS
SELECT Command
SELECT STUDENT.STUDENT_NUMBER,
STUDENT_NAME, TRANSCRIPT.COURSE_CODE,
GRADE, QUAR_YR, COURSE_NAME, CREDIT_HOURS
FROM STUDENT, TRANSCRIPT, COURSE
WHERE STUDENT.STUDENT_NUMBER
=TRANSCRIPT.STUDENT_NUMBER
AND TRANSCRIPT.COURSE_CODE
=COURSE.COURSE_CODE;

Three Tables
The number of joins is always
➔ Two Joins
one less than the number of
tables involved in the query
Results
STUD STUDENT_NAME COUR GR QUA COURSE_NAME CREDIT
1121 TRENT RAZEK MIS320 A 1/91 SYSTEMS I 4
1121 TRENT RAZEK MIS420 C 2/92 SYSTEMS II 4
1121 TRENT RAZEK MIS495 B 3/93 MGT INFO SYSTEMS 4

Notice how you get “logical” rows back from the select
as if they can from a single table when in fact the data
comes from three separate tables
Using Aliases
• Aliases for table names can be created in
the FROM part of the SELECT statement.

• Then you can use the alias in place of the


full table name when referring to columns
in that table.

• Sometimes this can save you considerable


typing!
Alias Example

SELECT S.STUDENT_NUMBER, STUDENT_NAME,


T.COURSE_CODE, GRADE, QUAR_YR,
COURSE_NAME, CREDIT_HOURS
FROM STUDENT S, TRANSCRIPT T, COURSE C
WHERE S.STUDENT_NUMBER
=T.STUDENT_NUMBER
AND T.COURSE_CODE=C.COURSE_CODE;
Hints for Successful Joins
• Plan your joins
– Draw a mini-ERD to show what tables are
involved.
• Count the number of tables involved in the
SELECT query.
• The number of joins is always one less than
the number of tables in the query.
• Watch out for ambiguous column names.
FUNCTIONS
SQL - Aggregate Functions

 These functions are applied to a set(s) of


records/rows and return one value for each set.
◼ Count (…)
◼ Min (…)
◼ Max (…)
◼ Sum (…)
◼ Avg (…)
 These functions thus aggregate the rows to
which they are applied.
SQL - Aggregation
• If one field in a Select clause is aggregated, all fields in the
clause must be aggregated.
• Aggregation: The process of transforming data from a
detail to a summary level.
• You can aggregate a field by including it after the GROUP
BY clause or by making it the argument of an aggregating
function.
SELECT Region, SUM(UnitPrice *
Quantity)
FROM [Order_Details]
GROUP BY Region;
SQL - Aggregation

• When you use GROUP BY, every field in your recordset


must be aggregated in some manner.

• The same rule applies when you use an aggregating


function such as SUM, COUNT, AVERAGE …. If one field in
the Select clause is aggregated, then every other field in
the Select clause must be aggregated in some manner.
SQL - Aggregation

Additional SQL Clause - HAVING:


• The HAVING clause is only used after the GROUP BY
clause.
• The HAVING clause specifies criteria for a GROUP,
similar to how the WHERE clause specifies criteria for
individual rows.
GROUP BY
USED WITH FUNCTIONS FOR SUBTOTALING

SELECT INSTRUCTOR_ID, SUM(SALARY)


FROM STAFFING
GROUP BY INSTRUCTOR_ID; ORIGINAL DATA IN TABLE

INSTRUCTOR SALARY
INSTRUCTO SUM(SALARY) 100000000 2500
--------- ----------- 100000000 3400
100000000 5900 200000000 3500
200000000 5900 200000000 2400
300000000 4500
300000000 4500
400000000 3400
400000000 4600 400000000 1200
500000000 1900 500000000 1900
GROUP BY and WHERE
SELECT INSTRUCTOR_ID, SUM(SALARY)
FROM STAFFING
WHERE SALARY>2500
GROUP BY INSTRUCTOR_ID;
INSTRUCTO CALL SALARY
INSTRUCTO SUM(SALARY) --------- ---- ----------
----------------- -------------------- 100000000 0001 2600
100000000 6000 100000000 0002 3400
200000000 6100
300000000 4500 200000000 0003 3500
400000000 3400 200000000 0004 2600

300000000 0005 4500


WHERE CAN RESTRICT
WHICH ROWS ARE PUT
400000000 0006 3400
INTO THE GROUP
400000000 0007 1200
GROUP BY Columns
SELECT INSTRUCTOR_ID, SUM(SALARY)
FROM STAFFING
GROUP BY CALL_NUMBER;
INSTRUCTO CALL SALARY DOES NOT MAKE SENSE
----------------- ------- ---------- TO DISPLAY SALARY OR
100000000 0001 2500 CALL_NUMBER ON A
100000000 0002 3400 GROUP BY INSTRUCTOR_ID
BECAUSE THEY VARY
200000000 0003 3500
200000000 0004 2400
DOES MAKE SENSE TO
300000000 0005 4500 DISPLAY
INSTRUCTOR_ID SINCE IT IS
400000000 0006 3400 THE SAME ACROSS THE
400000000 0007 1200
GROUP
GROUP BY and HAVING
SELECT INSTRUCTOR_ID, SUM(SALARY)
FROM STAFFING
HAVING SUM(SALARY)>4000
GROUP BY INSTRUCTOR_ID INSTRUCTO CALL SALARY
--------- ---- ----------
100000000 0001 2500
INSTRUCTO SUM(SALARY) 100000000 0002 3400
--------- -----------
100000000 5900 200000000 0003 3500
200000000 0004 2400
200000000 5900
300000000 4500 300000000 0005 4500
HAVING DETERMINES
WHICH GROUPS WILL BE 400000000 0006 2400
DISPLAYED 400000000 0007 1200
SQL statement
processing order
(adapted from van der
Lans, p.100)

An intermediate
recordset is developed
after each clause.
Summary of Select
Statements
• SELECT - list of attributes and functions
• FROM - list of tables
• WHERE - conditions / join conditions
• GROUP BY - attributes not aggregated in select clause
• HAVING - group condition
• ORDER BY - list of attributes
• Subqueries (Nested queries)
– Example
– Correlated subquery
• Join types
– Inner/outer
• Integrity constraints
• Triggers
• Functions
Sample Database
• Scripts to create and populate the database are available on the 6217 Web
site.

SUPPLIERS

SUPPLIER_NO SUPPLIER_NAME SUPPLIER_STATE SUPPLIER_STATE

QUOTATIONS
PART_NO SUPPLIER_NO PRICE DELIVERY

INVENTORY
PART_NO Q_ON_ORDER Q_ON_HAND COMPONENT
SUBQUERIES
Subqueries
• A subquery is a query that is used in the
WHERE condition of another query
• AKA Nested query
• Can be multiple levels of nesting
• Can be used with SELECT, INSERT, UPDATE
Example 1: By “Hand”
**** LIST PARTS W/ > AVERAGE NUMBER OF
Q_ON_HAND
**** FIRST QUERY: DETERMINE AVERAGE
SELECT AVG(Q_ON_HAND)
FROM INVENTORY
;

**** SECOND QUERY: PLUG AVERAGE INTO WHERE


CLAUSE
SELECT PART_NO, Q_ON_HAND, DESCRIPTION
FROM INVENTORY
WHEREQ_ON_HAND > 50.92
ORDER BY PART_NO
;
Example 1: Using Subquery

SELECT PART_NO, Q_ON_HAND,


DESCRIPTION
FROM INVENTORY
WHERE Q_ON_HAND >
(SELECT AVG(Q_ON_HAND)
FROM INVENTORY)
ORDER BY PART_NO
;
Example 2: Using Join
• List all suppliers who can deliver at least one product in less
than 10 days

SELECT DISTINCT (S.SUPPLIER_NO),


SUPPLIER_NAME
FROM SUPPLIERS S, QUOTATIONS Q
WHERE S.SUPPLIER_NO = Q.SUPPLIER_NO
AND DELIVERY_TIME < 10
ORDER BY S.SUPPLIER_NO
;
Example 2: Using Subquery

SELECT SUPPLIER_NO, SUPPLIER_NAME


FROM SUPPLIERS
WHERE SUPPLIER_NO IN
(SELECT SUPPLIER_NO
FROM QUOTATIONS
WHERE DELIVERY_TIME < 10)
ORDER BY SUPPLIER_NAME DESC
;
Example 3: With Aggregation
• List all suppliers who can deliver a product in less than the
average delivery time.

SELECT SUPPLIER_NO, SUPPLIER_NAME


FROM SUPPLIERS
WHERE SUPPLIER_NO IN
(SELECT SUPPLIER_NO
FROM QUOTATIONS
WHERE DELIVERY_TIME <
(SELECT AVG(DELIVERY_TIME)
FROM QUOTATIONS)
)
ORDER BY SUPPLIER_NAME DESC
;
Example 4: ANY
• LIST SUP_NO, PART, DEL FOR QUOTES WHERE DEL > ANY
SUPPLIED BY #71
SELECT SUPPLIER_NO, PART_NO,
DELIVERY_TIME
FROM QUOTATIONS
WHERE DELIVERY_TIME > ANY
(SELECT DELIVERY_TIME
FROM QUOTATIONS
WHERE SUPPLIER_NO = 71)
;
Example 5: ALL
• LIST SUP_NO, PART, DEL FOR QUOTES WHERE DEL > ALL
SUPPLIED BY #71
SELECT SUPPLIER_NO, PART_NO,
DELIVERY_TIME
FROM QUOTATIONS
WHERE DELIVERY_TIME > ALL
(SELECT DELIVERY_TIME
FROM QUOTATIONS
WHERE SUPPLIER_NO = 71)
;
Example 6: ANY
• Who are alternate suppliers for parts supplied by #71?

SELECT SUPPLIER_NO, PART_NO,


DELIVERY_TIME
FROM QUOTATIONS
WHERE PART_NO = ANY
(SELECT PART_NO
FROM QUOTATIONS
WHERE SUPPLIER_NO = 71)
AND SUPPLIER_NO != 71
ORDER BY SUPPLIER_NO;
Example 7: NOT EXISTS
• List all suppliers who have not provided a quote

SELECT *
FROM SUPPLIERS
WHERE NOT EXISTS
(SELECT *
FROM QUOTATIONS
WHERE SUPPLIER_NO =
SUPPLIERS.SUPPLIER_NO)
ORDER BY SUPPLIER_NO;
Correlated Subqueries

• A correlated subquery is a subquery that is


evaluated once for each row processed by
the parent statement. The parent
statement can be a SELECT, UPDATE, or
DELETE statement. These examples
show the general syntax of a correlated
subquery:
Example 8: Step-by-Step
• List all suppliers, parts and prices where quoted price is less
than the average quote for that part.

SELECT AVG(PRICE)
FROM QUOTATIONS
WHERE PART_NO = 321;

SELECT SUPPLIER_NO, PART_NO, PRICE


FROM QUOTATIONS Q
WHERE PRICE < 4
AND PART_NO = 321;

SELECT SUPPLIER_NO, PART_NO, PRICE


FROM QUOTATIONS Q
WHERE PART_NO = 321;
OTHER TYPE OF JOIN
Example 8: Correlated Subquery
SELECT SUPPLIER_NO, PART_NO,
PRICE
FROM QUOTATIONS Q
WHERE PRICE <
(SELECT AVG(PRICE)
FROM QUOTATIONS
WHERE Q.PART_NO = PART_NO)
ORDER BY PART_NO, SUPPLIER_NO;
Join Types
• Natural join/inner join
– This is what you’re used to.
– Returns only rows where PK and FK values match.
– Does not repeat PK/FK columns
• Equi-Join
– Similar to natural join, but includes both PK and FK
values in record set.
Equi-Join Example

SELECT I.PART_NO, Q.PART_NO,


SUPPLIER_NO, PRICE
FROM INVENTORY I, QUOTATIONS Q
WHERE I.PART_NO = Q.PART_NO
ORDER BY I.PART_NO
;
More Join Types
• Outer join
– Includes columns with null FK values
– Problem: Inner join will not return a row that does
not have a matching value.
• Sometimes this prevents you from getting the output
you want.
– Example: List all parts (including description) and
any quotes that exist for each part. We want to
include all parts even if there are no quotes for
some of them.
Solution: Left Outer Join
SELECT I.PART_NO, DESCRIPTION, SUPPLIER_NO,
PRICE
FROM INVENTORY I, QUOTATIONS Q
WHEREI.PART_NO = Q.PART_NO (+)
ORDER BY I.PART_NO
;
This is what makes it an outer join.
Include all rows from the table away
from the (+)

Includes all rows from the left table.


SQL Server Version
SELECT I.PART_NO, DESCRIPTION,
SUPPLIER_NO, PRICE
FROM INVENTORY I, QUOTATIONS Q
WHERE I.PART_NO *= Q.PART_NO
ORDER BY I.PART_NO

This is what makes it an outer join.


Include all rows from the table closest
to the * in *=

Includes all rows from the left table.


Non-Solution: Right Outer Join
SELECT I.PART_NO, DESCRIPTION,
SUPPLIER_NO, PRICE
FROM INVENTORY I, QUOTATIONS Q
WHERE I.PART_NO (+)= Q.PART_NO
ORDER BY I.PART_NO;
This query does not include all rows from the
INVENTORY table. So, it doesn’t work. We could
reverse the order of tables in the WHERE
condition and the query would be OK
Right-Outer Join: SQL Server

SELECT I.PART_NO, DESCRIPTION,


SUPPLIER_NO, PRICE
FROM INVENTORY I, QUOTATIONS Q
WHERE I.PART_NO *= Q.PART_NO
ORDER BY I.PART_NO
Null Values
• Field values in a tuple are sometimes unknown (e.g., a rating has not
been assigned) or inapplicable (e.g., no spouse’s name).
– SQL provides a special value null for such situations.
• The presence of null complicates many issues. E.g.:
– Special operators needed to check if value is/is not null.
– Is rating>8 true or false when rating is equal to null? What about AND, OR and
NOT connectives?
– We need a 3-valued logic (true, false and unknown).
– Meaning of constructs must be defined carefully. (e.g., WHERE clause
eliminates rows that don’t evaluate to true.)
– New operators (in particular, outer joins) possible/needed.
Integrity Constraints (Review)
• An IC describes conditions that every legal instance
of a relation must satisfy.
– Inserts/deletes/updates that violate IC’s are disallowed.
– Can be used to ensure application semantics (e.g., sid is a
key), or prevent inconsistencies (e.g., sname has to be a
string, age must be < 200)
• Types of IC’s: Domain constraints, primary key
constraints, foreign key constraints, general
constraints.
– Domain constraints: Field values must be of right type.
Always enforced.
General Constraints
CREATE TABLE Sailors
• Useful when more ( sid INTEGER,
general ICs than sname CHAR(10),
keys are involved. rating INTEGER,
• Can use queriesCREATE
to age REAL,
TABLE Reserves
express PRIMARY KEY (sid),
( sname CHAR(10), CHECK ( rating >= 1
constraint. bid INTEGER, AND rating <= 10 )
• Constraints can be day DATE,
named. PRIMARY KEY (bid,day),
CONSTRAINT noInterlakeRes
CHECK (`Interlake’ <>
( SELECT B.bname
FROM Boats B
WHERE B.bid=bid)))
Constraints Over Multiple Relations
CREATE TABLE Sailors
• Awkward and ( sid INTEGER, Number of boats
wrong! sname CHAR(10), plus number of
• If Sailors is empty, rating INTEGER, sailors is < 100
the number of age REAL,
Boats tuples can be
anything! PRIMARY KEY (sid),
• ASSERTION is the CHECK
right solution; not ( (SELECT COUNT (S.sid) FROM Sailors S)
associated with + (SELECT COUNT (B.bid) FROM Boats B) < 100 )
either table.
CREATE ASSERTION smallClub
CHECK
( (SELECT COUNT (S.sid) FROM Sailors S)
+ (SELECT COUNT (B.bid) FROM Boats B) < 100 )
Triggers
• Trigger: procedure that starts automatically if
specified changes occur to the DBMS
• Three parts:
– Event (activates the trigger)
– Condition (tests whether the triggers should run)
– Action (what happens if the trigger runs)
Triggers: Example (SQL:1999)
CREATE TRIGGER youngSailorUpdate
AFTER INSERT ON SAILORS
REFERENCING NEW TABLE NewSailors
FOR EACH STATEMENT
INSERT
INTO YoungSailors(sid, name, age, rating)
SELECT sid, name, age, rating
FROM NewSailors N
WHERE N.age <= 18
Some Useful Functions
• ABS (n)
• MOD (m,n)
– Returns the remainder of m/n
• POWER (m,n)
• ROUND(n[,m])
• SIGN(n)
• SQRT
• TRUNC(15.79,1)
Character Functions
• CONCAT(char1, char2)
– ||
• LOWER/UPPER
• LTRIM(char [,set]) RTRIM(char [,set]
• SUBSTR(char, m [,n])
• LENGTH(char)
Date Functions

• ADD_MONTHS(d,n)
• LAST_DAY(d)
• MONTHS_BETWEEN(d1, d2)
• ROUND(d[,fmt])
• SYSDATE
• TO_CHAR(d [, fmt [, 'nlsparams'] ])
• TO_DATE(char [, fmt [, 'nlsparams'] ])
Data Dictionary Tables
• DICTIONARY
– All tables and views that are available to the user
– This table contains several hundred rows
• Useful Data Dictionary Views
– Use just like a table
– More useful (generally) than full tables
– Use DESCRIBE to see the columns in the view
– USER_TABLES
– USER_VIEWS
– USER_CONSTRAINTS
– USER_OBJECTS
Are you able to..

• Construct SQL commands to create tables


and indexes, insert/update/delete data,
and query data in a relational DBMS.
• Implement functions in SQL commands
• Construct data-intensive application using
DBMS.

You might also like