35
Data definition language

Data definition language

Embed Size (px)

DESCRIPTION

Data definition language. CREATE TABLE to create a new table in the database; ALTER TABLE CREATE VIEW to create a new view from a base table. CREATE TABLE. Data Types:. The most widely used data types are: CHARACTER(L): (CHAR) defines a string of fixed length L. - PowerPoint PPT Presentation

Citation preview

Data definition language

• CREATE TABLE to create a new table in the database;

• ALTER TABLE

• CREATE VIEW to create a new view from a base table

CREATE TABLE

Data Types:The most widely used data types are:• CHARACTER(L): (CHAR) defines a string of fixed length L. • CHARACTER VARYING(L): (VARCHAR) defines a string of varying length

L. If you enter a string with fewer characters than this length, only those characters entered are stored, thereby using less space.

• DECIMAL(precision, [scale]) or NUMERIC(precision, [scale]): defines a number with an exact representation. precision specifies the number of significant digits and scale specifies the number of digits after the decimal point.For example, DECIMAL(4) can represent numbers between –9999 and +9999; DECIMAL(4, 2) can represent numbers between –99.99 and +99.99.

• INTEGER and SMALLINT: define numbers where the representation of fractions is not required. Typically SMALLINT would be used to store numbers with a maximum absolute value of 32 767.

• DATE: stores date values in Julian date format as a combination of YEAR (4 digits), MONTH (2 digits), and DAY (2 digits).

• whether the column cannot accept nulls (NOT NULL),

• whether each value within the column will be unique; that is, the column is a candidate key (UNIQUE),

• a default value for the column; this is a value that would be used if the value of the column is not specified (DEFAULT).

SQL data types.

FOREIGN KEY clause and referential integrity

• The definition of foreign keys with the FOREIGN KEY clause in the CREATE TABLE statement.

• Referential integrity by rejecting any INSERT or UPDATE operation that attempts to create a foreign key value in a child table without a matching candidate key value in the parent table.

• The action SQL takes for any UPDATE or DELETE operation that attempts to update or delete a candidate key value in the parent table that has some matching rows in the child table is dependent on the referential action specified using the ON UPDATE and ON DELETE subclauses of the FOREIGN KEY clause:

• CASCADE: Update/delete the row from the parent table and automatically update/delete the matching rows in the child table.

• SET NULL: Update/delete the row from the parent table and set the foreign key value(s) in the child table to NULL.

• SET DEFAULT: Update/delete the row from the parent table and set each component of the foreign key in the child table to the specified default value.

• NO ACTION: Reject the update/delete operation from the parent table. This is the default setting if the ON UPDATE/ON DELETE rule is omitted.

ALTER TABLE

• Change default column settings.

• Set a new identity column or alter an existing identity column.

• Add one or more new columns.

• Define, add, and drop constraints for a column or the entire table, or both

Change an existing column:

Add one or more columns where the [, ... ] means that one or more new columns can be added in the same ALTER TABLE statement:

Drop a constraint from an existing column without dropping the column itself:

Change a data type, default values, NULL settings, and again-identity columns.

Drop an existing column:

the Types of Constraints• NOT NULL Specifies that a column can’t contain a NULL value. If NOT

NULL is omitted for a column, then the default setting is NULL. • UNIQUE Restricts a column value to be unique across all rows in a table.

UNIQUE does allow NULL values and will default to NULL. However, only one row can have a NULL value .

• PRIMARY KEY A primary key is a special type of unique constraint in that it can be linked to one or more foreign key columns, in one or more tables, and even a foreign key in the same table.

• REFERENCES This is a foreign key constraint, which helps to enforce referential integrity. A foreign key can also be a composite column (table-level) constraint, when its referenced primary key is a composite key.

• CHECK Specifies a condition that values in a column must satisfy. Check constraints can even be applied to enforce expressions, which span multiple columns.

• DEFAULT Specifies a default value for a column when the column is not specified in an INSERT statement.

Check

• For example, suppose that department numbers are restricted to integer numbers between 1 and 20; CREATE TABLE DEPARTMENT( DNAME VARCHAR(15) Not Null DNUMBER INT Not Null MGR_ID CHAR(9) Not Null MGRSTARTDATE DATE, PRIMARY KEY(DNUMBER) , FOREIGN KEY(MGR_ID) REFERENCES EMPLOYEE(ID) ) ;

• change the attribute declaration of DNUMBER in the DEPARTMENT tableDNUMBER INT NOT NULL CHECK (DNUMBER > 0 AND DNUMBER < 21);

• The CHECK clause can also be used in conjunction with the CREATE DOMAIN statement.CREATE DOMAIN D_NUM AS INTEGER

CHECK(D_NUM > 0 AND D_NUM < 21);

• The created domain D_NUM can be used as the attribute type for all attributes that refer to department numbers.

Removing Constraints

SPECIFYING GENERALCONSTRAINTS AS ASSERTIONS• Users can specify general constraints via

declarative assertions, using the CREATE ASSERTION statement of the DDL.

• Each assertion is given a constraint name and is specified via a condition similar to the WHERE clause of an SQL query.

• For example, to specify the constraint that "the salary of an employee must not be greater than the salary of the manager of the department that the employee works for" in SQL:

CREATE ASSERTION SALARY_CONSTRAINTCHECK ( NOT EXISTS

(SELECT *FROM EMPLOYEE E, EMPLOYEE M, DEPARTMENT

DWHERE E.SALARY>M.SALARY ANDE.DNO=:D.DNUMBER ANDD.MGRSSN=:M.SSN) );

the query selects all employees whose salaries are greater than the salary of the manager of their department. If the result of the query is not empty, the assertion is violated.

• The constraint name SALARY_CONSTRAINT is followed by the keyword CHECK, which is followed by a condition in parentheses that must hold true on every database state for the assertion to be satisfied.

• The constraint name can be used later to refer to the constraint or to modify or drop it.

• Any WHERE clause condition can be used, but many constraints can be specified using the EXISTS and NOT EXISTS style of SQL conditions.

• The constraint is violated whenever some tuples in the database cause the condition of an ASSERTION statement to evaluate to FALSE.

• The constraint is satisfied by a database state if no combination of tuples in that database state violates the constraint.

• The basic technique for writing such assertions is to specify a query that selects any tuples that violate the desired condition.

• By including this query inside a NOT EXISTS clause, the assertion will specify that the result of this query must be empty. Thus, the assertion is violated if the result of the query is not empty.

VIEW

• What Is a View?

A view stores a query and does not store data. • The reasons to create view:

– To focus on specific data, perhaps for security reasons.

– To simplify manipulation of data for some users, such as power users.

– To provide backward compatibility.– To export data.

CREATE VIEW• The (simplified) format of the CREATE VIEW statement is:

• A view is defined by specifying an SQL SELECT statement (known as the defining query).

• A name may optionally be assigned to each column in the view. • If a list of column names is specified, it must have the same number

of items as the number of columns produced by the subselect. • If the list of column names is omitted, each column in the view takes

the name of the corresponding column in the subselect statement.• The list of column names must be specified if there is any ambiguity

in the name for a column.

• For example, : create a view of staff at branch B001 that excludes salary information as follows:

SQL queries on a view

DROP VIEW command

TRIGGERS

• To enforce domain integrity, use a CHECK constraint.

• To enforce entity integrity, use UNIQUE or PRIMARY KEY constraints.

• To enforce referential integrity, use FOREIGN KEY constraints.

Triggers can respond to the following situations that constraints can’t handle:

• Unlike CHECK constraints, a trigger can reference data in another table.For example, compare inserted data to data in another table and perform an action, depending on the results of that comparison.

• Error handling. If you require custom error messages, use a trigger.

• Triggers can evaluate values in a table before and after modification and respond, depending on that comparison.

Using AFTER Triggers

• An AFTER trigger executes after a triggering action. • A triggering action is the Transact-SQL statement, or

statements, that produces the event to which the trigger responds.

• An AFTER trigger executes after the following:– Constraint processing– Declarative referential actions– Creation of the Inserted and Deleted tables– The triggering action

• An AFTER trigger never executes if there’s a constraint violation.

The basic syntax to create an AFTER trigger is as follows:

an INSERT Trigger

• Create an INSERT trigger: to fire whenever a new row is inserted into the trigger table.

• When you add a new row to a table on which you’ve defined an INSERT trigger, SQL Server not only inserts the row into the trigger table, but also into a logical table named inserted.

• The inserted table contains a copy of the row (or rows) you’ve just inserted into the trigger table; so, the inserted and trigger tables have these rows in common.

a DELETE Trigger

• use a DELETE trigger to perform specific functions whenever a row is deleted from the trigger table.

an UPDATE Trigger

• You can use an UPDATE trigger to perform specific actions whenever you update the data in a table.

CREATE TRIGGER no_update_cust_numON customerFOR UPDATEASIF UPDATE (cust_num)BEGINRAISERROR ('You cannot change a customer's account number.',

10, 1)ROLLBACK TRANSACTIONEND