22
1 SQL - DDL SQL DDL statements are used to create and manipulate the schema definitions of base tables, view tables, domains, assertions (integrity constraints), privileges and so on. The statements include: CREATE TABLE ALTER TABLE DROP TABLE CREATE VIEW DROP VIEW GRANT REVOKE Relational DBMS products vary even more widely in the DDL features supported than DML features.

SQL DDL statements are used to create and manipulate the ...1 SQL - DDL • SQL DDL statements are used to create and manipulate the schema definitions of base tables, view tables,

  • Upload
    others

  • View
    36

  • Download
    1

Embed Size (px)

Citation preview

Page 1: SQL DDL statements are used to create and manipulate the ...1 SQL - DDL • SQL DDL statements are used to create and manipulate the schema definitions of base tables, view tables,

1

SQL - DDL

• SQL DDL statements are used to create and manipulate the schema definitions

of base tables, view tables, domains, assertions (integrity constraints),

privileges and so on.

• The statements include:

CREATE TABLE

ALTER TABLE

DROP TABLE

CREATE VIEW

DROP VIEW

GRANT

REVOKE

• Relational DBMS products vary even more widely in the DDL features

supported than DML features.

Page 2: SQL DDL statements are used to create and manipulate the ...1 SQL - DDL • SQL DDL statements are used to create and manipulate the schema definitions of base tables, view tables,

2

BASE TABLES

• A base table is a named table which exists in its own right. We can think of a

base table as being supported by actual stored rows in database files.

• The CREATE TABLE statement is used to define a new base table:

CREATE TABLE SUPPLIER

(SNUM VARCHAR(5) NOT NULL,

SNAME VARCHAR(20) NOT NULL,

STATUS NUMERIC(5) DEFAULT 20 NOT NULL,

CITY VARCHAR(15) DEFAULT 'LONDON' NOT NULL,

CONSTRAINT PK_SUPPLIER PRIMARY KEY (SNUM),

CONSTRAINT UNQ_SNAME UNIQUE (SNAME),

CONSTRAINT CHECK_STATUS CHECK (STATUS > 0))

• The table has 4 columns - SNUM, SNAME, STATUS and CITY. Each column has

a data type defined for it, and constraints are being defined to further limit the

acceptable values which may be stored in the table.

Page 3: SQL DDL statements are used to create and manipulate the ...1 SQL - DDL • SQL DDL statements are used to create and manipulate the schema definitions of base tables, view tables,

3

• In the definition of the SUPPLIER table, a data type (either VARCHAR or

NUMERIC) has been defined for each column. Some examples of SQL data

types are:

CHAR(n) Fixed length string of exactly n characters.

VARCHAR(n) Variable length string of up to n characters.

NUMERIC(p,s) Decimal number with p digits (precision) and decimal

point s digits (scale) from the right. The number may be

signed.NUMERIC(p) An abbreviation for NUMERIC(p,0).

NUMERIC An abbreviation for NUMERIC(p) where p is

implementation defined.

• Other data types for strings and numbers exist, for example for bit strings and

floating point numbers, as well as other data types, for example for dates and

times.

• When defining a column, it is possible to specify a default value. The default value will be used if an INSERT statement does not specify an explicit value for

the column in a new row.

Page 4: SQL DDL statements are used to create and manipulate the ...1 SQL - DDL • SQL DDL statements are used to create and manipulate the schema definitions of base tables, view tables,

4

INTEGRITY CONSTRAINTS

• In addition to data types, SQL supports integrity constraints including NOT NULL

column constraints, CHECK constraints, and primary, alternate and foreign key

definitions.

NOT NULL

• Any column of a base table may be specified as NOT NULL, indicating that it is

not possible for a null value to be stored in any row for the column in question.

CHECK

• A check constraint is of the form: CHECK ( conditional-expression )

e.g.

CONSTRAINT CHECK_STATUS CHECK (STATUS > 0)

• A change to a row in a table (INSERT, UPDATE, DELETE) violates the constraint

and is prevented if the conditional expression evaluates to "false" by reference

to any row in the table: the constraint is not violated if the conditional expression

evaluates to "true" or "unknown".

Page 5: SQL DDL statements are used to create and manipulate the ...1 SQL - DDL • SQL DDL statements are used to create and manipulate the schema definitions of base tables, view tables,

5

Another example CHECK constraint follows. This constraint on the SUPPLY table

would ensure that the quantity of any supply instance by a London supplier did not

exceed 2000.

CONSTRAINT CHECK_LONDON_S_QUANTITY

CHECK (SUPPLY.QUANTITY <= 2000]

OR NOT EXISTS

(SELECT *

FROM SUPPLIER

WHERE SUPPLIER.CITY = 'LONDON'

AND SUPPLIER.SNUM = SUPPLY.SNUM))

Page 6: SQL DDL statements are used to create and manipulate the ...1 SQL - DDL • SQL DDL statements are used to create and manipulate the schema definitions of base tables, view tables,

6

• If a CHECK, PRIMARY KEY or UNIQUE constraint only involves a single column it

may be defined as part of the column definition. Hence, table SUPPLIER could

have been defined as:

CREATE TABLE SUPPLIER

(SNUM VARCHAR(5) NOT NULL PRIMARY KEY,

SNAME VARCHAR(20) NOT NULL UNIQUE,

STATUS NUMERIC(5) DEFAULT 20 NOT NULL

CHECK (STATUS > 0),

CITY VARCHAR(15) DEFAULT 'LONDON' NOT NULL)

• Oracle supports a restricted form of CHECK constraint in which the conditional

expression may only refer to columns in the table whose definition the

constraint appears in, and the conditional expression must be evaluable for

each row in the table individually.

Page 7: SQL DDL statements are used to create and manipulate the ...1 SQL - DDL • SQL DDL statements are used to create and manipulate the schema definitions of base tables, view tables,

7

CANDIDATE KEYS

• Candidate keys for a base table may be specified with either a PRIMARY KEY

or UNIQUE clause.

• A candidate key constraint is satisfied if and only if no two rows in the table

have the same non-null values in the candidate key columns.

• For a given base table at most one candidate key may be specified as a primary

key.

• A primary key may consist of a list of columns. Primary key column(s) are implicitly NOT NULL even if explicit NOT NULL constraints are omitted.

• Alternate keys for a table are specified with UNIQUE. Again, the key may be

formed by multiple columns.

• Unlike PRIMARY KEY columns, alternate key columns are not necessarily NOT

NULL.

Page 8: SQL DDL statements are used to create and manipulate the ...1 SQL - DDL • SQL DDL statements are used to create and manipulate the schema definitions of base tables, view tables,

8

FOREIGN KEYS

• SQL supports the idea of a foreign key, namely a column or columns in one

"referencing" table which must match the values of a key in a second (not

necessarily distinct) "referenced" table.

• SQL allows the referenced key to be an alternate key instead of a primary key

(unlike many definitions of the relational model). e.g.

CREATE TABLE SUPPLY

(SNUM VARCHAR(5) NOT NULL,

PNUM VARCHAR(6) NOT NULL,

JNUM VARCHAR(4) NOT NULL,

QUANTITY NUMERIC(9),

PRIMARY KEY (SNUM, PNUM, JNUM),

FOREIGN KEY (SNUM) REFERENCES SUPPLIER

ON DELETE CASCADE ON UPDATE CASCADE,

FOREIGN KEY (PNUM) REFERENCES PART

ON DELETE CASCADE ON UPDATE CASCADE,

FOREIGN KEY (JNUM) REFERENCES PROJECT

ON DELETE CASCADE ON UPDATE CASCADE)

Page 9: SQL DDL statements are used to create and manipulate the ...1 SQL - DDL • SQL DDL statements are used to create and manipulate the schema definitions of base tables, view tables,

9

• Three foreign keys have been defined. In this particular case the foreign keys

are part of the referencing table’s own primary key, but that is not necessary.

• Neither is it necessary for foreign keys to be NOT NULL (unless of course they

do form part of the table’s own primary key).

• Each foreign key specifies the existing "referenced“ table holding the key which

the foreign key values must match.

• If a table without specific columns is referenced, that table must have a matching PRIMARY KEY definition for the column(s).

• If a reference is made to particular columns in a table, as for example in

FOREIGN KEY (SNAME) REFERENCES SUPPLIER (SNAME)

the referenced table could have a matching alternate key UNIQUE definition

rather than a PRIMARY KEY definition.

Page 10: SQL DDL statements are used to create and manipulate the ...1 SQL - DDL • SQL DDL statements are used to create and manipulate the schema definitions of base tables, view tables,

10

• If an INSERT or UPDATE of a row in the referencing table would cause a

foreign key constraint to be violated, the INSERT or UPDATE is rejected.

• A DELETE or UPDATE on a referenced table may also cause a foreign key

constraint to be violated. The default action is that the DELETE or UPDATE will

be rejected.

• However, use of the optional ON DELETE or ON UPDATE clauses enable other

actions to be specified. In the example, deletes and updates on the referenced

table are “cascaded” to the referencing table to ensure the constraints are not

violated.

• The cascaded updates and deletes may themselves result in further cascaded

updates and deletes if the referencing table is itself referenced by foreign key

definitions.

• Oracle provides support for foreign keys as described except its support for ON

DELETE and ON UPDATE is limited to an optional ON DELETE CASCADE or ON

DELETE SET NULL clause.

Page 11: SQL DDL statements are used to create and manipulate the ...1 SQL - DDL • SQL DDL statements are used to create and manipulate the schema definitions of base tables, view tables,

11

DEFERRED CONSTRAINT CHECKING

• By default, integrity constraints are checked after each SQL statement is

executed, and if there is a constraint violation the statement fails.

• However, the example of two base tables each with a foreign key referencing

the other shows that this can cause problems.

• Deferred constraint checking enables each constraint to be in the default IMMEDIATE mode, or DEFERRED mode in which case constraint checking is

deferred until a later point in the transaction.

• When a constraint is defined it is possible to specify whether or not checking of

the constraint may be deferred, and the initial mode which will be used for

• checking in each new transaction. For example:

CONSTRAINT FK1 ... INITIALLY DEFERRED

CONSTRAINT FK2 ... INITIALLY IMMEDIATE DEFERRABLE

CONSTRAINT FK3 ... INITIALLY IMMEDIATE NOT DEFERRABLE

-- the last is the default

Page 12: SQL DDL statements are used to create and manipulate the ...1 SQL - DDL • SQL DDL statements are used to create and manipulate the schema definitions of base tables, view tables,

12

• In order to switch modes during a transaction, the SET CONSTRAINTS

statement is used, as in:

SET CONSTRAINTS FK2 DEFERRED

SET CONSTRAINTS FK1, FK2 IMMEDIATE

SET CONSTRAINTS ALL IMMEDIATE

-- ALL is shorthand for all deferrable constraints

• If a constraint is switched to IMMEDIATE mode during a transaction, it is

checked at that point. If there is a constraint violation then the SET

CONSTRAINTS statement fails and checking of the constraint will remain in

DEFERRED mode.

• If a transaction executes a COMMIT with any constraints still in DEFERRED

mode, then they are checked at that point and the transaction fails and rolls

back if there is any constraint violation.

• Oracle provides support for deferred constraint checking as described.

Page 13: SQL DDL statements are used to create and manipulate the ...1 SQL - DDL • SQL DDL statements are used to create and manipulate the schema definitions of base tables, view tables,

13

ALTER TABLE and DROP TABLE

• An existing base table may be altered in a number of ways through use of

ALTER TABLE:

• A new column may be added to a table.

• The default definition of an existing column may be modified.

• An existing column may be removed.

• An integrity constraint may be added or removed.

• An existing base table may be removed with DROP TABLE.

Page 14: SQL DDL statements are used to create and manipulate the ...1 SQL - DDL • SQL DDL statements are used to create and manipulate the schema definitions of base tables, view tables,

14

VIEWS

• Views are tables derived from one or more other tables (base tables or views) by the evaluation of a SELECT query expression. They can be thought of as

providing an "external level" definition of table structures corresponding to the

"conceptual level" definition of base tables.

• Views provide:

• logical data independence

• a security mechanism

• a simplified application view of the content of a database.

• A view’s defining query expression is usually stored (in the data

dictionary/catalog) and the view table rows are formed as a matter of query evaluation when required.

Page 15: SQL DDL statements are used to create and manipulate the ...1 SQL - DDL • SQL DDL statements are used to create and manipulate the schema definitions of base tables, view tables,

15

• View definitions are created with CREATE VIEW and removed with DROP VIEW.

e.g.

CREATE VIEW RED_PARTS (PNUM, PNAME, WEIGHT, CITY) AS

SELECT P#, PNAME, WEIGHT, CITY

FROM PART

WHERE COLOUR = 'RED'

• Having created a view, it may be the subject of data manipulation statements as

if it were a "real" base table:

SELECT *

FROM RED_PARTS

PNUM PNAME WEIGHT CITY

------ ----------- ------- ---------

P1 NUT 12 LONDON

P4 SCREW 14 LONDON

P6 COG 19 LONDON

Page 16: SQL DDL statements are used to create and manipulate the ...1 SQL - DDL • SQL DDL statements are used to create and manipulate the schema definitions of base tables, view tables,

16

• To execute a query on the view, the DBMS can usually merge the query with the

view definition to produce an equivalent modified query. So

SELECT *

FROM RED_PARTS

WHERE WEIGHT > 13

can be translated by the DBMS to a query on "real" base tables:

SELECT P#, PNAME, WEIGHT, CITY

FROM PART

WHERE COLOUR = 'RED'

AND WEIGHT > 13

• Alternatively a DBMS may separately temporarily "materialize" i.e. construct the view table and then query it.

Page 17: SQL DDL statements are used to create and manipulate the ...1 SQL - DDL • SQL DDL statements are used to create and manipulate the schema definitions of base tables, view tables,

17

• Updates on views may cause difficulty. Given an INSERT, DELETE or UPDATE

on a view, there may be no way or multiple ways the base tables can be

modified to reflect the updated view. e.g.

CREATE VIEW LOCAL_PART AS

SELECT PNAME, JNAME

FROM PART, PROJECT

WHERE PART.CITY = PROJECT.CITY

SELECT *

FROM LOCAL_PART

PNAME JNAME

-------------------- ----------

NUT RAID

NUT TAPE

BOLT SORTER

SCREW DISPLAY

SCREW RAID

SCREW TAPE

CAM SORTER

COG RAID

COG TAPE

Page 18: SQL DDL statements are used to create and manipulate the ...1 SQL - DDL • SQL DDL statements are used to create and manipulate the schema definitions of base tables, view tables,

18

• Bearing in mind only one "RAID" row exists in PROJECT whereas three "RAID"

rows exist in LOCAL_PART, what should the effect of the following update

statement be?

UPDATE LOCAL_PART

SET JNAME = 'WIRE'

WHERE JNAME = 'RAID'

AND PNAME = 'NUT'

• The definition of SQL specifies that a view table is updatable if and only if

certain conditions hold for the defining query expression. These conditions are

rather complex under later SQL standards - the rather simpler conditions under

SQL-92 include:• The top-level SELECT expression does not specify DISTINCT.

• The top-level SELECT list consists of column references rather than

aggregate functions or other general expressions.• The top-level FROM clause only refers to one table, which is itself a base

table or updatable view.• The top-level SELECT expression does not include a GROUP BY or HAVING

clause.• and others...

Page 19: SQL DDL statements are used to create and manipulate the ...1 SQL - DDL • SQL DDL statements are used to create and manipulate the schema definitions of base tables, view tables,

19

• One integrity constraint exists specifically for use with views - the CHECK

OPTION.

• Consider the following (updatable) view definition and sequence of DML

statements.

CREATE VIEW HEAVY_PART AS

SELECT P#, PNAME, COLOUR, WEIGHT, CITY

FROM PART

WHERE WEIGHT > 15

SELECT *

FROM HEAVY_PART

P# PNAME COLOUR WEIGHT CITY

------ --------- ------ ---------- --------

P2 BOLT GREEN 17 PARIS

P3 SCREW BLUE 17 ROME

P6 COG RED 19 LONDON

UPDATE HEAVY_PART

SET WEIGHT = 14

WHERE P# = 'P2'

Page 20: SQL DDL statements are used to create and manipulate the ...1 SQL - DDL • SQL DDL statements are used to create and manipulate the schema definitions of base tables, view tables,

20

SELECT *

FROM HEAVY_PART

P# PNAME COLOUR WEIGHT CITY

------ --------- ------ ---------- ---------

P3 SCREW BLUE 17 ROME

P6 COG RED 19 LONDON

• The effect of the update is that a row has disappeared from HEAVY_PART since

the updated row no longer figures in the result of the query defining the view.

• To prevent a row inserted or updated in a view from disappearing in this way, the view may be defined WITH CHECK OPTION as in:

CREATE VIEW HEAVY_PART AS

SELECT P#, PNAME, COLOUR, WEIGHT, CITY

FROM PART

WHERE WEIGHT > 15

WITH CHECK OPTION

• With the check option in force, a view insertion or update is rejected if the modified rows would not then satisfy the view definition.

Page 21: SQL DDL statements are used to create and manipulate the ...1 SQL - DDL • SQL DDL statements are used to create and manipulate the schema definitions of base tables, view tables,

21

PRIVILEGES

• The person who creates and so "owns" an object (base table, view...) has a

series of privileges enabling him or her to then use the object. Privileges include SELECT, DELETE, INSERT and UPDATE to manipulate a specific owned table

in the obvious ways.

• The owner of an object may then use the GRANT statement to grant specific

privileges on an object to other users.

e.g.

GRANT SELECT, INSERT ON TABLE PART TO TOM, ANNE

authorizes users TOM and ANNE to execute SELECT and INSERT

statements on the PART table.

• Privileges may be withdrawn using the REVOKE statement, as in:

REVOKE SELECT ON TABLE PART FROM TOM

Page 22: SQL DDL statements are used to create and manipulate the ...1 SQL - DDL • SQL DDL statements are used to create and manipulate the schema definitions of base tables, view tables,

22

• Normally a granted privilege on an object may not be itself granted by the

recipient to a further user. However, if the grantor wishes the recipient of a

privilege to be able to grant that privilege to others, it can be done with use of WITH GRANT OPTION.

e.g.GRANT UPDATE ON TABLE SUPPLY TO TOM

WITH GRANT OPTION

• Use of roles can often simplify administration of privileges. Rather than granting

each privilege separately to each user, a suitable role could be created e.g. a "developer" role - CREATE ROLE DEVELOPER - and the privileges granted to

the role:

GRANT SELECT, DELETE, INSERT, UPDATE ON TABLE SUPPLIER

TO DEVELOPER

• That role could then be granted to each user who is a developer so each has

the privileges associated with the role:

GRANT DEVELOPER TO TOM, ANNE, MARY, BILL