Documente Academic
Documente Profesional
Documente Cultură
Database Management Systems SQL for Database Constuction(DDL) Advanced SQL (DML)
Spring-1112
BIS512
View Ridge Gallery is a small art gallery that has been in business for 30 years . It sells contemporary European and North American fine art. View Ridge has one owner, three salespeople, and two workers. View Ridge owns all of the art that it sells; it holds no items on a consignment basis.
Spring-1112
BIS512
Application Requirements
Spring-1112
BIS512
Spring-1112
BIS512
Spring-1112
BIS512
Spring-1112
BIS512
CREATE TABLE
CREATE TABLE statement is used for creating relations Each column is described with three parts: column name, data type, and optional constraints Example:
Spring-1112
BIS512
Data Types
Spring-1112
BIS512
Constraints
Constraints can be defined within the CREATE TABLE statement, or they can be added to the table after it is created using the ALTER table statement Five types of constraints:
PRIMARY KEY may not have null values UNIQUE may have null values NULL/NOT NULL FOREIGN KEY CHECK
Spring-1112
BIS512
Creating Relationships
Spring-1112
10
BIS512
Implementing Cardinalities
Spring-1112
11
Spring-1112
12
BIS512
Spring-1112
13
BIS512
Referential Integrity
A referential triggered action clause can be attached to a foreign key constraint, that specifies the action to take if a referenced tuple is deleted, or a referenced primary key value is modified.
ON DELETE ON UPDATE SET NULL | SET DEFAULT | CASCADE | NO ACTION SET NULL | SET DEFAULT | CASCADE | NO ACTION
CREATE TABLE EMPLOYEE ( . FOREIGN KEY (DNO) REFERENCES DEPARTMENT (DNUMBER) ON DELETE SET DEFAULT ON UPDATE CASCADE);
Spring-1112
14
BIS512
Spring-1112
15
BIS512
ALTER TABLE
BIS512
The following statement will add a column named MyColumn to the CUSTOMER table:
ALTER TABLE CUSTOMER ADD MyColumn Char(5) NULL;
Spring-1112
17
BIS512
BIS512
Removing Tables
BIS512
INSERT command:
INSERT INTO ARTIST ([Name], Nationality, Birthdate,DeceasedDate) VALUES ('Tamayo', 'Mexican', 1927, 1998);
Bulk INSERT:
INSERT INTO ARTIST ([Name], Nationality,Birthdate) SELECT [Name], Nationality, Birthdate FROM IMPORTED_ARTIST;
Spring-1112 20
10
BIS512
UPDATE command:
UPDATE SET WHERE CUSTOMER City = 'New York City' CustomerID = 1000;
Bulk UPDATE:
UPDATE SET WHERE
Spring-1112
BIS512
DELETE command:
DELETE FROM CUSTOMER WHERE CustomerID = 1000;
If you omit the WHERE clause, you will delete every row in the table!
Spring-1112
22
11
BIS512
SQL
SELECT [DISTINCT] (attribute / expression / aggregation-function list | * ) FROM <table list> [WHERE [join condition and] search_condition] [GROUP BY grouping attributes] [HAVING <group condition>] [ORDER BY column_name [ASC|DESC] {, columnname [ASC|DES]}];
Spring-1112
23
BIS512
Joins in SQL
A Join used to combine related tuples from two relations into a single tuple in a new (result) relation.
This is needed when information is contained in more than one relation Join relations are specified in the FROM Clause
Work(WorkID,Artist ID,Title,Copy,Description) Artist (Artist ID,Name,Nationality,Birthdate,DeceasedDate) R1(CustomerID,Artist ID) Customer(CustomerID,TransactionId,Name,AreaCode,LNumber,..., Country,Email) TransAction(TranActionID,WorkID,DateReq,PPrice,PDate,SPrice,APrice)
Spring-1112 24
12
BIS512
EquiJoin
Joins tuples from two relations when they have the same value for some pair(s) of designated attributes
The specification is termed a join condition With equi-join, the join condition only has equality comparisons
List the names of the artist who did work Titled Mystic Fabric.
SELECT Name FROM ARTIST, WORK WHERE Artist.ArtistID=Work.ArtistID AND Title =Mystic Fabric;
BIS512
EquiJoin (syntax)
List the names of the artist who did work Titled Mystic Fabric.
SELECT Name FROM ARTIST JOIN WORK ON Artist.ArtistID=Work.ArtistID WHERE Title =Mystic Fabric;
Spring-1112
26
13
BIS512
Natural Join
Similar to equi-join except that the attributes that are used for the join are those that have the same name in each relation
Join attributes (and join condition) are not explicitly specified Duplicate attributes are eliminated No special SQL syntax for this join Get artist names and the corresponding work names. SELECT Name FROM ARTIST, WORK
Work(WorkID,Artist ID,Title,Copy,Description) Artist (Artist ID,Name,Nationality,Birthdate,DeceasedDate)
Spring-1112 27
BIS512
Inner Join
This is the default join, in which a tuple is included in the result relation, only if matching tuples exist in both relations
Outer Join
Outer joins can include the tuples that do not satisfy the join condition, i.e, a matching tuple does not exist, which is indicated by a NULL value
Left Outer Join: Includes all rows from first table Right Outer Join: Includes all rows from second table
Spring-1112
28
14
BIS512
Spring-1112
29
BIS512
Left Outer Join:
SELECT FROM ON
Outer Join
Spring-1112
30
15
BIS512 L-170
L-230 L-260
loan-number
Inner Join Left Outer Join Right Outer Join Full Outer Join
Spring-1112
loan-number branch-name amount customer-name L-170 Downtown 3000 Jones L-230 Redwood 4000 Smith loan-number branch-name amount customer-name L-170 L-230 L-260 Downtown Redwood Perryridge 3000 4000 1700 Jones Smith null
loan-number branch-name amount customer-name L-170 L-230 L-155 loan-number L-170 L-230 L-260 L-155 Downtown Redwood null 3000 4000 null Jones Smith Hayes
branch-name amount customer-name Downtown 3000 Jones Redwood 4000 Smith 31 Perryridge 1700 null null null Hayes
BIS512
Renaming in SQL
Two options:
Qualifying attribute names Declaring an alias
Spring-1112
32
16
BIS512
Renaming Examples
SELECT Artist.Name FROM ARTIST, WORK WHERE Artist.ArtistID=Work.ArtistID AND Work.Title =Mystic Fabric; Declaring an Alias
SELECT A.Name FROM ARTIST A, WORK W WHERE A.ArtistID=W.ArtistID AND W.Title =Mystic Fabric;
Attributes can be renamed using AS
Spring-1112 33
BIS512
A nested query (often termed subquery) is a query that appears within another query
Inside the WHERE clause of another SELECT statement Inside an INSERT, UPDATE or DELETE statement Nesting can occur at multiple levels The query that contains the nested query is called the outer query Nested queries represent an alternative technique for expressing multi-table manipulation
Spring-1112 34
17
BIS512
Subqueries in SQL
SELECT ... FROM WHERE {expression {[NOT] IN | comparison-operator [ANY|ALL]} | [NOT] EXISTS} (SELECT FROM WHERE ...);
Spring-1112
35
BIS512
The outer query takes an action based on the results of the inner query
18
BIS512
Non-Correlated Subquery
Spring-1112
37
BIS512
Find the names of artists who works on Mystic Select Name From Artist Where Mystic Fabric in ( Select Title From Work Where Work.ArtistID = Artist.ArtistID);
Work(WorkID,Artist ID,Title,Copy,Description) Artist (Artist ID,Name,Nationality,Birthdate,DeceasedDate) R1(CustomerID,Artist ID) Customer(CustomerID,TransactionId,Name,AreaCode,LNumber,..., Country,Email) TransAction(TranActionID,WorkID,DateReq,PPrice,PDate,SPrice,APrice)
Spring-1112
38
19
BIS512
Both joins and sub-queries are used for multi-table queries They can be used interchangeably
Join SELECT Name FROM ARTIST, WORK WHERE Artist.ArtistID=Work.ArtistID AND Title =Mystic Fabric;
Sub-query SELECT A.Name FROM ARTIST A WHERE A.Artist IN (SELECT W.ArtistID FROM WORK W WHERE W.Title = Mystic Fabric);
Spring-1112
39
BIS512
The sub-query implementation can only display data from the table(s) in the outer query The join implementation can display data from all tables in the FROM clause
SELECT Name, Copy FROM ARTIST, WORK WHERE Artist.ArtistID=Work.ArtistID AND Title =Mystic Fabric; Work(WorkID,Artist ID,Title,Copy,Description) Artist (Artist ID,Name,Nationality,Birthdate,DeceasedDate)
Spring-1112
40
20
BIS512
The ability to calculate an aggregate value on the fly and feed it back to the outer query for comparison is an advantage subqueries have over joins
SELECT Name, Birthdate FROM Artist WHERE Birthdate = (SELECT max (Birthdate) FROM Artist )
Spring-1112 41
BIS512
Sub-query Operators
Spring-1112
42
21
BIS512
Expression and attribute list in sub-query SELECT clause must have same domain expression {[NOT] IN (sub-query)
expression is checked for membership in the set (of tuples) returned by sub-query
BIS512
IN Operator Example
ARTIST A A.ArtistID IN (SELECT W.ArtistID FROM WORK W WHERE W.Title = Mystic Fabric);
Spring-1112
44
22
BIS512
SELECT A.Name FROM ARTIST A WHERE A.ArtistID = ANY (SELECT W.ArtistID FROM WORK W WHERE W.Title = Mystic Fabric);
SELECT A.Name FROM ARTIST A WHERE A.ArtistID IN (SELECT W.ArtistID FROM WORK W WHERE W.Title = Mystic Fabric);
Spring-1112
45
BIS512
NOT IN Example
SELECT A.Name FROM ARTIST A WHERE A.ArtistID NOT IN (SELECT W.ArtistID FROM WORK W WHERE W.Title = Mystic Fabric); SELECT C.Name FROM Customer C WHERE C.CustomerID NOT IN (SELECT T.CustomerID FROM Trans T);
Spring-1112 46
23
BIS512
ALL Example
Spring-1112
47
BIS512
Expression and attribute list in sub-query SELECT clause must have same domain expression comp-op (sub-query)
expression is compared with the value returned by the sub-query The sub-query must evaluate to a single value otherwise an error will occur
Spring-1112
48
24
BIS512
SELECT Name, Birthdate FROM Artist WHERE Birthdate = (SELECT max (Birthdate) FROM Artist )
Spring-1112
49
BIS512
The EXISTS function tests for the existence or nonexistence of data that meet the criteria of the sub-query
SELECT FROM WHERE [NOT] EXISTS (sub-query) Sub-queries are used with EXISTS and NOT EXISTS are always correlated WHERE EXISTS (sub-query) evaluates to true if the result of the correlated sub-query is a non-empty set,
contains 1 or more tuples
WHERE NOT EXISTS (sub-query) evaluates to true if the result of the correlated sub-query returns an empty set,
Spring-1112
zero tuples
50
25
BIS512
Spring-1112
51
BIS512
The following code determines the name of any ARTIST that is of interest to every CUSTOMER:
SELECT FROM WHERE A.Name ARTIST AS A NOT EXISTS (SELECT C.CustomerID FROM CUSTOMER C WHERE NOT EXISTS (SELECT CI.CustomerID FROM CUSTOMER_artist_int CI WHERE C.CustomerID = CI.CustomerID AND A.ArtistID = CI.ArtistID));
52
Spring-1112
26
BIS512
Correlated Subquery
The following is a correlated subquery It contains the same tables in both levels of the query SELECT FROM WHERE W1.Title, W1.Copy WORK W1 W1.Title IN (SELECT W2.Title FROM WORK W2 WHERE W1.Title = W2.Title AND W1.WorkID <> W2.WorkID);
Spring-1112
53
BIS512
EMPLOYEE( ssn, firstname, lastname, title, salary, dept id, mgr id) DEPARTMENT( dept id, departmentname, totalbudget)
(Basic) Find the ssn, first and last name of employees who do not have a manager. (Group By) Find the name, total budget of departments in which the total salary of all people working in that department exceeds the total budget of the department. (Join) Find the first and last name of employees whose salary is greater than the salary oftheir manager. (Nesting) Find name of departments that does not have any employees with title Vice President working in them.
27
BIS512
Employee (SSN, Name, Salary, DeptNo, MGRSSN) Customer (AccountNo, Name, LenderSSN) Loan (LoanNumber, Amount, AccountNo) Find the numbers of all departments where the average salary of an employee in that department is greater than the average salary of employees in the company. with GROUP BY and 2. without GROUPBY Find the SSN of all employees whose managers do not have any customers with EXISTS and 2. with IN
28