SQL_Ch3
-
Upload
anju-renjith -
Category
Documents
-
view
221 -
download
0
Transcript of SQL_Ch3
-
8/3/2019 SQL_Ch3
1/42
SQL
(DQL, DDL, DML)
Prof. Sin-Min Lee
Alina Vikutan
CS 157A Fall 2005
-
8/3/2019 SQL_Ch3
2/42
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, ALTERUsed to manipulate database structures and definitions.
RIGHTS
REVOKE, GRANT
Used to give and take access rights to database objects.
-
8/3/2019 SQL_Ch3
3/42
Statement examples
SELECT [ DISTINCT ] * | LIST OF COLUMNS, FUNCTIONS, CONSTANTSFROM 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 NAMESET COLUMN NAME = VALUE[ WHERE CONDITION ]
-
8/3/2019 SQL_Ch3
4/42
Set Operations [union all]
The UNION ALL operator merges the result sets of twocomponent queries.
This operation returns rows retrieved by either of the
component queries.
(selectcustNo,NamefromCustomerwhere ID=5)
union all
(selectcustNo,NamefromBorrower)
This will retain duplicated tuples. Num of duplication isequals to num of duplicates that appears in both tables
-
8/3/2019 SQL_Ch3
5/42
Set Operations [union]
The UNION operator returns all distinct rowsretrieved by two component queries.
The UNION operation eliminates duplicates while
merging rows retrieved by either of the componentqueries.
(selectcustNo,NamefromCustomerwhere
ID=5)union
(selectcustNo,NamefromBorrower)
-
8/3/2019 SQL_Ch3
6/42
Differences between union & unionall
To eliminate duplicate rows, a UNION operation needs to dosome extra tasks as compared to the UNION ALL operation.
These extra tasks include sorting and filtering the result set. Ifwe observe carefully, we will notice that the result set of theUNION ALL operation is not sorted, whereas the result set ofthe UNION operation is sorted.
These extra tasks introduce a performance overhead to the
UNION operation. A query involving UNION will take extratime compared to the same query with UNION ALL, even ifthere are no duplicates to remove. Therefore, unless we havea valid need to retrieve only distinct rows, we should useUNION ALL instead of UNION for better performance
-
8/3/2019 SQL_Ch3
7/42
Set Operations [intersect]
Returns only those rows that are returned by each oftwo SELECT statements.
(selectdistinct cust_namefromCustomer)
intersect
(selectdistinct cust_namefromBorrower)
INTERSECT returns only the rows retrieved by bothcomponent queries.
Intersect all also allowed, and it will return duplicates
-
8/3/2019 SQL_Ch3
8/42
Set Operations [except]
Takes the result set of one SELECTstatement, and removes those rows that arealso returned by a second SELECT
statement.
Automatically eliminates duplicates
(selectcust_namefromCustomer)
except
(selectcust_namefromBorrower)
If duplicates are needed, use except all
-
8/3/2019 SQL_Ch3
9/42
JOIN A join is essentially a cartesian product followed by a
predicate to filter the results. For example, givenemployee and department tables as follows
Table "employee"
LastNameDepartmentID
Smith 34
Jones 33
Robinson 34
Jasper 36
Steinberg 33
Rafferty 31
Table "department"
DepartmentNameDepartmentID
Sales 31
Engineering 33
Clerical 34
Marketing 35
http://en.wikipedia.org/wiki/Cartesian_producthttp://en.wikipedia.org/wiki/Cartesian_product -
8/3/2019 SQL_Ch3
10/42
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 childtable 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 keycolumns.
ON DELETE CASCADE -allows deletion of referenced key values in the parent table that have dependent rowsin the child table and causes ORACLE to automatically delete dependent rows from the child table to maintainreferential integrity. If you omit this option, ORACLE forbids deletion of referenced key values in the parent tablethat have dependent rows in the child table.
SELECT * FROM employeeJOINdepartmentON employee.DepartmentID = department.DepartmentID
LastName DepartmentID DepartmentName
Smith 34 Clerical
Jones 33 Engineering
Robinson 34 Clerical
Steinberg 33 Engineering
Rafferty 31 Sales
-
8/3/2019 SQL_Ch3
11/42
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 thosein the "left" table (A). This means that if the ON clausematches 0 records in B, a row in the result will still bereturnedbut 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 theirdepartment is NULL or does not exist. The example abovewould have ignored employees in non-existent departments.
SELECT *FROM employee
LEFT OUTER JOIN
department
ON employee.DepartmentID = department.DepartmentID
LastName DepartmentID DepartmentName
Smith 34 Clerical
Jones 33 Engineering
Robinson 34 Clerical
Jasper 36 NULL
Steinberg 33 Engineering
Rafferty 31 Sales
http://en.wikipedia.org/wiki/Null_%28SQL%29http://en.wikipedia.org/wiki/Null_%28SQL%29http://en.wikipedia.org/wiki/Null_%28SQL%29http://en.wikipedia.org/wiki/Null_%28SQL%29 -
8/3/2019 SQL_Ch3
12/42
Right outer join A right outer join is much like a left outer join, except
that the tables are reversed. Every record from theright side, B or department, will be returned, andNULL values will be returned for those that have no
matching record in A.
SELECT *
FROM employee
RIGHT OUTER JOINdepartment
ON employee.DepartmentID = department.DepartmentID
LastName DepartmentID DepartmentName
Smith 34 Clerical
Jones 33 Engineering
Robinson 34 Clerical
Steinberg 33 Engineering
Rafferty 31 SalesNULL 35 Marketing
-
8/3/2019 SQL_Ch3
13/42
Full outer join Full outer joins are the combination of left and right outer
joins. These joins will show records from both tables, and fillin NULLs for missing matches on either side.
Some database systems do not offer this functionality, but itcan be emulated through the use of left outer joins and
unions.
SELECT *
FROM employee
FULL OUTER JOIN
department
ON employee.DepartmentID = department.DepartmentID
LastName DepartmentID DepartmentName
Smith 34 Clerical
Jones 33 Engineering
Robinson 34 Clerical
Jasper 36 NULL
Steinberg 33 Engineering
Rafferty 31 Sales
NULL 35 Marketing
http://en.wikipedia.org/wiki/Null_%28SQL%29http://en.wikipedia.org/w/index.php?title=Union_%28SQL%29&action=edithttp://en.wikipedia.org/w/index.php?title=Union_%28SQL%29&action=edithttp://en.wikipedia.org/wiki/Null_%28SQL%29 -
8/3/2019 SQL_Ch3
14/42
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 arenot 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 anull 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 functionagainst a column containing null values, the null values will be eliminated
from the calculation. However, if the COUNT function uses an asterisk, itwill calculate all rows regardless of null values being present
-
8/3/2019 SQL_Ch3
15/42
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:
All group functions except COUNT(*) ignore nulls. You can
use the NVL in the argument to a group function to substitutea value for a null. If a query with a group function returns norows or only rows with nulls for the argument to the groupfunction, the group function returns null.
DISTINCT This option causes a group function to consider only distinct values of theargument expression.
ALLThis option causes a group function to consider all values including all
duplicates
-
8/3/2019 SQL_Ch3
16/42
Group function (cont.)AVG([DISTINCT|ALL] n) Returns average value of n.
COUNT({* | [DISTINCT|ALL]
expr} )
Returns the number of rows in the query. If you specify expr,this function returns rows where expr is not null. You cancount either all rows, or only distinct values of expr. If youspecify the asterisk (*), this function returns all rows,including duplicates and nulls.
MAX([DISTINCT|ALL] expr) Returns maximum value of expr.
MIN([DISTINCT|ALL] expr) Returns minimum value of expr.
STDDEV([DISTINCT|ALL] x)Returns the standard deviation of x, a number. ORACLEcalculates the standard deviation as the square root of thevariance defined for the VARIANCE group function.
SUM([DISTINCT|ALL] n) Returns sum of values of n.
VARIANCE([DISTINCT|ALL] x)Returns variance of x, a number. For the variance formulasee page 3-48 of ``ORACLE7 Server SQL LanguageReference Manual''.
select bName, avg(balance) fromgroup bybName having avg(balance) > 1200
select count(*)fromcustomer
select nName,count (distinct cName) from depositor, account
where depositor.acctNo = account.acctNogroup by bName
-
8/3/2019 SQL_Ch3
17/42
Predicates
Predicate DescriptionBETWEEN ... ANDCompares a value to a range formed by two values.IN Determines whether a value exists in a list of values or a table.LIKE Compares, in part or in whole, one value with another.JOIN Joins two tables.
Predicate (Transaction SQL) is an expression that evaluates to TRUE, FALSE,or UNKNOWN. Predicates are used in the search condition of WHEREclauses and HAVING clauses, and the join conditions of FROM clauses.
http://msdn2.microsoft.com/en-us/library/ms242864http://msdn2.microsoft.com/en-us/library/ms242864http://msdn2.microsoft.com/en-us/library/ms244920http://msdn2.microsoft.com/en-us/library/ms242864http://msdn2.microsoft.com/en-us/library/ms242466http://msdn2.microsoft.com/en-us/library/ms242466http://msdn2.microsoft.com/en-us/library/ms242864http://msdn2.microsoft.com/en-us/library/ms244920 -
8/3/2019 SQL_Ch3
18/42
Numeric functionsABS(n) Returns the absolute value of n.
CEIL(n) Returns smallest integer greater than or equal to n.
COS(n) Returns the cosine of n (angle expressed in radians).
COSH(n) Returns the hyperbolic cosine of n.
EXP(n) Returns e raised to the nth power.
FLOOR(n) Returns largest integer equal to or less than n.LN(n) Returns the natural logarithm of n (for n > 0).
LOG(m,n) Returns the logarithm, base m, of n. (m 0 or 1).
MOD(m,n) Returns remainder of m divided by n.
POWER(m,n) Returns m raised to the nth power (m**n).
ROUND(n[,m]) Returns n rounded to m places right of the decimal.
SIGN(n) Returns -1 if n0.SIN(n) Returns the sine of n.
SINH(n) Returns the hyperbolic sine of n.
SQRT(n) Returns square root of n.
TAN(n) Returns the tangent of n.
TANH(n) Returns the hyperbolic tangent of n.
TRUNC(n[,m]) Returns n truncated to m decimal places; else m=0.
-
8/3/2019 SQL_Ch3
19/42
in keyword In SQL, there are two uses of theIN keyword, and this section
introduces the one that is relatedto the WHERE clause. Whenused in this context, we know
exactly the value of the returnedvalues we want to see for at leastone of the columns. The syntaxfor using the IN keyword is asfollows:
SELECT "column_name"FROM "table_name"WHERE "column_name" IN('value1', 'value2', ...)
Store_Informationstore_name Sales DateLos Angeles $1500Jan-05-1999San Diego $250 Jan-07-1999San Francisco$300 Jan-08-1999Boston $700 Jan-08-1999SELECT *FROM Store_InformationWHERE store_name IN ('Los Angeles', 'San D
store_nameSales DateLos Angeles$1500Jan-05-1999San Diego $250 Jan-07-1999
-
8/3/2019 SQL_Ch3
20/42
between keyword Whereas the IN keyword help
people to limit the selectioncriteria to one or morediscrete values, theBETWEEN keyword allows forselecting a range. The syntaxfor the BETWEEN clause isas 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 DateLos Angeles $1500Jan-05-1999San Diego $250 Jan-07-1999San Francisco$300 Jan-08-1999Boston $700 Jan-08-1999we key in,SELECT *FROM Store_InformationWHERE Date BETWEEN 'Jan-06-1999' AND 'Jan-10-199Note that date may be stored in different formats in difResult:
store_name SalesDateSan Diego $250 Jan-07-1999San Francisco$300 Jan-08-1999Boston $700 Jan-08-1999
-
8/3/2019 SQL_Ch3
21/42
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 (becausethere 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 conditionSELECT *
FROM Store_Information
WHERE store_name LIKE '%AN%'
store_name Sales DateLOS ANGELES $1500Jan-05-1999SAN FRANCISCO$300 Jan-08-1999SAN DIEGO $250 Jan-07-1999
-
8/3/2019 SQL_Ch3
22/42
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 particularorder. This could be in ascending order, indescending order, or could be based on eithernumerical value or text value. In such cases, we canuse the ORDER BY keyword to achieve our goal.
The syntax for an ORDER BY statement is asfollows:
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 beforethe ORDER BY clause. ASC means that the results
will be shown in ascending order, and DESC meansthat the results will be shown in descending order. Ifneither is specified, the default is ASC.
It is possible to order by more than one column. Inthis 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 Sales DateLos Angeles $1500Jan-05-1999Boston $700 Jan-08-1999San Francisco$300 Jan-08-1999San Diego $250 Jan-07-1999SELECT store_name, Sales, Date
FROM Store_Information
ORDER BY 2 DESC
-
8/3/2019 SQL_Ch3
23/42
group by keyword Now we return to the aggregate functions.
Remember we used the SUM keyword to
calculate the total sales for all stores? Whatif we want to calculate the total sales foreachstore? Well, we need to do two things:First, we need to make sure we select thestore name as well as total sales. Second,we need to make sure that all the salesfigures are grouped by stores. Thecorresponding SQL syntax is,
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 arithematicoperator appears in the SELECT statement.When that happens, we need to GROUPBY all the other selected columns, i.e., allcolumns except the one(s) operated on bythe arithematic operator.
SELECT store_name, SUM(Sales)
FROM Store_Information
GROUP BY store_name
store_nameSUM(Sales)Los Angeles$1800San Diego $250Boston $700
-
8/3/2019 SQL_Ch3
24/42
having keyword Another thing people may want to do
is to limit the output based on thecorresponding sum (or any otheraggregate functions). For example,we might want to see only the storeswith sales over $1,500. Instead ofusing the WHERE clause in the SQLstatement, though, we need to usethe HAVING clause, which isreserved for aggregate functions. TheHAVING clause is typically placednear the end of the SQL statement,and a SQL statement with theHAVING clause may or may notinclude the GROUP BY clause. Thesyntax for HAVING is,
SELECT "column_name1",SUM("column_name2")FROM "table_name"GROUP BY "column_name1"HAVING (arithmetic functioncondition)
SELECT store_name, SUM(sales)FROM Store_Information
GROUP BY store_nameHAVING SUM(sales) > 1500
store_nameSUM(Sales)Los Angeles$1800
-
8/3/2019 SQL_Ch3
25/42
Operators
Arithmetic Operators Comparison Operators
unary + -
arithmetic * /
binary + -
Logical Operatorsnot NOT
and AND
or OR
Character Operators
concatenate ||
equality =
inequality !=,
greater >, >=
less ALL, =ALL
between [NOT] BETWEEN x ANY y
exists EXISTS
like x [NOT] LIKE y [ESCAPE z]
null IS [NOT] NULL
Note: % matches any string of zero or more characters except null.The character ``_'' matches any single character.
-
8/3/2019 SQL_Ch3
26/42
DDL (Data Definitions Language)
SQL commands are divided into a number ofcategories, of which the DDL commands arebut one part:Data Definition Language commands
Data Manipulation Language commands
Transaction Control commands
Session Control commands
Data Definition Language commands allowyou to perform these tasks:- create, alter, and drop objects
- grant and revoke privileges and roles
-
8/3/2019 SQL_Ch3
27/42
Data Definition examplesCREATE 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_NAMEON 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)]}
-
8/3/2019 SQL_Ch3
28/42
Create Schema This command allows the user to create multiple tables,
multiple views and perform multiple grants in a singletransaction.
schema - is the name of the schema. The schema namemust 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
-
8/3/2019 SQL_Ch3
29/42
Create Schema (cont)
The order in which you list the CREATE TABLE, CREATE VIEW, andGRANT 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 CREATETABLE statement.
A GRANT statement can grant privileges on a table or view that is createdby a later CREATE TABLE or CREATE VIEW statement.
The statements within a CREATE SCHEMA statement can also referenceexisting objects.
CREATE SCHEMA AUTHORIZATION blairCREATE TABLE sox (color VARCHAR2(10) PRIMARY KEY,
quantity NUMBER)
CREATE VIEWred_sox
AS SELECT color, quantity FROMsoxWHERE color = 'RED'
GRANT selectON red_sox TO waites;
-
8/3/2019 SQL_Ch3
30/42
Create Table
This command allows the user to create a table,the basic structure to hold user data, byspecifying the following information: column definitions
integrity constraints
the table's tablespace
storage characteristics
an optional cluster
data from an arbitrary query
-
8/3/2019 SQL_Ch3
31/42
Create Table (cont)
-
8/3/2019 SQL_Ch3
32/42
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 thedatatype 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 commandsthat create and alter clusters, indexes, snapshots, and snapshot logs. The combination ofPCTFREE 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 parametersneed 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 existingcolumn with the MODIFY clause of the ALTER TABLE command. To modify an integrityconstraint, you must drop the constraint and redefine it.
-
8/3/2019 SQL_Ch3
33/42
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 VIEWclerk(id_number,person,department, position)AS SELECT empno, ename, deptno, job
FROMemp
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 employeeis not a clerk.
-
8/3/2019 SQL_Ch3
34/42
Create View (cont.)
schema - is the schema to contain the table. If you omit schema, ORACLE creates the table in your ownschema.
OR REPLACE - recreates the view if it already exists. You can use this option to change the definition ofan 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 schemacontaining the view has privileges on them. Note that both of these conditions must be true before anySELECT, 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 theview 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 ownschema.
view - is the name of the view.
alias - specifies names for the expressions selected by the view's query. The number of aliases mustmatch 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 canbe 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 inrows that the view query can select. The CHECK OPTION cannot make this guarantee if there is asubquery 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''.
-
8/3/2019 SQL_Ch3
35/42
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 withthe 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 objectwith the GRANT OPTION.
column - specifies a table or view column on which privileges are granted. You can only specifycolumns 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.
-
8/3/2019 SQL_Ch3
36/42
GRANT (example)GRANT SELECT, UPDATE ON
golf_handcapTO PUBLIC
GRANT REFERENCES(empno), UPDATE(empno, sal, comm)ON scott.empTO blake
BLAKE can subsequently update values of EMPNO, SAL and COMMcolumns. BLAKE can also define referential integrity constraints that refer tothe EMPNO column. However, since the GRANT statement lists only thesecolumns, BLAKE cannot perform operations on any of the other columns ofthe 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.
-
8/3/2019 SQL_Ch3
37/42
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 entryfor each value that appears in the indexed column(s) of the table or clusterand provides direct, fast access to rows. To create an index in your ownschema, you must have either space quota on the tablespace to containthe index or UNLIMITED TABLESPACE system privilege.
schema - is the schema to contain the index. If you omit schema, ORACLEcreates 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 orLONG RAW.
ASC DESC - are allowed for DB2 syntax compatibility, although indexesare 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 rowswhen creating the index.
CREATE INDEX i_emp_ename ON emp (ename)
-
8/3/2019 SQL_Ch3
38/42
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 primaryor 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 PRIMARYKEY constraints.
EXCEPTIONS INTO - identifies a table into which ORACLE places information about rowsthat 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.
-
8/3/2019 SQL_Ch3
39/42
Constraints (cont) Defining Integrity Constraints -To define an integrity constraint,
include a CONSTRAINT clause in a CREATE TABLE or ALTERTABLE statement. The CONSTRAINT clause has two syntactic forms:
table_constraint syntax -is part of the table definition. An integrityconstraint defined with this syntax can impose rules on any columns inthe table. This syntax can define any type of integrity constraint excepta NOT NULL constraint.
column_constraint syntax -is part of a column definition. In mostcases, an integrity constraint defined with this syntax can only imposerules on the column in which it is defined. Column_constraint syntaxthat appears in a CREATE TABLE statement can define any type ofintegrity constraint. Column_constraint syntax that appears in anALTER TABLE statement can only define or remove a NOT NULLconstraint.
The table_constraint syntax and the column_constraint syntax aresimply different syntactic means of defining integrity constraints. Thereis no functional difference between an integrity constraint defined withtable_constraint syntax and the same constraint defined withcolumn_constraint syntax.
C i ( )
-
8/3/2019 SQL_Ch3
40/42
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 orNULL with column\_constraint syntax in a CREATE TABLE or ALTER TABLE statement, not withtable\_constraint syntax.
ALTER TABLE empMODIFY (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 keymade up of a single column can contain nulls. A unique key column cannot be of datatype LONG or LONGRAW. You cannot designate the same column or combination of columns as both a unique key and a primarykey. 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 departmentswithout 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. Tosatisfy 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 belowensures that no two departments in the table have the same department number and that no departmentnumber is NULL.CREATE TABLE dept
(deptno NUMBER CONSTRAINT pk_dept PRIMARY KEY,dname VARCHAR2(9), loc VARCHAR2(10)
-
8/3/2019 SQL_Ch3
41/42
Constraints (cont.) 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 orunique 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. Notethese 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 theseconditions: 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 tableconstraint 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 anddatatypes as the foreign key columns.
ON DELETE CASCADE -allows deletion of referenced key values in the parent table that havedependent rows in the child table and causes ORACLE to automatically delete dependent rowsfrom 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 childtable.
-
8/3/2019 SQL_Ch3
42/42
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)
http://www.ilook.fsnet.co.uk/ora_sql/sqlmain.htmhttp://www.oreilly.com/catalog/mastorasql/chapter/ch07.htmlhttp://www.w3schools.com/sql/sql_functions.asphttp://www.sql-tutorial.net/http://www.mckoi.com/database/SQLSyntax.htmlhttp://ugweb.cs.ualberta.ca/~c391/manual/chapt6.htmlhttp://www.free-cgi.com/freecgi/reference/sqlref.phphttp://databases.about.com/od/sql/http://www.akadia.com/services/dealing_with_null_values.htmlhttp://www.1keydata.com/sql/sql-syntax.htmlhttp://en.wikipedia.org/wiki/Join_(SQL)http://en.wikipedia.org/wiki/Join_(SQL)http://www.1keydata.com/sql/sql-syntax.htmlhttp://www.1keydata.com/sql/sql-syntax.htmlhttp://www.1keydata.com/sql/sql-syntax.htmlhttp://www.akadia.com/services/dealing_with_null_values.htmlhttp://databases.about.com/od/sql/http://www.free-cgi.com/freecgi/reference/sqlref.phphttp://www.free-cgi.com/freecgi/reference/sqlref.phphttp://www.free-cgi.com/freecgi/reference/sqlref.phphttp://ugweb.cs.ualberta.ca/~c391/manual/chapt6.htmlhttp://www.mckoi.com/database/SQLSyntax.htmlhttp://www.sql-tutorial.net/http://www.sql-tutorial.net/http://www.sql-tutorial.net/http://www.w3schools.com/sql/sql_functions.asphttp://www.oreilly.com/catalog/mastorasql/chapter/ch07.htmlhttp://www.ilook.fsnet.co.uk/ora_sql/sqlmain.htm