Chapter 6 SQL Data Definition Language Chapter 7

  • Slides: 49
Download presentation
Chapter 6 SQL Data Definition Language Chapter 7 in Textbook

Chapter 6 SQL Data Definition Language Chapter 7 in Textbook

Database Design Steps in building a database for an application: Real-world domain SQL (DDL)

Database Design Steps in building a database for an application: Real-world domain SQL (DDL) Conceptual model DBMS data model Create Schema (DDL) Modify data (DML) 2

DDL Statements The main SQL data definition language statements are: CREATE SCHEMA DROP SCHEMA

DDL Statements The main SQL data definition language statements are: CREATE SCHEMA DROP SCHEMA CREATE DOMAIN DROP DOMAIN CREATE TABLE ALTER TABLE DROP TABLE CREATE VIEW DROP VIEW CREATE INDEX DROP INDEX SQL (DDL) 3

Identifiers • May contain A-Z, a-z, 0 -9, _ • No longer than 128

Identifiers • May contain A-Z, a-z, 0 -9, _ • No longer than 128 characters • Start with letter • Cannot contain spaces SQL (DDL) 4

Data Types Data Type Declaration Boolean (TRUE/FALSE) BOOLEAN character CHAR Bno CHAR(4) VARCHAR Name

Data Types Data Type Declaration Boolean (TRUE/FALSE) BOOLEAN character CHAR Bno CHAR(4) VARCHAR Name VERCHAR(15) exact numeric Example NUMERIC DECIMAL, DEC salary DECIMAL(7, 2) INTEGER, INT SMALLINT SQL (DDL) No. Room SMALLINT 5

Data Types Data Type Declaration aprox numeric (e) FLOAT Example REAL DOUBLE PRECISION datetime

Data Types Data Type Declaration aprox numeric (e) FLOAT Example REAL DOUBLE PRECISION datetime large object DATE (YYYY-MM-DD) View. Date DATE TIME (HH: MM: SS) View. Time TIME CHARACTER LARGE OBJECT BINARY LARGE OBJECT SQL (DDL) 6

Data Types Syntax BOOLEAN CHARACTER [VARYING] [(length)] NUMERIC [ ( precision [, scale] )

Data Types Syntax BOOLEAN CHARACTER [VARYING] [(length)] NUMERIC [ ( precision [, scale] ) ] DECIMAL [ ( precision [, scale] ) ] INTEGER SMALLINT FLOAT [ ( precision ) ] REAL DOUBLE PRECISION DATE TIME [ ( Precision ) ] [WITH TIME ZONE] SQL (DDL) 7

Scalar Operators Data Type Meaning Example CHAR_LENGTH length of string in characters LOWER convert

Scalar Operators Data Type Meaning Example CHAR_LENGTH length of string in characters LOWER convert letters to lower-case LOWER(name) UPPER convert letters to upper-case UPPER(name) SUBSTRING returns a substring CURRENT_DATE returns the current date CURRENT_TIME returns the current time CHAR_LENGTH(‘Bee’) SUBSTRING(‘Beech’ FROM 1 TO 3) * See Page 180 Connolly 5 th Edition and ORACLE SQLRef manual. SQL (DDL) 8

Integrity Enhancement Feature (IEF) Five types of Integrity constraints defined in CREATE & ALTER:

Integrity Enhancement Feature (IEF) Five types of Integrity constraints defined in CREATE & ALTER: • Required data • Domain constraints • Entity integrity • Referential integrity • Enterprise constrains SQL (DDL) 9

Required Data • Null is distinct from blank or zero. • When NOT NULL

Required Data • Null is distinct from blank or zero. • When NOT NULL is specified, the system rejects any attempt to insert a null in the column. • If NULL is specified, the system accepts NULL. Syntax: column. Name data. Type [NOT NULL | NULL] Example: position VARCHAR(10) NOT NULL SQL (DDL) 10

Domain Constraints CHECK Syntax: CHECK (search condition) Example: sex CHAR NOT NULL CHECK (sex

Domain Constraints CHECK Syntax: CHECK (search condition) Example: sex CHAR NOT NULL CHECK (sex In (‘M’, ‘F’)) salary DECIMAL NOT NULL CHECK (salary > 10000); bno INT CHECK ( bno IN (SELECT branchno FROM branch) ) SQL (DDL) 11

Domain Constraints DOMAIN Syntax: CREATE DOMAIN domain. Name [AS] [DEFAULT default option ] [CHECK

Domain Constraints DOMAIN Syntax: CREATE DOMAIN domain. Name [AS] [DEFAULT default option ] [CHECK (search condition)]; datatype Example: CREATE DOMAIN Sex. Type AS CHAR DEFAULT ‘M’ CHECK (VALUE IN (‘M’, ‘F’)); CREATE DOMAIN Branch. Number AS CHAR(4) CHECK (VALUE IN (SELECT bno FROM branch)); SQL (DDL) 12

Domain Constraints DOMAIN Syntax: DROP DOMAIN Domain. Name [RESTRICT | CASCADE]; • RESTRICT, domain

Domain Constraints DOMAIN Syntax: DROP DOMAIN Domain. Name [RESTRICT | CASCADE]; • RESTRICT, domain must not be used in any existing table, view or assertion. • CASCADE, any column based on the domain is automatically changed to use the underlying data type, column constraint and default clause. SQL (DDL) 13

Entity Integrity PRIMARY KEY Syntax: PRIMARY KEY (attribute (, …)) Example: PRIMARY KEY (pno)

Entity Integrity PRIMARY KEY Syntax: PRIMARY KEY (attribute (, …)) Example: PRIMARY KEY (pno) PRIMARY KEY (cno, pno) • SQL rejects any operations that attempt to create duplication in the PK column. • PK forbids NULL value. SQL (DDL) 14

Entity Integrity UNIQUE • UNIQUE permits NULL value. • Every column that appears in

Entity Integrity UNIQUE • UNIQUE permits NULL value. • Every column that appears in a UNIQUE clause must also be declared in as NOT NULL. • UNIQUE can appear after a column definition or separately. Syntax: • UNIQUE(attribute • column. Name (, …)) data. Type [NOT NULL| NULL] [UNIQUE] Example: cno VARCHAR(5) NOT NULL; pno VARCHAR(5) NOT NULL; UNIQUE(cno, pno); pno VARCHAR(5) NOT NULL UNIQUE; 15

Referential Integrity FOREIGN KEY clause is defined in the CREATE & ALTER TABLE statements.

Referential Integrity FOREIGN KEY clause is defined in the CREATE & ALTER TABLE statements. Syntax: FOREIGN KEY (FK column (, …)) REFERENCES table_name [(CK column (, …))] Example: FOREIGN KEY (bno) REFERENCES branch ; branch (branch. No); • SQL rejects any INSET or UPDATE operation that attempts to create a foreign key value without a matching CK value key. • UPDATE or DELETE operation for a CK clause that has matching rows in another table is dependent on the referential action specified using ON UPDATE & ON DELETE subclauses. 16

Referential Integrity Four options are supported when the user attempt to delete or update

Referential Integrity Four options are supported when the user attempt to delete or update a CK, & there are matching FKs: • CASCADE: automatically delete/update the CK row & all matching (FKs) rows in child table. • SET NULL: delete/update the CK row & set the FK values to NULL. Valid only if NOT NULL clause is not specified for the FK. • SET DEFAULT: delete/update the CK row & set the FK values to default. Valid only if DEFAULT clause is specified for the FK. • NO ACTION: rejects the delete/update operation. Syntax: FOREIGN KEY ( FK column (, …) ) REFERENCES tablename [ ( CK column (, …) ) ] [ ON UPDATE [ CASCADE | SET NULL| SET DEFAULT| NO ACTION ] ] [ ON DELETE [ CASCADE | SET NULL| SET DEFAULT| NO ACTION ] ] SQL (DDL) 17

Referential Integrity Example: FOREIGN KEY (staff. No) REFERENCES staff ON DELETE SET NULL; FOREIGN

Referential Integrity Example: FOREIGN KEY (staff. No) REFERENCES staff ON DELETE SET NULL; FOREIGN KEY (owner. No) REFERENCES owner ON UPDATE CASCADE; FOREIGN KEY (MSSN) REFERENCES employee (SSN) ON DELETE SET DEFAULT ON UPDATE CASCADE; SQL (DDL) 18

Naming Constraints In order to modify or delete an existing constraint, it is necessary

Naming Constraints In order to modify or delete an existing constraint, it is necessary that the constraint have a name. Proceed the constraint by the CONSTRIANT clause then specify a name for the constraint. Example: Sex CHAR CONSTRAINT Sex. Type. Valid CHECK (sex IN (‘F’, ‘M’) ) Dept CHAR(4) NOT NULL CONSTRAINT Dep. No. In. List CHECK( Dno IN (SELECT Dept FROM DEPARTMENT)) CONSTRAINT IDISKey PRIMARY KEY (SSN) SQL (DDL) 19

Creating a DB Schema is a named collection of related database objects (tables, views,

Creating a DB Schema is a named collection of related database objects (tables, views, domains, . . . ) who belong to the same database application. Syntax CREATE SCHEMA [Name | AUTHORIZATION Identifier] Example: CRETAE SCHEMA company; CREATE SCHEMA AUTHORIZATION Smith; SQL (DDL) 20

Creating a DB Example: CREATE SCHEMA AUTHORIZATION blair CREATE TABLE sox (color VARCHAR 2(10)

Creating a DB Example: CREATE SCHEMA AUTHORIZATION blair CREATE TABLE sox (color VARCHAR 2(10) PRIMARY KEY, quantity NUMBER) CREATE VIEW red_sox AS SELECT color, quantity FROM sox WHERE color = ’RED’; SQL (DDL) 21

Destroying a DB Syntax DROP SCHEMA Name [RESTRICT | CASCADE] • RESTRICT, schema must

Destroying a DB Syntax DROP SCHEMA Name [RESTRICT | CASCADE] • RESTRICT, schema must be empty. • CASCADE, drop operation drops all objects associated with schema. SQL (DDL) 22

Creating a Table Syntax CREATE TABLE tablename { ( {column. Name data. Type [NOT

Creating a Table Syntax CREATE TABLE tablename { ( {column. Name data. Type [NOT NULL | NULL] [UNIQUE] [DEFAULT default. Option ] [CHECK (search condition)] (, …) } [PRIMARY KEY (column (, …) ) , ] [UNIQUE (column (, …) ) (, …) ] [FOREIGN KEY (FK column(, …)) REFERENCES tablename [(CK column(, …))] [ON UPDATE Referential. Action] [ON DELETE Referential. Action] (, …) ] [CHECK (search condition) (, …) ] ) } ; • DEFAULT clause provide a default value for a particular column. • PRIMARY KEY clause specify the column(s) that form the table’s PK. • FOREIGN KEY clause specify a foreign key in the table and relate it to another table. • Column-Based CHECK vs. Tuple-Based CHECK. • Constraints may be given names using CONSTRAINT clause. 23

Creating a Table DEPARTMENT( Dname, Dnumber) CREATE TABLE department ( Dname VARCHAR(15) NOT NULL,

Creating a Table DEPARTMENT( Dname, Dnumber) CREATE TABLE department ( Dname VARCHAR(15) NOT NULL, Dnumber INT NOT NULL, PRIMARY KEY (Dnumber), UNIQUE (Dname), CHECK (Dname NOT LIKE ‘% Inc. ’ ); SQL (DDL) AND Dnumber > 70) 24

Creating a Table EMPLOYEE( Fname, Lname, SSN, DOB, Address, Sex, Salary, Dno) CREATE DOMAIN

Creating a Table EMPLOYEE( Fname, Lname, SSN, DOB, Address, Sex, Salary, Dno) CREATE DOMAIN Sex. Type AS CHAR CHECK (VALUE IN (‘M’, ‘F’)); CREATE TABLE employee ( Fname VARCHAR(15) NOT NULL, Lname VARCHAR(15) NOT NULL, SSN CHAR(9) NOT NULL, DOB DATE, Address VARCHAR(30), Sex. Type DEFAULT ‘F’, Salary DECIMAL(10, 2), Dno INT NOT NULL, PRIMARY KEY (SSN), FOREIGN KEY (Dno) REFERENCES DEPARTMENT(Dnumber) ON DELETE SET DEFAULT ON UPDATE CASCADE ); SQL (DDL) 25

Creating a Table CREATE TABLE employee ( …… , Sex CONSTRAINT CHAR Sex. Value

Creating a Table CREATE TABLE employee ( …… , Sex CONSTRAINT CHAR Sex. Value CONSTRAINT Emp. SSN CONSTRAINT Emp. FK FOREIGN KEY (Dno) ON DELETE DEFAULT ‘F’ CHECK (Sex IN (‘M’, ‘F’)) , PRIMARY KEY (SSN), REFERENCES DEPARTMENT(Dnumber) SET DEFAULT ON UPDATE CASCADE ); SQL (DDL) 26

Changing a Table Definition ALTER consists of six options to: • Add a column

Changing a Table Definition ALTER consists of six options to: • Add a column to table • Drop a column from a table • Add a table constraint • Drop a table constraint • Set a default for a column • Drop a default for a column SQL (DDL) 27

Changing a Table Definition Syntax ALTER TABLE tablename [ADD [COLUMN] Column. Name data. Type

Changing a Table Definition Syntax ALTER TABLE tablename [ADD [COLUMN] Column. Name data. Type [NOT NULL] [UNIQUE] [DEFAULT default. Option] [CHECK (search condition)] ] [DROP[COLUMN] Column. Name [RESTRICT | CASCADE]] [ADD [CONSTRAINT [Constraint Name]] Table. Constraint Definition] [DROP CONSTRAINT Constraint. Name [RESTRICT | CASCADE]] [ALTER Column. Name SET DEFAULT Default. Option] [ALTER Column. Name DROP DEFAULT] ; • RESTRICT, drop operation is rejected if the column is referenced by another database object. • CASCADE, drop operation drops all column from objects it is referenced by. SQL (DDL) 28

Changing a Table Definition Example: Add an attribute for keeping track of jobs of

Changing a Table Definition Example: Add an attribute for keeping track of jobs of staff in the company schema. ALTER ADD TABLE company. staff job VARCHAR(12); Example: Remove the address attribute from the staff table. ALTER TABLE company. staff DROP address CASCASE; SQL (DDL) 29

Changing a Table Definition Example: Change the staff table by removing the default of

Changing a Table Definition Example: Change the staff table by removing the default of ‘Assistant’ for the position column and setting the default for the sex column to female. ALTER TABLE staff ALTER position DROP DEFAULT; ALTER TABLE ALTER sex SQL (DDL) staff SET DEFAULT ‘F’; 30

Changing a Table Definition Example: Change the Property. For. Rent table by removing the

Changing a Table Definition Example: Change the Property. For. Rent table by removing the constraint that the staff are not allowed more than 100 properties at a time (Staff. Not. Handling. Too. Much). ALTER TABLE Property. For. Rent DROP CONSTRAINT Staff. Not. Handling. Too. Much CASCADE; Example: Change the employee table by making name a primary key other than Id. ALTER TABLE Employee DROP CONSTRAINT IDISKey CASCADE ADD CONSTRAINT Name. Is. Key PRIMARY KEY (name); SQL (DDL) 31

Changing a Table Definition Example: Change the Client table by adding a new column

Changing a Table Definition Example: Change the Client table by adding a new column representing the preferred number of rooms. ALTER TABLE Client ADD Pref. No. Rooms Property. Rooms; SQL (DDL) 32

Removing a Table Syntax DROP TABLE tablename [RESTRICT | CASCADE]; • RESTRICT, drop operation

Removing a Table Syntax DROP TABLE tablename [RESTRICT | CASCADE]; • RESTRICT, drop operation is rejected if there any other objects that depend for their existence upon the existence of the table to be dropped. • CASCADE, drop operation drops all dependent objects. SQL (DDL) 33

Creating an Index is a structure that provides accelerated access to rows of a

Creating an Index is a structure that provides accelerated access to rows of a table based on the value of one or more attributes. Indexes are updated every time the underlying tables are modified. Created only on base tables. Syntax CREATE [UNIQUE] INDEX Index. Name ON table. Name (column. Name [ASC | DESC] [, …]) Example: CRETAE UNIQUE INDEX Staff. Ind ON staff (Staff. No); CREATE INDEX Rent. Ind ON Property. For. Rent (city, rent); SQL (DDL) 34

Removing an Index Syntax DROP SQL (DDL) INDEX Indexname; 35

Removing an Index Syntax DROP SQL (DDL) INDEX Indexname; 35

Creating a View Syntax CREATE VIEW View. Name [(new. Column. Name [, …])] AS

Creating a View Syntax CREATE VIEW View. Name [(new. Column. Name [, …])] AS subselect [WITH [CASCADE | LOCAL] CHECK OPTION] New. Column. Name assign a name to each column in view. If WITH CHECK OPTION is specified, if a row fails to satisfy the WHERE clause, it is not added to the base table of the view. SQL (DDL) 36

Creating a View (Horizontal) Example: Create a view for managers at branch B 003

Creating a View (Horizontal) Example: Create a view for managers at branch B 003 can see only the details for staff who work in their branch office. CREATE VIEW Maneger 3 Staff AS SELECT * FROM staff WHERE branch. No = ‘B 003’; SELECT * FROM Manager 3 Staff; SQL (DDL) 37

Creating a View (Vertical) Example: Create a view for staff details at branch B

Creating a View (Vertical) Example: Create a view for staff details at branch B 003 that excludes salary information. CREATE VIEW Staff 3 AS SELECT Staff. No, Fname, Lname, position, sex FROM staff WHERE branch. No = ‘B 003’; CREATE VIEW Staff 3 AS SELECT Staff. No, Fname, Lname, position, sex FROM Manager 3 Staff; SQL (DDL) 38

Creating a View (Groups & Join) PROPERTYFORRENT (pno, street, area, city, pcode, type, rooms,

Creating a View (Groups & Join) PROPERTYFORRENT (pno, street, area, city, pcode, type, rooms, rent, sno) STAFF (sno, fname, lname, position, sex, DOB, salary, bno) Example: Create a view for staff who manage properties for rent, which include the branch number they work at, their staff number, and the number of properties they manage. CREATE VIEW Staff. Prop. Count (Branch. No, Staff. No, cnt) AS SELECT s. Bno, s. Sno, COUNT(*) FROM Staff s, Property. For. Rent p WHERE s. sno = p. sno GROUP BY s. bno, s. sno; SQL (DDL) 39

Branch. No SQL (DDL) Staff. No Cnt B 003 SG 14 1 B 003

Branch. No SQL (DDL) Staff. No Cnt B 003 SG 14 1 B 003 SG 37 2 B 005 SL 41 1 B 007 SA 9 1 40

Removing a View Syntax DROP VIEW View. Name [RESTRICT | CASCADE]; • RESTRICT, drop

Removing a View Syntax DROP VIEW View. Name [RESTRICT | CASCADE]; • RESTRICT, drop operation is rejected if there any other objects that depend for their existence upon the existence of the view to be dropped. • CASCADE, drop operation drops all views defined on the dropped view. SQL (DDL) 41

Restrictions on Accessing Views 1. If a column in the view is based on

Restrictions on Accessing Views 1. If a column in the view is based on aggregation function, then the column may appear only in SELECT and ORDER BY clauses of queries that access the view. Example: Illegal operation SELECT COUNT(cnt) FROM Staff. Prop. Count; SELECT * FROM Staff. Prop. Count WHERE cnt > 2; 2. Grouped view may never be joined with a base table or a view. SQL (DDL) 42

View Updatability For a view to be updatable, the DBMS must be able to

View Updatability For a view to be updatable, the DBMS must be able to trace any row or column back to its row or column in the source table. All updates to a base relation are immediately reflected in all views that reference that base relation. All updates to a view will be reflected in the underlying base relation, under the following rules: - Updates are allowed through a view defined using a simple query involving a single base relation & containing either the PK or a CK of the base relation. - Update are NOT allowed through views involving multiple base relations. - Updates are NOT allowed through views involving aggregation or grouping operations. SQL (DDL) 43

View Updatability Example: Illegal operation INSERT INTO Staff. Prop. Count VALUES (‘B 003’, ‘SG

View Updatability Example: Illegal operation INSERT INTO Staff. Prop. Count VALUES (‘B 003’, ‘SG 5’, SQL (DDL) 2); 44

View Updatability Example: Illegal operation CREATE TABLE Property. For. Rent( Pno VARCHAR(5) NOT NULL,

View Updatability Example: Illegal operation CREATE TABLE Property. For. Rent( Pno VARCHAR(5) NOT NULL, city VACHAR(15) NOT NULL, … ); CREATE VIEW Staff. Prop. List (bno, sno, pno) AS SELECT s. bno, s. sno, p. pno FROM staff s, propertyforrent p WHERE s. sno = p. sno; INSERT INTO Staff. Prop. List VALUES (‘B 003’, ‘SG 5’, SQL (DDL) ‘PG 19’); 45

View Updatability A view is updatable if: • DISTINCT not specified. • Every column

View Updatability A view is updatable if: • DISTINCT not specified. • Every column in the SELECT statement is a column name (rather than constant, expression, or aggregation function). • FROM clause specifies only one table. • The WHERE clause does not include any subquesries. • There is no GROUP BY or HAVING clause. • Any row inserted through the view must not violate the integrity constraints of the base table. SQL (DDL) 46

WITH CHECK OPTION If a row in a view is altered in a way

WITH CHECK OPTION If a row in a view is altered in a way that is no longer satisfies the condition, then it will disappear from the view (migration rows). WITH CHECK OPTION prohibits a row migration out of the view. • When INSERT or UPDATE statement on the view violates the WHERE condition, the operation is rejected. [LOCAL | CASCADE] applicable to view hierarchies. • LOCAL, any row inserted or updated on this view, must not cause the row to disappear from the view, unless the row also disappears from the underlying derived view/table. • CASCADE, any row inserted or updated on this view and view defined on this view must not cause the row to disappear from the view. SQL (DDL) 47

WITH CHECK OPTION Example: CREATE VIEW Manager 3 Staff AS SELECT * FROM Staff

WITH CHECK OPTION Example: CREATE VIEW Manager 3 Staff AS SELECT * FROM Staff WHERE bno = ‘B 003’ WITH CHECK OPTION; UPDATE Manager 3 Staff SET bno = ‘B 005’ WHERE sno = ‘SG 37’; INSERT INTO Manager 3 Staff VALUES (‘SL 15’, ‘Mary’, ‘Black’, ‘Assistant’, DATE ‘ 1987 -06 -12’, 8000, ‘B 002’); SQL (DDL) ‘F’, 48

WITH CHECK OPTION Example: CREATE VIEW Low. Salary AS SELECT * FROM Staff WHERE

WITH CHECK OPTION Example: CREATE VIEW Low. Salary AS SELECT * FROM Staff WHERE salary > 9000; CREATE VIEW Manager 3 Staff AS SELECT * FROM High. Salary WHERE bno = ‘B 003’; CREATE VIEW High. Salary AS SELECT * FROM Low. Salary WHERE salary > 10000 WITH LOCAL CHECK OPTION; UPDATE Manager 3 Staff SET Salary = 9500 WHERE Sno = ‘SG 37’; SQL (DDL) 49