©silberschatz, korth and sudarshan6.1database system concepts schema management and sql as ddl...
Post on 21-Dec-2015
220 views
TRANSCRIPT
©Silberschatz, Korth and Sudarshan6.1Database System Concepts
Schema Management and SQL as DDLSchema Management and SQL as DDL Professor Kedem’s changes, if any, are marked in green, they
are not copyrighted by the authors, and the authors are not responsible for them.
Dennis writes in blue.
©Zvi M. Kedem
©Silberschatz, Korth and Sudarshan6.2Database System Concepts
DDL -- Data Definition LanguageDDL -- Data Definition Language SQL, as part of the ANSI standard, has certain DDL capabilities.
Unfortunately, they are not sufficient to really manage the database.
We will therefore describe the main features of the standard, while also describing some common nonstandard extensions.
We will continue with the example of our database consisting of the relations:
• PLANTS(P#,PNAME,CITY,MARGIN)
• CUSTOMERS(C#,CNAME,CITY,P#)
• ORDERS(O#,AMT,DATE,C#)
©Zvi M. Kedem
©Silberschatz, Korth and Sudarshan6.3Database System Concepts
ExampleExample
PLANTS(P#,PNAME,CITY,MARGIN)
CUSTOMERS(C#,CNAME,CITY,P#)
ORDERS(O#,AMT,DATE,C#)
Plants talks about factories, each has a profit margin
Customers are assigned to plants
Orders are placed by customers
©Zvi M. Kedem
©Silberschatz, Korth and Sudarshan6.4Database System Concepts
Defining Base RelationsDefining Base Relations Base relations, that is the relations in the conceptual level, are
defined using the CREATE command.
At the minimum, this command specifies:
• The name of the relation.
• The names of the columns of the relation.
• The domains for each column. Permitted domains are: CHARACTER (CHAR), NUMERIC, DECIMAL (DEC), INTEGER (INT), SMALLINT, FLOAT, DOUBLE PRECISION, REAL, with various lengths and precision specifications.
©Zvi M. Kedem
©Silberschatz, Korth and Sudarshan6.5Database System Concepts
A Simplest DefinitionA Simplest Definition CREATE TABLE PLANTS
(P# DECIMAL(5),PNAME CHAR(20),CITY CHAR (25),MARGIN REAL);
There are many additional aspects of the relation that can generally be specified, and we will examine them in turn by means of making the example more and more comprehensive.
©Zvi M. Kedem
©Silberschatz, Korth and Sudarshan6.6Database System Concepts
NULLS And Default ValuesNULLS And Default Values It is possible to specify for a column that:
• It cannot have a NULL value, or
• What is the default, if the value is not specified (say in an insertion)
• CREATE TABLE PLANTS(P# DECIMAL(5) NOT NULL,PNAME CHAR(20) DEFAULT 'MISSING',CITY CHAR (25) NOT NULL DEFAULT 'CHICAGO',MARGIN REAL);
©Zvi M. Kedem
©Silberschatz, Korth and Sudarshan6.7Database System Concepts
Integrity ConstraintsIntegrity Constraints We can specify certain integrity constraints:
• CREATE TABLE PLANTS(P# DECIMAL(5),PNAME CHAR(20),CITY CHAR (25),MARGIN REAL,CHECK ( P# BETWEEN 1 AND 44444),CHECK ( CITY IN ('CHICAGO', 'DAYTONA')),CHECK ( CITY <> 'CHICAGO' OR MARGIN > 0.0));
• Note that the last integrity constraint is equivalent to:
• CITY = 'CHICAGO' MARGIN > 0.0.
So we have in general CHECK ( predicate )
©Zvi M. Kedem
©Silberschatz, Korth and Sudarshan6.8Database System Concepts
Specifying KeysSpecifying Keys We can specify alternate keys (or superkeys). For instance, to
specify that both C# by itself and the pair PNAME, CITY uniquely identify a tuple we could write:
• CREATE TABLE PLANTSP# DECIMAL(5),PNAME CHAR(20),CITY CHAR (25),MARGIN REAL,UNIQUE (P#),UNIQUE (PNAME,CITY));
They are supersets of keys and not necessarily keys, because some proper subset may also be unique. For example, we could specify UNIQUE(P#, City).
UNIQUE fields may be null, but should not be.
©Zvi M. Kedem
©Silberschatz, Korth and Sudarshan6.9Database System Concepts
Primary KeysPrimary Keys We could specify a set of columns that uniquely identifies a tuple as a
primary key. Only one such set can be defined for any relation. We could therefore write:
• CREATE TABLE PLANTSP# DECIMAL(5),PNAME CHAR(20),CITY CHAR (25),MARGIN REAL,PRIMARY KEY (P#),UNIQUE (PNAME,CITY));
Attributes of a primary cannot be NULL (this does not need be specified but is assumed automatically for attributes of primary key, this will not permit us to naturally use COUNTRY, STATE/TERRITORY, NAME as primary key with allowing null STATE/TERRITORY)
Primary keys, and foreign keys (defined next) are used for certain integrity checks.
Most database systems establish an index for each unique combination. If yours does not, then build an index yourself.
©Zvi M. Kedem
©Silberschatz, Korth and Sudarshan6.10Database System Concepts
!!Foreign KeysForeign Keys Assume that the application is such that if a value appears as
some C# in the relation orders then it specifies a single definite tuple in the relation customers.
We specify this foreign key constraint by;• CREATE TABLE ORDERS
(..., ..., ...,FOREIGN KEY C#REFERENCES CUSTOMERS(C#));
This could be done only if C# was defined as primary key in the relation CUSTOMERS. (It is a coincidence that in the example in both relations the same name, C#, was given to customer number.)
For some variants of SQL:
REFERENCES CUSTOMERS (no need to specify primary key)
©Zvi M. Kedem
©Silberschatz, Korth and Sudarshan6.11Database System Concepts
Maintenance of Referential IntegrityMaintenance of Referential Integrity In order to maintain this referential integrity constraint, the
system will reject any operation that will violate it.
This constraint “will act” when:
• An INSERT or an UPDATE on ORDERS is attempted that would create a value of of C# that does not exist in CUSTOMERS.
• A DELETE or an UPDATE on CUSTOMERS is attempted that will leave tuples in orders in which the value of C# does not appear in any tuple of CUSTOMERS.
Unless anything additional is specified in the constraint then there will be NO ACTION, that is the above will not be permitted
©Zvi M. Kedem
©Silberschatz, Korth and Sudarshan6.12Database System Concepts
Maintenance of Referential Integrity Maintenance of Referential Integrity (Cont.)(Cont.)
Other options to maintain integrity when actions violating the referential integrity are attempted on the table that has the primary key.
• CASCADE
Here the new value of the primary key is copied to the foreign key
• SET NULL
Here the new value of the foreign key is NULL
• SET DEFAULT
Here the new value of the foreign key is a specified default value
©Zvi M. Kedem
©Silberschatz, Korth and Sudarshan6.13Database System Concepts
More About ConstraintsMore About Constraints table constraint is:
[CONSTRAINT constraint name] {PRIMARY KEY (column name.,..)} | {UNIQUE (column name.,..)} | {FOREIGN KEY (column name.,..)} REFERENCES table name [(column name.,..)] [referential specification]} | {CHECK predicate} [[INITIALLY DEFERRED | INITIALLY IMMEDIATE] [ [NOT] DEFERRABLE] ]
column constraint is:[CONSTRAINT constraint name] {NOT NULL} | {PRIMARY KEY} | {UNIQUE} | {REFERENCES table name [(column name)] [referential specification]} | {check predicate} [[INITIALLY DEFERRED | INITIALLY IMMEDIATE] [ [NOT] DEFERRABLE] ]
referential specification is:[MATCH {FULL | PARTIAL}] [ON UPDATE {CASCADE | SET NULL | SET DEFAULT | NO ACTION } ] [ON DELETE {CASCADE | SET NULL | SET DEFAULT | NO ACTION } ]
Note: it is a good idea to name constraints, as they can be later dropped while referring to their names
©Zvi M. Kedem
©Silberschatz, Korth and Sudarshan6.14Database System Concepts
More About Constraints (Cont.)More About Constraints (Cont.) Constraints are checked as tables are modified (immediately or deferred
until later).
• Essentially, each row of the table has to satisfy the constraint
The actual checking is done either after each statement or at the end of a transaction
• It is done at the end, to allow changes that cannot be done in a single statement
Formal meaning of the CHECK constraint:
It is violated when the following set is not empty:
SELECT *FROM tablesWHERE NOT predicate
Conclusion: An empty relation satisfies all CHECK conditions!!!
©Zvi M. Kedem
©Silberschatz, Korth and Sudarshan6.15Database System Concepts
Assertions (optional)Assertions (optional) Assertion is like a CHECK constraint that is not attached to a
table definition; it is “free floating”
CREATE ASSERTION SMALL_ENTERPRISECHECK( (SELECT COUNT (*) FROM PLANTS) + (SELECT COUNT (*)FROM CUSTOMERS) < 1000)
Assertions are more natural then previously described constraints, especially when refererring to several tables
Often deleted though if they are expensive to run. In fact, it is rare to see constraints or assertions other than simple value constraints (e.g. bal >= 0), unique, or foreign key constraints.
©Zvi M. Kedem
©Silberschatz, Korth and Sudarshan6.16Database System Concepts
Assertions vs. ChecksAssertions vs. Checks Assertions can specify conditions that cannot be specified by standard
constraints (and are quite expensive) CREATE TABLE PLANTS
(P# DECIMAL(5),PNAME CHAR(20),CITY CHAR (25),MARGIN REAL,CHECK (SELECT COUNT (*) FROM PLANTS > 0) );
This constraint does not check anything. The empty table PLANTS satisfies it, because
Each row of the empty table satisfies it
But the assertion
CREATE ASSERTION NICE_ASSERTIONCHECK (SELECT COUNT (*) FROM PLANTS > 0)
will work, as it is not a row-by-row condition
©Zvi M. Kedem
©Silberschatz, Korth and Sudarshan6.17Database System Concepts
ViewsViews We now proceed to the definition of the user level, that is to the
definition of views. Generally speaking, a view consists of “continuously current” relation that is derived by means of a SELECT statement from other relations.
For example, we could write
• CREATE VIEW GOODPLANTSAS SELECT *FROM PLANTSWHERE MARGIN > .0;
We could now execute a query against the view
• SELECT P#FROM GOODPLANTSWHERE CITY = 'CHICAGO';
This will give all P# for CHICAGO where margin is positive.
©Zvi M. Kedem
©Silberschatz, Korth and Sudarshan6.18Database System Concepts
Views Versus SnapshotsViews Versus Snapshots View is not a snapshot (which is also known as a materialized
view), which is static. View can be thought of as a procedure call. Therefore we should think of the following procedure for computing the answer to the last query:
The system computes the value of the relation GOODPLANTS.
The system executes the query against the relation GOODPLANTS.
In fact, the system may compute the answer differently. However, the result will be equivalent to the canonical procedure described above.
©Zvi M. Kedem
©Silberschatz, Korth and Sudarshan6.19Database System Concepts
Views Defined by QueriesViews Defined by Queries In general, almost any query definition could be used to define a
view, so we could have:
• CREATE VIEW CUSTOMERS_IN_THE_CITYAS SELECT CNAMEFROM PLANTS, CUSTOMERSWHERE (PLANTS.CITY = CUSTOMERS.CITYAND PLANTS.C# = CUSTOMERS.C#AND MARGIN >= .1);
Views can also be defined with CHECK option, which we will discuss later.
©Zvi M. Kedem
©Silberschatz, Korth and Sudarshan6.20Database System Concepts
Most Views Cannot Be UpdatedMost Views Cannot Be Updated Consider the view:
• CREATE VIEW MARGIN_ON_DATEAS SELECT MARGIN, DATEFROM PLANTS, ORDERS, CUSTOMERSWHERE (PLANTS.P# = CUSTOMERS.P#AND ORDERS.C# = CUSTOMERS.C#);
There is no meaning to the update
• INSERT INTO MARGIN_ON_DATEVALUES (0.9,1987.3.12);
• Why?
Because there is no well-defined way to this update in the base relations.
©Zvi M. Kedem
©Silberschatz, Korth and Sudarshan6.21Database System Concepts
Views That Are Updateable in SQLViews That Are Updateable in SQL The following are the major conditions that must be true for an
updatable view
• Is drawn from one table
• no joins, unions, differences, intersections
• If the underlying table is a view, it must be updateable
• The SELECTed columns are column references (each column at most once and without DISTINCT) and not values or aggregates
• No GROUP BY
©Zvi M. Kedem
©Silberschatz, Korth and Sudarshan6.22Database System Concepts
Some Views That Could Be UpdatedSome Views That Could Be Updated It may make sense to update views that SQL standard does not
allow to update
If we have two tables, in which SSN is a key• R(SSN,SALARY)
• S(SSN,ADDRESS)
The view
CREATE VIEW RSAS SELECT *FROM R, SWHERE R.SSN = S.SSN
can be meaningfully updated, but is not updateable following SQL standard
©Zvi M. Kedem
©Silberschatz, Korth and Sudarshan6.23Database System Concepts
PrivilegesPrivileges Privileges can be granted to user or PUBLIC for
• Operations
• References
on
• Base relations
• Views
©Zvi M. Kedem
©Silberschatz, Korth and Sudarshan6.24Database System Concepts
Types of PrivilegesTypes of Privileges Select
Insert
Update
Delete
References
©Zvi M. Kedem
©Silberschatz, Korth and Sudarshan6.25Database System Concepts
Examples of PrivilegesExamples of Privileges A typical instruction is:
• GRANT SELECT, INSERTON CUSTOMERSTO LI, BROWN;
Privileges can be restricted to columns:
• GRANT SELECTON CUSTOMERS.CITYTO LI, BROWN;
It is possible to grant all privileges by:
• GRANT ALLON CUSTOMERSTO LI, BROWN;
©Zvi M. Kedem
©Silberschatz, Korth and Sudarshan6.26Database System Concepts
Passing PrivilegesPassing Privileges It is possible to allow the users to pass the privileges to other
users by issuing:
• GRANT SELECT, INSERTON CUSTOMERSTO LI, BROWNWITH GRANT OPTION;
Then LI can issue
• GRANT SELECTON CUSTOMERS.CITYTO JONES;
©Zvi M. Kedem
©Silberschatz, Korth and Sudarshan6.27Database System Concepts
Privilege to ReferencePrivilege to Reference It is possible to allow a user to specify columns in a relation as
foreign keys referring to primary keys in a relation to which the user has no privileges:• GRANT ALL
ON ORDERSTO LI;
• GRANT REFERENCES (C#)ON CUSTOMERSTO LI
Needed to make sure that information can leak. In general, modifications on ORDERS could give information on CUSTOMERS, e.g., an attempt to insert a fake order into ORDERS for C# = 17 will tell a user where there is C#.=17 in CUSTOMERS, depending on whether the database accepts or rejects this insertion. So this privilige must be explicitly set
©Zvi M. Kedem
©Silberschatz, Korth and Sudarshan6.28Database System Concepts
Privileges on ViewsPrivileges on Views It is possible to grant privileges on views.
• Of course, the privilege must be meaningful. That is a privilege to update can be given only on a view that can be updated, etc.
©Zvi M. Kedem
©Silberschatz, Korth and Sudarshan6.29Database System Concepts
Revoking PrivilegesRevoking Privileges Privileges can be revoked
There are various way to specify what happens with privileges granted by somebody from whom a privilege is taken away
©Zvi M. Kedem
©Silberschatz, Korth and Sudarshan6.30Database System Concepts
Changing a TableChanging a Table ALTER TABLE table name {ADD [COLUMN] column definition} |
{ALTER [COLUMN] column name alter action} | {DROP [COLUMN] column name RESTRIC | CASCADE } | {ADD table constraint definition} | {DROP CONSTRAINT constraint name RESTRICT | CASCADE };
Alter action refers to default values
In the DROP COLUMN action RESTRICT and CASCADE deal with the case when the column is referenced by a view(s).• RESTRICT does not allow dropping if the column is referenced
• CASCADE will delete all such views
In the DROP CONSTRAINT action RESTRICT and CASCADE deal with the case of primary key constraint, when it is used as foreign key elsewhere• RESTRICT does not allow dropping if there is such foreign key reference
• CASCADE will delete all such references
©Zvi M. Kedem