Upload
truongthuthuy47
View
215
Download
0
Embed Size (px)
Citation preview
7/27/2019 A03_DDL
1/55
CS 522 - Database
Administration
DDLDr. Dongming Liang
http://class.svuca.edu/~d.liang/([email protected])
Silicon Valley University
7/27/2019 A03_DDL
2/55
2
Agenda
Database objectsCreate table
Constraints
Alter/drop table
Other schema objects
7/27/2019 A03_DDL
3/55
3
Database ObjectsObjects Description
Table Basic unit of storage; composed ofrows
View Logically represents subsets of data
from one or more table
Sequence Generates numeric values
Index Improves the performance of somequeries
Synonym Gives alternative name to an object
7/27/2019 A03_DDL
4/55
4
DDL
DDL
(Data Definition Language)
CREATE
ALTER
DROP
TRUNCATE
7/27/2019 A03_DDL
5/55
5
CREATE Table Statement
You must have CREATE Table privilege
A storage area
CREATE TABLE [schema.]table(column datatype[DEFAULT expr] [, ]);
You specify
Table name Column name, column data type, and column size
7/27/2019 A03_DDL
6/55
6
Reference Another Users Table
Tables belonging to other users are notin the users schema
You should use the owners name as a
prefix to those tablesFor example, UserA wants to access the
EMPLOYEES table the belongs to UserB
SELECT *
FROM UserB.employees
7/27/2019 A03_DDL
7/55
7
Default Option
When you define a table, you canspecify a default value for a columnduring an insert
hire_date DATE DEFAULT sysdate, Literal values, expressions, or SQL
functions are legal values
Another columns name or apseudocolumn are illegal values
7/27/2019 A03_DDL
8/55
8
Example: Create Table
CREATE TABLE dept(deptno NUMBER(2),
dname VARCHAR2(14),
loc VARCHAR2(13),
create_date DATE
DEFAULT SYSDATE);
7/27/2019 A03_DDL
9/55
9
Confirm Table Creation
DESCRIBE deptDESCRIBE dept
Name Null Type
---------------- ---- ------
DEPTNO NUMBER
DNAME VARCHAR2(14)LOC VARCHAR2(13)
CREATE_DATE DATE
7/27/2019 A03_DDL
10/55
10
Data TypesData Type Description
VARCHAR2(size) Variable-length character dataCHAR(size) Fixed-length character data
NUMBER(p, s) Variable-length numeric data
DATE Data and time values
CLOB Character data (up to 4GB)
BFILE Binary data stored in an externalfile
ROWID The unique address of a row in itstable
7/27/2019 A03_DDL
11/55
11
DatetimeData Types
Data Type Description
TIMESTAMP Date with fractional seconds
INTERVAL YEARTO MONTH
Stored as an interval of years andmonths
INTERVAL DAYTO SECOND
Stored as an interval of days,
hours, minutes, and seconds
7/27/2019 A03_DDL
12/55
12
Constraints
7/27/2019 A03_DDL
13/55
13
Including Constraints
Use constraints to prevent invalid dataentry into tables
Constraints enforce rules at the tablelevel
Constraints prevent the deletion of
table if there are dependencies
7/27/2019 A03_DDL
14/55
14
Constraint Types
NOT NULL the column cannot contain a nullvalue
UNIQUE column value must be unique
PRIMARY KEY uniquely identify each row inthe table
FOREIGN KEY establish and enforce areferential integrity
CHECK specify a condition that must betrue
7/27/2019 A03_DDL
15/55
15
Constraint Guidelines
You can name a constraint, or the Oracleserver generates a name by using theSYS_Cnformat
Create a constraint at either of the followingtimesAt the same time as the creation of the table
After the creation of the table
Define a constraint at the column or tablelevel
7/27/2019 A03_DDL
16/55
16
Define Constraint
CREATE TABLE [schema.]table(column datatype[DEFAULT expr]
[column_constraint],
[table_constraint][, ]);
7/27/2019 A03_DDL
17/55
17
Example: Define Constraint
CREATE TABLE employees(employee_id NUMBER(6)
CONSTRAINT emp_emp_id_pk
PRIMARY KEY,
first_name VARCHAR2(20),
);
Column level syntax
7/27/2019 A03_DDL
18/55
18
Example: Define Constraint
CREATE TABLE employees
(employee_idNUMBER(6),
first_name VARCHAR2(20),
job_id VARCHAR2(10) NOT NULL,
CONSTRAINT emp_emp_id_pk
PRIMARY KEY(EMPLOYEE_ID));
Here emp_emp_id_pk is in table level syntax
7/27/2019 A03_DDL
19/55
19
FOREIGN KEY
Aforeign keymeans that
values inone table must also
appear in another table.
7/27/2019 A03_DDL
20/55
20
Define Foreign Key
CREATE TABLE employees(employee_idNUMBER(6),
first_name VARCHAR2(20),
dept_id NUMBER(4),
CONSTRAINT emp_dept_id_fk
FOREIGN KEY(dept_id)
REFERENCES departments(department_id));
7/27/2019 A03_DDL
21/55
21
Foreign Key Constraint: Keywords
FOREIGN KEY: define the column in childtable
REFERENCES: identify the parent table andcolumn
ON DELETE CASCADE: delete the dependentrows in the child table when a row in theparent table is deleted
ON DELETE SET NULL: convert dependentforeign key values to null
7/27/2019 A03_DDL
22/55
22
CHECK Constraint
Defines a condition that each row mustsatisfy
,
salary NUMBER(4)
CONSTRAINT emp_salary_min
CHECK(salary > 0),
7/27/2019 A03_DDL
23/55
23
CHECK Constraint
The following expressions are notallowed
References to CURRVAL, NEXTVAL, LEVEL,
and ROWNUM pseudocolumns Calls to SYSDATE, UID, USER, and
USERENV functions
Queries that refer to other values in otherrows
7/27/2019 A03_DDL
24/55
24
Violating Constraints
UPDATE employeesSET department_id = 55
WHERE department_id = 110;
Department 55 does not exist theparent table, DEPARTMENTS, and soyou receive a parent key not foundviolation ORA-02291 error.
7/27/2019 A03_DDL
25/55
25
Create a Table Using a Subquery
CREATE TABLE dept80AS
SELECT employee_id, last_name,
salary*12 ANNSAL, hire_date
FROM employees
WHERE department_id = 80;
Be sure to provide a column alias, such asANNSAL, when selecting an expression
7/27/2019 A03_DDL
26/55
26
Alter Table
7/27/2019 A03_DDL
27/55
27
Alter Table Statement
Use theAlter Table statement to:Add a new column
Modify an existing column definition
Define a default value for the new column
Drop a column
Rename a column
Change table to read only status
7/27/2019 A03_DDL
28/55
28
Read Only Tables
Use the Alter Table statement to put a tableinto read-only mode
Prevent DDL or DML changes during tablemaintenance
ALTER TABLE employees READ ONLY;
Change it back into read/write mode after themaintenance
ALTER TABLE employees READ WRITE;
7/27/2019 A03_DDL
29/55
29
Drop a Table
Moves a table to the recycle binRemoves the table and all its data
entirely if the PURGE clause in specified
Invalidates dependent objects andremoves object privileges on the table
DROP TABLE dept80;
7/27/2019 A03_DDL
30/55
30
Other Schema Objects
7/27/2019 A03_DDL
31/55
31
Database ObjectsObjects Description
Table Basic unit of storage; composed ofrows
View Logically represents subsets of data
from one or more tableSequence Generates numeric values
Index Improves the performance of some
queries
Synonym Gives alternative name to an object
7/27/2019 A03_DDL
32/55
32
View
You can present logical subsets orcombination of data by creating viewsof tables
A view is a logical table based on atable or another view
A view contains no data of its own, but
is like window through which data fromtables can be viewed or changed
7/27/2019 A03_DDL
33/55
33
Base Table of View
The tableson which aview is
based arecalledbase
tables
7/27/2019 A03_DDL
34/55
34
Advantages of Views
To restrict data accessTo provide data independence
To make complex queries easy
To present different views of the samedata
7/27/2019 A03_DDL
35/55
35
Simple Views and Complex Views
Feature Simple Views Complex ViewsNumber oftables
One One or more
Containfunctions No Yes
Contain groupsof data
No Yes
DML operationsthrough a view
Yes Not always
7/27/2019 A03_DDL
36/55
36
Create a View
CREATE VIEW empvu30AS
SELECT employee_id, last_name, salary
FROM employeesWHERE department_id = 30;
A view is stored as a SELECT statementin the data dictionary
7/27/2019 A03_DDL
37/55
7/27/2019 A03_DDL
38/55
38
Retrieve Data from a View
You can retrieve data from a view as youwould from any table
SELECT *
FROM salvu50
You can display either the contents of theentire view or just specific rows and columns
7/27/2019 A03_DDL
39/55
39
Create Complex View
Create a complex view that contains groupfunctions to display values from two tables:
CREATE OR REPLACE VIEW dept_sum_vu
(name, minsal, maxsal, avgsal)
AS SELECT d.department_name, MIN(e.salary),MAX(e.salary), AVG(e.salary)
FROM employees e, departments dWHERE e.department_id = d.department_id
GROUP BY d.department_name
7/27/2019 A03_DDL
40/55
40
Remove a View
You can remove a view without losingdata because a view is based onunderlying tables in the database
DROP VIEW salvu50;
7/27/2019 A03_DDL
41/55
41
Database ObjectsObjects Description
Table Basic unit of storage; composed ofrows
View Logically represents subsets of data
from one or more tableSequence Generates numeric values
Index Improves the performance of some
queries
Synonym Gives alternative name to an object
7/27/2019 A03_DDL
42/55
42
Sequences
Can automatically generate uniquenumbers
Is a sharable object
Can be used to create a primary key
7/27/2019 A03_DDL
43/55
43
Create a Sequence
Create a sequence name DEPT_DEPTID_SEQto be used for the primary key of theDEPARTMENTS table
CREATE SEQUENCE dept_deptid_seqINCREMENT BY 10START WITH 120MAXVALUE 9999
NOCACHENOCYCLE
7/27/2019 A03_DDL
44/55
44
NEXTVAL and CURRVAL
NEXTVAL returns the next available sequencevalue
INSERT INTO departments(department_id,
department_name, location_id)
VALUES (dept_deptid_seq.NEXTVAL,
Support, 2500);
CURRVAL obtains the current sequence valueSELECT dept_deptid_seq.CURRVAL
FROM dual;
7/27/2019 A03_DDL
45/55
45
Database ObjectsObjects Description
Table Basic unit of storage; composed ofrows
View Logically represents subsets of data
from one or more tableSequence Generates numeric values
Index Improves the performance of some
queries
Synonym Gives alternative name to an object
7/27/2019 A03_DDL
46/55
7/27/2019 A03_DDL
47/55
47
How Are Indexes Created?
Automatically: a unique index is createdautomatically when you define aPRIMARY KEY or UNIQUE constraint in
a table definitionManually: Users can create nonunique
indexes on columns to speed up access
to the rows
7/27/2019 A03_DDL
48/55
48
Create an Index
Improve the speed of query access tothe LAST_NAME column in theEMPLOYEES table
CREATE IDNEX emp_last_name_idx
ON employees (last_name);
7/27/2019 A03_DDL
49/55
49
Index Creation Guidelines
Create an index when:A column contains a wide range of values
One or more columns are frequently used
together in a WHERE clause or a joincondition
The table is large and most queries are
expected to retrieve less than 2% to 4% ofthe rows in the table
7/27/2019 A03_DDL
50/55
50
Remove an Index
Remove an index from the datadictionary by using the DROP INDEXcommand
For example, remove theemp_last_name_idxindex:
DROP INDEX emp_last_name_idx;
7/27/2019 A03_DDL
51/55
51
Database ObjectsObjects Description
Table Basic unit of storage; composed ofrows
View Logically represents subsets of data
from one or more tableSequence Generates numeric values
Index Improves the performance of some
queriesSynonym Gives alternative name to an object
7/27/2019 A03_DDL
52/55
52
Synonym for an Object
Simplify access to objects by creating asynonym (another name for an object)
With synonyms you can
Create an easier reference to a table that isowned by another user
Shorten lengthy object names
7/27/2019 A03_DDL
53/55
53
Create and Remove Synonyms
Create a shortened name for theDEPT_SUM_VU view
CREATE SYNONYM d_sum
FOR dept_sum_vu;
Drop a synonym
DROP SYNONYM d_sum;
7/27/2019 A03_DDL
54/55
54
Summary
Categorize the main DB objects
Data types, table creation, and constraints
Create, use, and remove views
Automatically generate sequence number byusing sequence
Create indexes to improve speed of queryretrieval
Use synonyms to provide alternative namesfor objects
7/27/2019 A03_DDL
55/55
55
Oracle Database Architecture
Next Week