Sei sulla pagina 1di 9

CXB 3104 Advanced Database Systems

Lecture 4 SQL, Sub Queries

SQL Principals

SQL as a data definition language:


allows users to describe the relations and constraints.

SQL as a query language:


declarative - you specify what you want and not how to retrieve relationally complete

Updates in SQL:
allows users to insert, delete and modify tables

SQL Principals - Enhancements


Triggers (SQL:1999) Programs that respond to events relating to a given table Stored Procedures(SQL:1999): Predefined sequences of SQL statements New data types: Object-oriented features in SQL:1999, XML in SQL:2003/2006 Application Programming Interface (API): ODBC and JDBC provide standard set of DDL/DML functions

Deleting Database Components


The drop command allows the removal of database components, e.g. DROP TABLE Lecture RESTRICT; Options: restrict - specifies that the command must not be carried out if the component being deleted is not empty. cascade the component is removed together with the components that depend on it.

Constraints in RDBMS
UNIQUE, NOT NULL, CHECK Entity integrity - Primary keys Referential integrity - Foreign keys

Primary Keys
A primary key is a set of columns that together makes each row distinct No two rows will have the same value of this primary key (implies that no two rows can be identical duplicates are disallowed) Every table must have one primary key A primary key should not contain a null value since then it may not be possible to identify some tuples.

Intra-relational constraints1
The simplest intra-relational constraints are NOT NULL, UNIQUE, PRIMARY KEY and CHECK The first three can be included in a table definition on each column or after the column definitions If multiple columns are used to form a composite PRIMARY KEY, the key definition must be included in the table definition after the column definitions.

Foreign Keys
A FOREIGN KEY is an inter-relational constraint that references one or more rows in the table in which it is defined to a primary key (strictly a candidate key) in another table. Every non-NULL value that exists in a foreign key attribute must also exist in the table for which it is the primary key. i.e.:

if B references A, A must exist

Inter-relational constraints-2
If a row of a table with a foreign key is updated or deleted violations in the referential constraints can occur. Four response modes can be given to the foreign key: cascade, set null, set default, no action, restrict

Altering a Foreign Key


ALTER TABLE Student DROP PRIMARY KEY CASCADE; ALTER TABLE Student DROP CONSTRAINT stLec CASCADE; ALTER TABLE Student ADD CONSTRAINT stLec FOREIGN KEY (roomNo,occurs) REFERENCES Lecture(roomNo,occurs) ON DELETE CASCADE;

10

Data Manipulation Statements - 1

Data Manipulation Statements - II


Data modification UPDATE Customer SET customerCity = Penang, street = Cheras WHERE customerName = Smith; Data removal DELETE FROM Customer WHERE customerName = Smith;

Data retrieval (Queries)


SELECT custName FROM Customer WHERE

customerCity = Kuala Lumpur; Data storage


INSERT INTO Customer (custName,

customerCity) VALUES (Smith,Penang);

11

12

SQL Simple Selects

SQL Union

Find the branch names for each deposit of customers Smith and Chen that have a balance greater than 200 or less than 100: SELECT DISTINCT branchName FROM Deposit WHERE customerName = Smith OR customerName = Chen AND balance > 200 OR balance < 100; SELECT DISTINCT branchName FROM Deposit WHERE balance NOT BETWEEN 100 AND 200 AND customerName IN (Smith,Chen);

Find the names of all customers who have either a loan or an account at the RHB branch: ( SELECT customerName FROM Deposit WHERE branchName = RHB ) UNION ( SELECT customerName FROM Loan WHERE branchName = RHB );

13

14

SQL Intersection

SQL Minus

Find the names of all customers who have both a loan and an account at the RHB branch ( SELECT customerName FROM Deposit WHERE branchName = RHB ) INTERSECT ( SELECT customerName FROM Loan WHERE branchName = RHB );

Return the rows that are in the first table except those rows that also appear in the second table: ( SELECT customerName FROM Deposit WHERE branchName = RHB ) MINUS ( SELECT customerName FROM Borrow WHERE branchName = RHB );

15

16

Multiple Table Queries (Joins)


Can specify multiple tables in the FROM clause to perform an inner join: SELECT * FROM Loan, Customer WHERE Loan.customerName=Customer.customerName;

Inner Join with condition

Specify which column to join and a conditional clause: SELECT Loan.customerName FROM Loan, Customer WHERE Loan.customerName = Customer.customerName AND Loan.amount > 2000 AND Customer.customerCity = Kuala Lumpur;

An alternative way of writing joins: SELECT * FROM Loan JOIN Customer ON Loan.customerName =Customer.customerName;

17

18

Inner Joins example (aliases)

Outer Joins
Preserve unmatched rows from one or both tables LEFT [OUTER] JOIN - preserves unmatched rows from the left table RIGHT [OUTER] JOIN - preserves unmatched rows from the right table FULL [OUTER] JOIN - preserves unmatched rows from both tables Rows that dont match are given NULL values for columns from the other table

19 20

Left Outer Join - example

Right outer join

21

22

Full Outer Join

Single Table Self-Join

Find all the customers who have an account at same branch at which Patel has an account (also output the branch names) SELECT T.customerName FROM Deposit S, Deposit T WHERE S.customerName = Patel AND S.branchName = T.branchName;

23

24

Built-In Functions

Sub queries: The IN Clause


A sub query is a query that appears in the body of another expression. E.g. find the names of all customers who have both a loan and account at the RHB

Operate on the set of values in a column of a relation and return a single value. E.g. SUM([DISTINCT] column-name): sum of values AVG([DISTINCT] column-name): average value MIN(column-name): minimum value MAX(column-name): maximum value COUNT([DISTINCT] column-name): number of values excluding NULLS COUNT(*): number of values in column including NULLS - where DISTINCT means only include values that are different

SELECT customerName FROM Loan WHERE branchName = RHB AND customerName IN (SELECT customerName FROM Deposit WHERE branchName = RHB);

25

26

Sub queries and Joins

Sub queries: The ANY Clause

A sub query can sometimes also be expressed as a join. E.g. find the names of all customers who have both a loan and account at the RHB
SELECT Loan.customerName FROM Loan, Deposit WHERE Loan.branchName = RHB AND Deposit.branchName = RHB AND Loan.customerName = Deposit.customerName;

Find all branches that have greater assets than at least one branch located in Kuala Lumpur
SELECT branchName FROM Branch WHERE assets > ANY (SELECT assets FROM Branch WHERE branchCity = Kuala Lumpur);

27

28

Sub queries: The ALL Clause

Sub queries: The IN Clause

Find the names of all branches that have greater assets than every branches located in Kuala Lumpur
SELECT branchName FROM Branch WHERE assets > ALL (SELECT assets FROM Branch WHERE branchCity = Kuala Lumpur);

Find all customers who DO NOT have an account at a branch named RHB:
SELECT S.customerName FROM Customer S WHERE customerName NOT IN (SELECT customerName FROM Deposit T WHERE branchName = RHB);

29

30

Sub queries: The EXISTS Clause

Insertion using a query

Find all customers who DO NOT have an account at a branch named CIMB:

Provide all loan customers in the RHB branch with a $ 200 saving account. Let the loan number serve as the account number for the new savings account

SELECT S.customerName FROM Customer S WHERE NOT EXISTS (SELECT T.customerName FROM Deposit T WHERE branchName = CIMB AND S.customerName = T.customerName);

INSERT INTO Deposit SELECT customerName, branchName, loanNumber, 200 FROM Loan WHERE branchName = RHB;

31

32

Deletion using a sub query

Delete all accounts at banks located in CIMB


DELETE FROM Deposit WHERE branchName IN (SELECT branchName FROM Branch WHERE branchCity = CIMB);

33

Potrebbero piacerti anche