Sei sulla pagina 1di 42

SQL (DQL, DDL, DML)

Prof. Sin-Min Lee Alina Vikutan CS 157A Fall 2005

Structured Query Language features

DQL (Data Query Language)

SELECT

Used to get data from the database and impose ordering upon it. DML (Data Manipulation Language)

DELETE, INSERT, UPDATE

Used to change database data. DDL (Data Definition Language)

DROP, TRUNCATE, CREATE, ALTER

Used to manipulate database structures and definitions. RIGHTS

REVOKE, GRANT
Used to give and take access rights to database objects.

Statement examples
SELECT [ DISTINCT ] * | LIST OF COLUMNS, FUNCTIONS, CONSTANTS FROM LIST OF TABLES OR VIEWS [ WHERE CONDITION(S) ] [ ORDER BY ORDERING COLUMN(S) [ ASC | DESC ] ] [ GROUP BY GROUPING COLUMN(S) ] [ HAVING CONDITION(S) ] DELETE FROM TABLE NAME [ WHERE CONDITION(S) ] INSERT INTO TABLE NAME [ (COLUMN LIST) ] VALUES (VALUE LIST) UPDATE TABLE NAME SET COLUMN NAME = VALUE [ WHERE CONDITION ]

Set Operations [union all]


The UNION ALL operator merges the result sets of two component queries. This operation returns rows retrieved by either of the component queries.

(select custNo,Name from Customer where ID=5) union all (select custNo,Name from Borrower)

This will retain duplicated tuples. Num of duplication is equals to num of duplicates that appears in both tables

Set Operations [union]


The UNION operator returns all distinct rows retrieved by two component queries. The UNION operation eliminates duplicates while merging rows retrieved by either of the component queries.

(select custNo,Name from Customer where ID=5) union (select custNo,Name from Borrower)

Differences between union & union all


To eliminate duplicate rows, a UNION operation needs to do some extra tasks as compared to the UNION ALL operation. These extra tasks include sorting and filtering the result set. If we observe carefully, we will notice that the result set of the UNION ALL operation is not sorted, whereas the result set of the UNION operation is sorted. These extra tasks introduce a performance overhead to the UNION operation. A query involving UNION will take extra time compared to the same query with UNION ALL, even if there are no duplicates to remove. Therefore, unless we have a valid need to retrieve only distinct rows, we should use UNION ALL instead of UNION for better performance

Set Operations [intersect]

Returns only those rows that are returned by each of two SELECT statements.

(select distinct cust_name from Customer) intersect (select distinct cust_name from Borrower)

INTERSECT returns only the rows retrieved by both component queries. Intersect all also allowed, and it will return duplicates

Set Operations [except]


Takes the result set of one SELECT statement, and removes those rows that are also returned by a second SELECT statement. Automatically eliminates duplicates (select cust_name from Customer) except (select cust_name from Borrower) If duplicates are needed, use except all

JOIN

A join is essentially a cartesian product followed by a predicate to filter the results. For example, given employee and department tables as follows
Table "employee" LastName DepartmentID Smith Jones Robinson Jasper Steinberg Rafferty 34 33 34 36 33 31 Sales Engineering Clerical Marketing Table "department" DepartmentName DepartmentID 31 33 34 35

Inner Join

REFERENTIAL INTEGRITY constraint - designates a column or combination of columns as a foreign key and establishes a relationship between that foreign key and a specified primary or unique key, called the referenced key. In this relationship, the table containing the foreign key is called the child table and the table containing the referenced key is called the parent table. Note these caveats: The child and parent tables must be on the same database. They cannot be on different nodes of a distributed database. The foreign key and the referenced key can be in the same table. In this case, the parent and child tables are the same. To satisfy a referential integrity constraint, each row of the child table must meet one of these conditions: The value of the row's foreign key must appear as a referenced key value in one of the parent table's rows. The row in the child table is said to depend on the referenced key in the parent table. The value of one of the columns that makes up the foreign key must be null. A referential integrity constraint is defined in the child table. A referential integrity constraint definition can include any of these keywords:

FOREIGN KEY - identifies the column or combination of columns in the child table that makes up of the foreign key. Only use this keyword when you define a foreign key with a table constraint clause. REFERENCES - identifies the parent table and the column or combination of columns that make up the referenced key. The referenced key columns must be of the same number and datatypes as the foreign key columns. ON DELETE CASCADE - allows deletion of referenced key values in the parent table that have dependent rows in the child table and causes ORACLE to automatically delete dependent rows from the child table to maintain referential integrity. If you omit this option, ORACLE forbids deletion of referenced key values in the parent table that have dependent rows in the child table. LastName DepartmentID DepartmentName SELECT * FROM employee JOIN Smith 34 Clerical department Jones 33 Engineering ON employee.DepartmentID = department.DepartmentID

Robinson Rafferty

34 31

Clerical Engineering Sales

Steinberg 33

Left outer join

A left outer join is very different from an inner join. Instead of limiting results to those in both tables, it limits results to those in the "left" table (A). This means that if the ON clause matches 0 records in B, a row in the result will still be returnedbut with NULL values for each column from B. For example, this allows us to find the employee's departments, but still show the employee even when their department is NULL or does not exist. The example above would have ignored employees in non-existent departments.
LastName DepartmentID DepartmentName

Smith 34 Clerical SELECT * Jones 33 Engineering FROM employee Robinson 34 Clerical Jasper 36 NULL LEFT OUTER JOIN Steinberg 33 Engineering department Rafferty 31 Sales ON employee.DepartmentID = department.DepartmentID

Right outer join

A right outer join is much like a left outer join, except that the tables are reversed. Every record from the right side, B or department, will be returned, and NULL values will be returned for those that have no matching record in A.
LastName DepartmentID DepartmentName Smith 34 33 34 33 31 35 Clerical Engineering Clerical Engineering Sales Marketing Jones Robinson Steinberg Rafferty NULL

SELECT * FROM employee RIGHT OUTER JOIN department

ON employee.DepartmentID = department.DepartmentID

Full outer join

Full outer joins are the combination of left and right outer joins. These joins will show records from both tables, and fill in NULLs for missing matches on either side. Some database systems do not offer this functionality, but it can be emulated through the use of left outer joins and unions. LastName DepartmentID DepartmentName
Smith Jones 34 33 Clerical Engineering

SELECT * Robinson 34 Clerical Jasper 36 NULL FROM employee Steinberg 33 Engineering FULL OUTER JOIN Rafferty 31 Sales NULL 35 Marketing department ON employee.DepartmentID = department.DepartmentID

null values

If a row lacks a value for a particular column, that column is said to be null, or to contain a null. Nulls can appear in columns of any datatype that are not restricted by NOT NULL or PRIMARY KEY integrity constraints. Any arithmetic expression containing a null always evaluates to null. All Scalar functions (except NVL and TRANSLATE) return null when given a null argument. The NVL function can be used to return a value when a null occurs. For example, the expression NVL(COMM,0) returns 0 if COMM is null or the value of COMM if it is not null. To test for nulls, only use the comparison operators IS NULL and IS NOT NULL. Most aggregate functions eliminate null values in calculations; one exception is the COUNT function. When using the COUNT function against a column containing null values, the null values will be eliminated from the calculation. However, if the COUNT function uses an asterisk, it will calculate all rows regardless of null values being present

Aggregate (Group) Functions


Aggregate functions are functions that take a collection of values as input and return a single value. Many group functions accept these options:
This option causes a group function to consider only distinct values of the argument expression. This option causes a group function to consider all values including all duplicates

DISTINCT ALL

All group functions except COUNT(*) ignore nulls. You can use the NVL in the argument to a group function to substitute a value for a null. If a query with a group function returns no rows or only rows with nulls for the argument to the group function, the group function returns null.

Group function (cont.)


AVG([DISTINCT|ALL] n) COUNT({* | [DISTINCT|ALL] expr} ) MAX([DISTINCT|ALL] expr) MIN([DISTINCT|ALL] expr) STDDEV([DISTINCT|ALL] x) SUM([DISTINCT|ALL] n)
Returns average value of n. Returns the number of rows in the query. If you specify expr, this function returns rows where expr is not null. You can count either all rows, or only distinct values of expr. If you specify the asterisk (*), this function returns all rows, including duplicates and nulls. Returns maximum value of expr. Returns minimum value of expr. Returns the standard deviation of x, a number. ORACLE calculates the standard deviation as the square root of the variance defined for the VARIANCE group function. Returns sum of values of n.

Returns variance of x, a number. For the variance formula VARIANCE([DISTINCT|ALL] x) see page 3-48 of ``ORACLE7 Server SQL Language Reference Manual''.

select bName, avg(balance) from group by bName having avg(balance) > 1200
select count(*) from customer select nName,count (distinct cName) from depositor, account where depositor.acctNo = account.acctNo group by bName

Predicates
Predicate
Description

BETWEEN ... AND Compares a value to a range formed by two values. IN LIKE JOIN
Determines whether a value exists in a list of values or a table. Compares, in part or in whole, one value with another. Joins two tables.

Predicate (Transaction SQL) is an expression that evaluates to TRUE, FALSE, or UNKNOWN. Predicates are used in the search condition of WHERE clauses and HAVING clauses, and the join conditions of FROM clauses.

Numeric functions
ABS(n) CEIL(n) COS(n) COSH(n) EXP(n) FLOOR(n) LN(n) LOG(m,n) MOD(m,n) POWER(m,n) ROUND(n[,m]) SIGN(n) SIN(n) SINH(n) SQRT(n) TAN(n) TANH(n) TRUNC(n[,m])
Returns the absolute value of n. Returns smallest integer greater than or equal to n. Returns the cosine of n (angle expressed in radians). Returns the hyperbolic cosine of n. Returns e raised to the nth power. Returns largest integer equal to or less than n. Returns the natural logarithm of n (for n > 0). Returns the logarithm, base m, of n. (m <> 0 or 1). Returns remainder of m divided by n. Returns m raised to the nth power (m**n). Returns n rounded to m places right of the decimal. Returns -1 if n<0; 0 if n=0; 1 if n>0. Returns the sine of n. Returns the hyperbolic sine of n. Returns square root of n. Returns the tangent of n. Returns the hyperbolic tangent of n. Returns n truncated to m decimal places; else m=0.

in keyword

In SQL, there are two uses of the Store_Information store_name Sales Date IN keyword, and this section Los Angeles $1500 Jan-05-1999 introduces the one that is related San Diego $250 Jan-07-1999 to the WHERE clause. When San Francisco $300 Jan-08-1999 Boston $700 Jan-08-1999 used in this context, we know exactly the value of the returned SELECT * values we want to see for at least FROM Store_Information one of the columns. The syntax WHERE store_name IN ('Los Angeles', 'San D for using the IN keyword is as store_name Sales Date follows: Los Angeles $1500 Jan-05-1999 San Diego $250 Jan-07-1999 SELECT "column_name" FROM "table_name" WHERE "column_name" IN ('value1', 'value2', ...)

between keyword

Whereas the IN keyword help people to limit the selection criteria to one or more discrete values, the BETWEEN keyword allows for selecting a range. The syntax for the BETWEEN clause is as follows: SELECT "column_name" FROM "table_name" WHERE "column_name" BETWEEN 'value1' AND 'value2' This will select all rows whose column has a value between 'value1' and 'value2'.

Table Store_Information store_name Sales Date Los Angeles San Diego Boston $1500 Jan-05-1999 $250 Jan-07-1999 $700 Jan-08-1999

San Francisco $300 Jan-08-1999

we key in, SELECT * FROM Store_Information WHERE Date BETWEEN 'Jan-06-1999' AND 'Jan-10-1999 Note that date may be stored in different formats in diff Result: store_name Sales Date San Diego Boston $250 Jan-07-1999 $700 Jan-08-1999 San Francisco $300 Jan-08-1999

like keyword

LIKE is another keyword that is used in the WHERE clause. Basically, LIKE allows you to do a search based on a pattern rather than specifying exactly what is desired (as in IN) or spell out a range (as in BETWEEN). The syntax for is as follows: SELECT "column_name" FROM "table_name" WHERE "column_name" LIKE {PATTERN} {PATTERN} often consists of wildcards. Here are some examples: 'A_Z': All string that starts with 'A', another character, and end with 'Z'. For example, 'ABZ' and 'A2Z' would both satisfy the condition, while 'AKKZ' would not (because there are two characters between A and Z instead of one). 'ABC%': All strings that start with 'ABC'. For example, 'ABCD' and 'ABCABC' would both satisfy the condition. '%XYZ': All strings that end with 'XYZ'. For example, 'WXYZ' and 'ZZXYZ' would both satisfy the condition. '%AN%': All string that contain the pattern 'AN' anywhere. For example, 'LOS ANGELES' and 'SAN FRANCISCO' would both satisfy the condition
SELECT * FROM Store_Information WHERE store_name LIKE '%AN%' store_name LOS ANGELES SAN DIEGO Sales Date $1500 Jan-05-1999 $250 Jan-07-1999

SAN FRANCISCO $300 Jan-08-1999

order by keyword

So far, we have seen how to get data out of a table using SELECT and WHERE commands. Often, however, we need to list the output in a particular order. This could be in ascending order, in descending order, or could be based on either numerical value or text value. In such cases, we can use the ORDER BY keyword to achieve our goal. The syntax for an ORDER BY statement is as follows: SELECT "column_name" FROM "table_name" [WHERE "condition"] ORDER BY "column_name" [ASC, DESC] The [] means that the WHERE statement is optional. However, if a WHERE clause exists, it comes before the ORDER BY clause. ASC means that the results will be shown in ascending order, and DESC means that the results will be shown in descending order. If neither is specified, the default is ASC. It is possible to order by more than one column. In this case, the ORDER BY clause above becomes ORDER BY "column_name1" [ASC, DESC], "column_name2" [ASC, DESC] Assuming that we choose ascending order for both columns, the output will be ordered in

SELECT store_name, Sales, Date FROM Store_Information ORDER BY Sales DESC store_name Los Angeles Boston San Diego Sales Date $1500 Jan-05-1999 $700 $250 Jan-08-1999 Jan-08-1999 Jan-07-1999

San Francisco $300

SELECT store_name, Sales, Date FROM Store_Information ORDER BY 2 DESC

group by keyword

Now we return to the aggregate functions. Remember we used the SUM keyword to calculate the total sales for all stores? What if we want to calculate the total sales for each store? Well, we need to do two things: First, we need to make sure we select the store name as well as total sales. Second, we need to make sure that all the sales figures are grouped by stores. The corresponding SQL syntax is,

SELECT store_name, SUM(Sales) FROM Store_Information GROUP BY store_name store_name SUM(Sales) Los Angeles $1800 San Diego $250 $700 Boston

SELECT "column_name1", SUM("column_name2") FROM "table_name" GROUP BY "column_name1

The GROUP BY keyword is used when we are selecting multiple columns from a table (or tables) and at least one arithematic operator appears in the SELECT statement. When that happens, we need to GROUP BY all the other selected columns, i.e., all columns except the one(s) operated on by the arithematic operator.

having keyword

Another thing people may want to do is to limit the output based on the corresponding sum (or any other aggregate functions). For example, we might want to see only the stores with sales over $1,500. Instead of using the WHERE clause in the SQL statement, though, we need to use the HAVING clause, which is reserved for aggregate functions. The HAVING clause is typically placed near the end of the SQL statement, and a SQL statement with the HAVING clause may or may not include the GROUP BY clause. The syntax for HAVING is, SELECT "column_name1", SUM("column_name2") FROM "table_name" GROUP BY "column_name1" HAVING (arithmetic function condition)

SELECT store_name, SUM(sales) FROM Store_Information GROUP BY store_name HAVING SUM(sales) > 1500 store_name SUM(Sales) Los Angeles $1800

Operators
Arithmetic Operators
unary arithmetic binary not and or + * / + NOT AND OR equality inequality greater less equal to any not equal to any all between exists like null

Comparison Operators
= !=, <> >, >= <, <= IN, =ANY NOT IN, !=ANY =ANY, !=ANY, >ANY, <="ANY,">=ANY =ALL, !=ALL, >ALL, <="ALL,">=ALL [NOT] BETWEEN x ANY y EXISTS x [NOT] LIKE y [ESCAPE z] IS [NOT] NULL

Logical Operators

Character Operators
concatenate ||

Note: % matches any string of zero or more characters except null. The character ``_'' matches any single character.

DDL (Data Definitions Language)

SQL commands are divided into a number of categories, of which the DDL commands are but one part:
Data

Definition Language commands Data Manipulation Language commands Transaction Control commands Session Control commands

Data Definition Language commands allow you to perform these tasks:


-

create, alter, and drop objects - grant and revoke privileges and roles

Data Definition examples


CREATE TABLE TABLE_NAME ( COLUMN_NAME DATA_TYPE [(SIZE)] COLUMN_CONSTRAINT, [, other column definitions,...] [, primary key constraint] ) ALTER TABLE TABLE_NAME ADD | DROP | MODIFY ( COLUMN_NAME DATA_TYPE [(SIZE)] COLUMN_CONSTRAINT, [, other column definitions,...] )

DROP TABLE TABLE_NAME


CREATE [UNIQUE] [ASC | DESC] INDEX INDEX_NAME ON TABLE_NAME ( COLUMN_LIST ) DROP INDEX INDEX_NAME ON TABLE_NAME CREATE VIEW VIEW_NAME AS QUERY_NAME CONSTRAINT CONSTRAINT_NAME {PRIMARY KEY | UNIQUE | NOT NULL | REFERENCES FOREIGN_TABLE [(FIELD_LIST)]}

Create Schema

This command allows the user to create multiple tables, multiple views and perform multiple grants in a single transaction.

schema - is the name of the schema. The schema name must be the same as your ORACLE username. CREATE TABLE - is a CREATE TABLE statement to be issued as part of this CREATE SCHEMA statement. CREATE VIEW - is a CREATE VIEW statement to be issued as part of this CREATE SCHEMA statement. GRANT - is a GRANT statement (Objects Privileges) to be issued as part of this CREATE SCHEMA statement

Create Schema (cont)


The order in which you list the CREATE TABLE, CREATE VIEW, and GRANT statements is unimportant: A CREATE VIEW statement can create a view that is based on a table that is created by a later CREATE TABLE statement. A CREATE TABLE statement can create a table with a foreign key that depends on the primary key of a table that is created by a later CREATE TABLE statement. A GRANT statement can grant privileges on a table or view that is created by a later CREATE TABLE or CREATE VIEW statement. The statements within a CREATE SCHEMA statement can also reference existing objects.

CREATE SCHEMA AUTHORIZATION blair CREATE TABLE sox (color VARCHAR2(10) PRIMARY KEY, quantity NUMBER) CREATE VIEW red_sox AS SELECT color, quantity FROM sox WHERE color = 'RED' GRANT select ON red_sox TO waites;

Create Table

This command allows the user to create a table, the basic structure to hold user data, by specifying the following information:
column

definitions integrity constraints the table's tablespace storage characteristics an optional cluster data from an arbitrary query

Create Table (cont)

Create Table (cont.)


schema - is the schema to contain the table. If you omit schema, ORACLE creates the table in your own schema. table - is the name of the table to be created. column - specifies the name of a column of the table. The number of columns in a table can range from 1 to 254. datatype - is the datatype of a column. Datatypes are defined previously in this manual. DEFAULT - specifies a value to be assigned to the column if a subsequent INSERT statement omits a value for the column. The datatype of the expression must match the datatype of the column. A DEFAULT expression cannot contain references to other columns. column_constraint - defines an integrity constraint as part of the column definition. table_constraint - defines an integrity constraint as part of the table definition. PCTFREE - specifies the percentage of space in each of the table's data blocks reserved for future updates to the table's rows. PCTFREE has the same function in the commands that create and alter clusters, indexes, snapshots, and snapshot logs. The combination of PCTFREE and PCTUSED determines whether inserted rows will go into existing data blocks or into new blocks. See discussion on PCTFREE, PCTUSED, INITRANS, MAXTRANS, in Chapter 2 of ``ORACLE Architecture and Terminology''. These parameters need not be set as the default values will be sufficient for your purpose. AS subquery - inserts the rows returned by the subquery into the table upon its creation. After creating a table, you can define additional columns and integrity constraints with the ADD clause of the ALTER TABLE command. You can change the definition of an existing column with the MODIFY clause of the ALTER TABLE command. To modify an integrity constraint, you must drop the constraint and redefine it.

Create View

This directive defines a view, a logical table based on one or more tables or views. To create a view in your own schema, you must have the CREATE VIEW system privilege. The owner of the schema containing the view must have the privileges necessary to either select, insert, update or delete rows from all the tables or views on which the view is based.

CREATE VIEW clerk(id_number,person,department, position) AS SELECT empno, ename, deptno, job FROM emp WHERE job = 'CLERK' WITH CHECK OPTION CONSTRAINT wco

Because of the CHECK OPTION, you cannot subsequently insert a new row into CLERK if the new employee is not a clerk.

Create View (cont.)


schema - is the schema to contain the table. If you omit schema, ORACLE creates the table in your own schema. OR REPLACE - recreates the view if it already exists. You can use this option to change the definition of an existing view without dropping, recreating, and regranting object privileges previously granted to it. FORCE - creates the view regardless of whether the view's base tables exist or the owner of the schema containing the view has privileges on them. Note that both of these conditions must be true before any SELECT, INSERT, UPDATE, or DELETE statements can be issued against the view. NOFORCE - creates the view only if the base tables exist and the owner of the schema containing the view has privileges on them. The default is NOFORCE. schema - is the schema to contain the view. If you omit schema, ORACLE creates the view in your own schema. view - is the name of the view. alias - specifies names for the expressions selected by the view's query. The number of aliases must match the number of expressions selected by the view. AS subquery - identifies columns and rows of the table(s) that the view is based on. A view's query can be any SELECT statement without the ORDER BY or FOR UPDATE clauses. WITH CHECK OPTION - specifies that inserts and updates performed through the view must result in rows that the view query can select. The CHECK OPTION cannot make this guarantee if there is a subquery in the query of this view or any view on which this view is based. CONSTRAINT - is the name assigned to the CHECK OPTION constraint. If you omit this identifier, ORACLE automatically assigns the constraint a name of the form ``SYS_Cn''.

GRANT

This command permits the user to grant privileges for a particular object to users and roles. The object must be in your own schema or you must have been granted the object privileges with the GRANT OPTION. object_priv - is an object privilege to be granted. You can substitute any of these values:

ALTER DELETE EXECUTE INDEX INSERT REFERENCES SELECT UPDATE

ALL PRIVILEGES - grants all the privileges for the object that has all privileges on the object with the GRANT OPTION. column - specifies a table or view column on which privileges are granted. You can only specify columns when granting the INSERT, REFERENCES, or UPDATE privilege. If you do not list columns, the grantee has the specified privilege on all columns in the table or view. ON - identifies the object on which the privileges are granted. TO - identifies users or roles to which the object privilege is granted. PUBLIC - grants object privileges to all users. WITH GRANT OPTION - allows the grantee to grant the object privileges to other users and roles. The grantee must be a user or PUBLIC, rather than a role.

GRANT SELECT, UPDATE ON golf_handcap TO PUBLIC

GRANT (example)

GRANT REFERENCES(empno), UPDATE(empno, sal, comm) ON scott.emp TO blake BLAKE can subsequently update values of EMPNO, SAL and COMM columns. BLAKE can also define referential integrity constraints that refer to the EMPNO column. However, since the GRANT statement lists only these columns, BLAKE cannot perform operations on any of the other columns of the EMP table. For example, BLAKE can create a table with a constraint:
CREATE TABLE dependent (dependno NUMBER, dependname VARCHAR2(10), employee NUMBER CONSTRAINT in_emp REFERENCES scott.emp(empno))

The constraint IN_EMP ensures that all dependents in the DEPENDENT table correspond to an employee in the EMP table in the schema SCOTT.

Create INDEX

This directive permits the user to create an index on one or more columns of a table or a cluster. An index is a database object that contains an entry for each value that appears in the indexed column(s) of the table or cluster and provides direct, fast access to rows. To create an index in your own schema, you must have either space quota on the tablespace to contain the index or UNLIMITED TABLESPACE system privilege. schema - is the schema to contain the index. If you omit schema, ORACLE creates the index in your own schema. index - is the name of the index to be created. table - is the name of the table for which the index is to be created. column - is the name of a column in the table. An index can have as many as 16 columns. A column of an index cannot be of datatype LONG or LONG RAW. ASC DESC - are allowed for DB2 syntax compatibility, although indexes are always created in ascending order. NOSORT - indicates to ORACLE that the rows are stored in the database in ascending order and therefore ORACLE does not have to sort the rows when creating the index. CREATE INDEX i_emp_ename ON emp (ename)

Constraint clause

The CONSTRAINT command is used to define an integrity constraint. CONSTRAINT clauses can appear in either CREATE TABLE or ALTER TABLE commands. CONSTRAINT - identifies the integrity constraint by the name constraint. ORACLE stores this name in the data dictionary along with the definition of the integrity constraint. NULL - specifies that a column can contain null values. NOT NULL - specifies that a column cannot contain null values. UNIQUE - designates a column or combination of columns as a unique key. PRIMARY KEY - designates a column or combination of columns as the table's primary key. FOREIGN KEY - designates a column or combination of columns as the foreign key in a referential integrity constraint. REFERENCES - identifies the primary or unique key that is referenced by a foreign key in a referential integrity constraint. ON DELETE CASCADE - specifies that ORACLE maintains referential integrity by automatically removing dependent foreign key values if you remove a referenced primary or unique key value. CHECK - specifies a condition that each row in the table must satisfy. USING INDEX - specifies parameters for the index ORACLE uses to enforce a UNIQUE or PRIMARY KEY constraint. Only use this clause when enabling UNIQUE and PRIMARY KEY constraints. EXCEPTIONS INTO - identifies a table into which ORACLE places information about rows that violate an enabled integrity constraint. This table must exist before you use this option. DISABLE - disables the integrity constraint. If an integrity constraint is disabled, ORACLE does not enforce it.

Constraints (cont)

Defining Integrity Constraints - To define an integrity constraint, include a CONSTRAINT clause in a CREATE TABLE or ALTER TABLE statement. The CONSTRAINT clause has two syntactic forms: table_constraint syntax - is part of the table definition. An integrity constraint defined with this syntax can impose rules on any columns in the table. This syntax can define any type of integrity constraint except a NOT NULL constraint. column_constraint syntax - is part of a column definition. In most cases, an integrity constraint defined with this syntax can only impose rules on the column in which it is defined. Column_constraint syntax that appears in a CREATE TABLE statement can define any type of integrity constraint. Column_constraint syntax that appears in an ALTER TABLE statement can only define or remove a NOT NULL constraint. The table_constraint syntax and the column_constraint syntax are simply different syntactic means of defining integrity constraints. There is no functional difference between an integrity constraint defined with table_constraint syntax and the same constraint defined with column_constraint syntax.

Constraints (cont.)

NOT NULL constraint - specifies that a column cannot contain nulls. To satisfy this constraint, every row in the table must contain a value for the column. The NULL keyword indicates that a column can contain nulls (this is the default). It does not actually define an integrity constraint. You can only specify NOT NULL or NULL with column\_constraint syntax in a CREATE TABLE or ALTER TABLE statement, not with table\_constraint syntax. ALTER TABLE emp MODIFY (sal NUMBER CONSTRAINT nn_sal NOT NULL); NN_SAL ensures that no employee in the table has a null salary. UNIQUE constraint - designates a column or combination of columns as a unique key. To satisfy a UNIQUE constraint, no two rows in the table can have the same value for the unique key. However, the unique key made up of a single column can contain nulls. A unique key column cannot be of datatype LONG or LONG RAW. You cannot designate the same column or combination of columns as both a unique key and a primary key. However, you can designate the same column or combination of columns as both a unique key and a foreign key. You can define a unique key on a single column with column_constraint syntax. The constraint below ensures that no two departments in the table have the same name. However, the constraint does allow departments without names. CREATE TABLE dept (deptno NUMBER, dname VARCHAR2(9) CONSTRAINT unq_dname UNIQUE, loc VARCHAR2(10) ) PRIMARY KEY constraint - designates a column or combination of columns as a table's primary key. To satisfy a PRIMARY KEY constraint, both of these conditions must be true:

no primary key value can appear in more than one row in the table. no column that is part of the primary key can contain null.

You can use the column_constraint syntax to define a primary key on a single column. The constraint below ensures that no two departments in the table have the same department number and that no department number is NULL. CREATE TABLE dept (deptno NUMBER CONSTRAINT pk_dept PRIMARY KEY, dname VARCHAR2(9), loc VARCHAR2(10)

REFERENTIAL INTEGRITY constraint - designates a column or combination of columns as a foreign key and establishes a relationship between that foreign key and a specified primary or unique key, called the referenced key. In this relationship, the table containing the foreign key is called the child table and the table containing the referenced key is called the parent table. Note these caveats:

Constraints (cont.)

The child and parent tables must be on the same database. They cannot be on different nodes of a distributed database. The foreign key and the referenced key can be in the same table. In this case, the parent and child tables are the same.

To satisfy a referential integrity constraint, each row of the child table must meet one of these conditions:

The value of the row's foreign key must appear as a referenced key value in one of the parent table's rows. The row in the child table is said to depend on the referenced key in the parent table.

The value of one of the columns that makes up the foreign key must be null. A referential integrity constraint is defined in the child table. A referential integrity constraint definition can include any of these keywords: FOREIGN KEY - identifies the column or combination of columns in the child table that makes up of the foreign key. Only use this keyword when you define a foreign key with a table constraint clause. REFERENCES - identifies the parent table and the column or combination of columns that make up the referenced key. The referenced key columns must be of the same number and datatypes as the foreign key columns. ON DELETE CASCADE - allows deletion of referenced key values in the parent table that have dependent rows in the child table and causes ORACLE to automatically delete dependent rows from the child table to maintain referential integrity. If you omit this option, ORACLE forbids deletion of referenced key values in the parent table that have dependent rows in the child table.

References

http://www.ilook.fsnet.co.uk/ora_sql/sqlmain.htm http://www.oreilly.com/catalog/mastorasql/chapter/ch07.html http://www.w3schools.com/sql/sql_functions.asp http://www.sql-tutorial.net/ http://www.mckoi.com/database/SQLSyntax.html http://ugweb.cs.ualberta.ca/~c391/manual/chapt6.html http://www.free-cgi.com/freecgi/reference/sqlref.php http://databases.about.com/od/sql/ http://www.akadia.com/services/dealing_with_null_values.html http://www.1keydata.com/sql/sql-syntax.html http://en.wikipedia.org/wiki/Join_(SQL)

Potrebbero piacerti anche