Sunteți pe pagina 1din 28

BIS512

Database Management Systems SQL for Database Constuction(DDL) Advanced SQL (DML)

Spring-1112

BIS512

Example: View Ridge Gallery

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

View Ridge application requirements:


Track customers and their artist interests Record gallery's purchases Record customers' art purchases List the artists and works that have appeared in the gallery Report how fast an artist's works have sold and at what margin Show current inventory in a Web page

Spring-1112

BIS512

View Ridge Gallery Database Design

Spring-1112

BIS512

The Table Design

Spring-1112

BIS512

SQL DDL and DML

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

BIS512 Default Values and Data Constraints

Spring-1112

12

BIS512

SQL for Constraints

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

SQL for Constraints

Spring-1112

15

BIS512

ALTER TABLE

ALTER TABLE command is used for schema evolution,


the definition of a table created using the CREATE TABLE command, can be changed using the ALTER TABLE command

Alter table actions include


Adding or dropping a column Changing a column definition Adding or dropping constraint
Spring-1112 16

BIS512

Adding and Dropping Columns

The following statement will add a column named MyColumn to the CUSTOMER table:
ALTER TABLE CUSTOMER ADD MyColumn Char(5) NULL;

You can drop an existing column with the statement:


ALTER TABLE CUSTOMER DROP COLUMN MyColumn;

Spring-1112

17

BIS512

Adding and Dropping Constraints

ALTER can be used to add a constraint as follows:


ALTER TABLE CUSTOMER ADD CONSTRAINT MyConstraint CHECK ([Name] NOT IN ('Robert No Pay'));

ALTER can be used to drop a constraint:


ALTER TABLE CUSTOMER DROP CONSTRAINT MyConstraint;
Spring-1112 18

BIS512

Removing Tables

SQL DROP TABLE:


DROP TABLE [TRANSACTION];

If there are constraints:


ALTER TABLE CUSTOMER_ARTIST_INT DROP CONSTRAINT Customer_Artist_Int_CustomerFK; ALTER TABLE [TRANSACTION] DROP CONSTRAINT TransactionCustomerFK; DROP TABLE CUSTOMER;
Spring-1112 19

BIS512

SQL DML - INSERT

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

SQL DML: UPDATE

UPDATE command:
UPDATE SET WHERE CUSTOMER City = 'New York City' CustomerID = 1000;

Bulk UPDATE:
UPDATE SET WHERE
Spring-1112

CUSTOMER AreaCode = '333' City = 'Denver';


21

BIS512

SQL DML: DELETE

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;

Work(WorkID,Artist ID,Title,Copy,Description) Artist (Artist ID,Name,Nationality,Birthdate,DeceasedDate)


Spring-1112 25

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;

Work(WorkID,Artist ID,Title,Copy,Description) Artist (Artist ID,Name,Nationality,Birthdate,DeceasedDate)

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

Inner and Outer Joins

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

Name, SalePrice CUSTOMER LEFT OUTER JOIN TRANSACTION CUSTOMER.CustomerID = TRANSACTION.CustomerID

Spring-1112

30

15

BIS512 L-170
L-230 L-260

loan-number

branch-name Downtown Redwood Perryridge

amount 3000 4000 1700

customer-name loan-number Jones Smith Hayes L-170 L-230 L-155

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

SQL provides the facility to rename attribute and/or table names


Renaming assists in removing ambiguity

Two options:
Qualifying attribute names Declaring an alias

Spring-1112

32

16

BIS512

Renaming Examples

Qualifying Attribute Names

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

Nested SQL Queries

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

Nested Query Types

Non-correlated Nested Queries


Results are returned from an inner query to an outer query
sub-queries are evaluated from the inside out

The outer query takes an action based on the results of the inner query

Correlated Nested Queries


Correlated subqueries have conditions in their WHERE clause that references some attribute of a relation declared in the outer query The outer SQL statement provides the values for the inner subquery to use in its evaluation The subquery is evaluated once for each (combination of) tuple in the outer query
Spring-1112 36

18

BIS512

Non-Correlated Subquery

It contains two separate tables in the levels of the query:


ARTIST in the top level query WORK in the subquery List the names of the artist who did work Titled Mystic Fabric.
SELECT FROM WHERE A.Name ARTIST A A.Artist IN (SELECT W.ArtistID FROM WORK W WHERE W.Title = Mystic Fabric);

Spring-1112

37

BIS512

Correlated Query Example


Fabric

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

Joins and Sub-queries

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

Advantages of using a Join

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

Advantages of using Subqueries

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

Find youngest Artist Aggregation Result = 1950

SELECT max (Birthdate) FROM Artist

SELECT Name, Birthdate FROM Artist WHERE Birthdate = 1950 Sub-query

SELECT Name, Birthdate FROM Artist WHERE Birthdate = (SELECT max (Birthdate) FROM Artist )
Spring-1112 41

BIS512

Sub-query Operators

Sub-queries that return a set


expression {[NOT] IN (sub-query) expression comp-op [ANY|ALL] (sub-query)

Subqueries that return a single value


expression comp-op (sub-query)

Spring-1112

42

21

BIS512

Sub-query returning a Set

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

expression comp-op [ANY|ALL] (sub-query)


expression is compared with the set (of tuples) returned by the sub-query ANY: Evaluates to true if one comparison is true ALL: Evaluates to true if all comparisons are true
Spring-1112 43

BIS512

IN Operator Example
ARTIST A A.ArtistID IN (SELECT W.ArtistID FROM WORK W WHERE W.Title = Mystic Fabric);

SELECT A.Name FROM WHERE

Spring-1112

44

22

BIS512

Equivalence of IN and = ANY

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

List artist who is younger than all German Artists


SELECT * FROM Artist WHERE BirthDate > ALL (SELECT BirthDate FROM Artist WHERE Nationality='German');

Spring-1112

47

BIS512

Sub-query returning a Value

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

Single Value Subquery Example

SELECT Name, Birthdate FROM Artist WHERE Birthdate = (SELECT max (Birthdate) FROM Artist )

Spring-1112

49

BIS512

Using the EXISTS Function

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

(NOT) EXISTS Examples

Display the names of artist whose has work


SELECT A.Name FROM ARTIST A WHERE EXISTs (SELECT * FROM WORK W wHERE W.artistId=A.artistID);

Spring-1112

51

BIS512

Double NOT EXISTS

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

S-ar putea să vă placă și