Documente Academic
Documente Profesional
Documente Cultură
Language DDL
Used to define, alter, drop database objects and privileges
CREATE
ALTER
DROP
RENAME
TRUNCATE
GRANT
REVOKE
COMMENT
Tables an Overview
Tables an Overview
Naming Conventions
Must begin with a letter
Can be 130 characters long
Must contain only AZ, az, 09, _, $,
and #
Must not duplicate the name of another
object owned by the same user
Must not be an Oracle Server reserved
word
Column level
columnName dataType [NOT NULL] [UNIQUE]
[DEFAULT defaultOption]
CONSTRAINT pk PRIMARY KEY (catalogNo)
CONSTRAINT pk1 PRIMARY KEY (catalogNo, actorNo)
CONSTRAINT fk_deptno REFERENCES scott.dept(deptno)
Table level
PRIMARY KEY (FLT#),
FOREIGN KEY (TO-AIRPORTCODE)
REFERENCES AIRPORT(AIRPORTCODE));
UNIQUE(FLT#, DATE, CUST#),
CHECK (ename = UPPER(ename))
ENABLE VALIDATE
CREATE TABLE dept (deptno NUMBER (2) PRIMARY KEY DISABLE, dname VARCHAR2(10), loc VARCHAR2(9) );
Parallel
The following statement creates a table serially.Subsequent DML and queries on the table will
also be serially executed.
CREATE TABLE emp_dept AS
SELECT * FROM scott.emp WHERE deptno = 10;
Using parallelism speeds up the creation of the table because Oracle uses parallel execution
servers to create the table. After the table is created, querying the table is also faster, because
the same degree of parallelism is used to access the table.
CREATE TABLE emp_dept PARALLEL AS
SELECT * FROM scott.emp WHERE deptno = 10;
The following statement creates a table using 10 parallel execution servers, 5 to scan
SCOTT.EMP and another 5 to populate EMP_DEPT:
CREATE TABLE emp_dept PARALLEL (5) AS
SELECT * FROM scott.emp WHERE deptno = 10;
Partitioned Table
CREATE TABLE stock_xactions (stock_symbol CHAR(5), stock_series CHAR(1),
num_shares NUMBER(10), price NUMBER(5,2), trade_date DATE)
STORAGE (INITIAL 100K NEXT 50K) LOGGING
PARTITION BY RANGE (trade_date)
(PARTITION sx1992 VALUES LESS THAN (TO_DATE('01-JAN-1993','DD-MONYYYY')) TABLESPACE ts0 NOLOGGING,
PARTITION sx1993 VALUES LESS THAN (TO_DATE('01-JAN-1994','DD-MONYYYY')) TABLESPACE ts1,
PARTITION sx1994 VALUES LESS THAN (TO_DATE('01-JAN-1995','DD-MONYYYY')) TABLESPACE ts2);
Storage
A sample table SALGRADE is created in the HUMAN_RESOURCE tablespace with a
small storage capacity and limited allocation potential. The primary key constraint on the
GRADE column and specifies that the index Oracle creates to enforce this constraint is
created in the USERS_A tablespace.
CREATE TABLE salgrade ( grade NUMBER CONSTRAINT pk_salgrade PRIMARY
KEY USING INDEX TABLESPACE users_a, losal NUMBER, hisal NUMBER )
TABLESPACE human_resource
STORAGE (INITIAL 6144 NEXT 6144 MINEXTENTS 1 MAXEXTENTS 5 );
Table Creation
create table UserInfo (
userid number(4) not null,
username varchar2(30) not null,
From_dt date default sysdate,
);
Confirm Table creation
DESCRIBE USERINFO;
Name
Null?
Type
----------------------------------- --------USERID
Not Null NUMBER(4)
USERNAME
Not Null VARCHAR2(30)
FROM_DT
DATE
Tables Overview
User Tables
Collection of tables created and maintained
by the user
Contain user information
Data Dictionary
Collection of tables created and maintained
by the Oracle server
Contain database information
User_tables Tables owned by a user
User_catalog view tables, views,
synonyms, sequences created by an user
Adding a Column
USERINFO
USERID USERNAME
HIREDATE
-----7698
7654
7499
7844
...
--------01-MAY-81
28-SEP-81
20-FEB-81
08-SEP-81
---------BLAKE
MARTIN
ALLEN
TURNER
add a
New column new
JOB
column
into
USERINFO
table
USERINFO
USERID
-----7698
7654
7499
7844
...
USERNAME
HIREDATE
---------- -------BLAKE
01-MAY-81
MARTIN
28-SEP-81
ALLEN
20-FEB-81
TURNER
08-SEP-81
JOB
Adding a Column
You use the ADD clause to add columns.
SQL> ALTER TABLE USERINFO
2 ADD
(job VARCHAR2(9));
Table altered.
HIREDATE
HIREDATE
----------------01-MAY-81
01-MAY-81
28-SEP-81
28-SEP-81
20-FEB-81
20-FEB-81
08-SEP-81
08-SEP-81
JOB
JOB
----------------- -------
Modifying a Column
You can change a columns datatype,
size, and default value.
ALTER TABLE userinfo
MODIFY
(username VARCHAR2(15));
Table altered.
Dropping a Table
All data and structure in the table is
deleted.
Any pending transactions are
committed.
All indexes are dropped.
You cannot roll back this statement.
SQL> DROP TABLE userinfo;
Table dropped.
Truncating a Table
The TRUNCATE TABLE statement:
Constraints
Two Types of constraints:
Column
Column constraints
constraints
not
not null
null
Table
Table constraint
constraint
unique,
unique, primary
primary key
key
Specification is
Constraint <constraint_name> primary key | unique | not null
Constraint Guidelines
Name a constraint or the Oracle Server
will generate a name by using the
SYS_Cn format.
Create a constraint:
emp(
NUMBER(4),
VARCHAR2(10) NOT NULL,
VARCHAR2(9),
NUMBER(4),
DATE,
NUMBER(7,2),
NUMBER(7,2),
NUMBER(7,2) NOT NULL);
dept(
NUMBER(2),
VARCHAR2(14),
VARCHAR2(13),
dept_dname_uk UNIQUE(dname));
dept(
NUMBER(2),
VARCHAR2(14),
VARCHAR2(13),
dept_dname_uk UNIQUE (dname),
dept_deptno_pk PRIMARY KEY(deptno));
References
References to
to CURRVAL,
CURRVAL, NEXTVAL,
NEXTVAL, LEVEL,
LEVEL, and
and
ROWNUM
ROWNUM pseudocolumns
pseudocolumns
Calls
Calls to
to SYSDATE,
SYSDATE, UID,
UID, USER,
USER, and
and USERENV
USERENV
functions
functions
Queries
Queries that
that refer
refer to
to other
other columns
columns in
in other
other
tables
tables
Adding a Constraint
Add
Add aa FOREIGN
FOREIGN KEY
KEY constraint
constraint to
to
the
the EMP
EMP table
table indicating
indicating that
that aa
manager
manager must
must already
already exist
exist as
as aa
valid
valid employee
employee in
in the
the EMP
EMP table.
table.
Dropping a Constraint
Remove the manager constraint from
the EMP table.
SQL>
emp
SQL> ALTER
ALTER TABLE
TABLE
emp
22 DROP
DROP CONSTRAINT
CONSTRAINT emp_mgr_fk;
emp_mgr_fk;
Table
Table altered.
altered.
Disabling Constraints
Execute the DISABLE clause of the
ALTER TABLE statement to deactivate
an integrity constraint.
Apply the CASCADE option to disable
dependent integrity constraints.
SQL>
SQL> ALTER
ALTER TABLE
TABLE
22 DISABLE
DISABLE CONSTRAINT
CONSTRAINT
Table
Table altered.
altered.
emp
emp
emp_empno_pk
emp_empno_pk CASCADE;
CASCADE;
Enabling Constraints
Activate an integrity constraint
currently disabled in the table
definition by using the ENABLE clause.
SQL>
SQL> ALTER
ALTER TABLE
TABLE
22 ENABLE
ENABLE CONSTRAINT
CONSTRAINT
Table
Table altered.
altered.
emp
emp
emp_empno_pk;
emp_empno_pk;
Viewing Constraints
Query the USER_CONSTRAINTS table to view
all constraint definitions and names.
SQL>
2
3
4
CONSTRAINT_NAME
CONSTRAINT_NAME
----------------------------------------------SYS_C00674
SYS_C00674
SYS_C00675
SYS_C00675
EMP_EMPNO_PK
EMP_EMPNO_PK
...
...
CC
-CC
CC
PP
SEARCH_CONDITION
SEARCH_CONDITION
------------------------------------------------EMPNO
EMPNO IS
IS NOT
NOT NULL
NULL
DEPTNO
DEPTNO IS
IS NOT
NOT NULL
NULL
View
View the
the columns
columns associated
associated with
with the
the
constraint
constraint names
names in
in the
the USER_CONS_COLUMNS
USER_CONS_COLUMNS
view.
view.
SQL> SELECT
2 FROM
3 WHERE
constraint_name, column_name
user_cons_columns
table_name = 'EMP';
CONSTRAINT_NAME
CONSTRAINT_NAME
------------------------------------------------EMP_DEPTNO_FK
EMP_DEPTNO_FK
EMP_EMPNO_PK
EMP_EMPNO_PK
EMP_MGR_FK
EMP_MGR_FK
SYS_C00674
SYS_C00674
SYS_C00675
SYS_C00675
COLUMN_NAME
COLUMN_NAME
------------------------------------------DEPTNO
DEPTNO
EMPNO
EMPNO
MGR
MGR
EMPNO
EMPNO
DEPTNO
DEPTNO
New row
DEPT
DEPTNO
-----10
20
30
40
DNAME
---------ACCOUNTING
RESEARCH
SALES
OPERATIONS
LOC
-------NEW YORK
DALLAS
CHICAGO
BOSTON
DNAME
---------ACCOUNTING
RESEARCH
SALES
OPERATIONS
LOC
-------NEW YORK
DALLAS
CHICAGO
BOSTON
50 DEVELOPMENT DETROIT
dept
(70, 'FINANCE', NULL);
emp
(2296,'AROMANO','SALESMAN',7782,
TO_DATE('FEB 3, 97', 'MON DD, YY'),
1300, NULL, 10);
Creating a Script
with Customized Prompts
ACCEPT
ACCEPT
INSERT INTO
VALUES
(&department_id, '&department_name',
'&location');
Copying Rows
from Another Table
Write your INSERT statement with a
subquery.
SQL> INSERT INTO managers(id, name, salary, hiredate)
2
SELECT empno, ename, sal, hiredate
3
FROM
emp
4
WHERE job = 'MANAGER';
3 rows created.
KING
BLAKE
CLARK
JONES
JOB
...
DEPTNO
PRESIDENT
MANAGER
MANAGER
MANAGER
10
30
10
20
update a row
in EMP table
EMP
EMPNO ENAME
7839
7698
7782
7566
...
KING
BLAKE
CLARK
JONES
JOB
PRESIDENT
MANAGER
MANAGER
MANAGER
...
DEPTNO
10
30
20
10
20
Updating with
Multiple-Column Subquery
Update employee 7698s job and department to
match that of employee 7499.
SQL>
SQL> UPDATE
UPDATE employee
employee
22 SET
deptno
SET
deptno == (SELECT
(SELECT
33
FROM
FROM
44
WHERE
WHERE
55 WHERE
job
== (SELECT
WHERE
job
(SELECT
66
FROM
FROM
77
WHERE
WHERE
22 rows
rows updated.
updated.
deptno
deptno
emp
emp
empno
empno ==
job
job
emp
emp
empno
empno ==
7788)
7788)
7788);
7788);
DNAME
---------ACCOUNTING
RESEARCH
SALES
OPERATIONS
LOC
-------NEW YORK
DALLAS
CHICAGO
BOSTON
DEVELOPMENT DETROIT
MIS
delete a row
from DEPT table
DEPT
DEPTNO
-----10
20
30
40
60
...
DNAME
---------ACCOUNTING
RESEARCH
SALES
OPERATIONS
MIS
LOC
-------NEW YORK
DALLAS
CHICAGO
BOSTON
employee
deptno =
(SELECT
FROM
WHERE
deptno
dept
dname ='SALES');
Advantages of COMMIT
and ROLLBACK Statements
Ensure data consistency
Preview data changes before making
changes permanent
Group logically related operations
Controlling Transactions
Transaction
INSERT
COMMIT
UPDATE
Savepoint A
INSERT
DELETE
Savepoint B
ROLLBACK to Savepoint B
ROLLBACK to Savepoint A
ROLLBACK
Committing Data
Make the changes.
SQL>
SQL> UPDATE
UPDATE emp
emp
22 SET
deptno
SET
deptno == 10
10
33 WHERE
empno
WHERE
empno == 7782;
7782;
11 row
row updated.
updated.
employee;
Implementation of Read
Consistency
Data
blocks
UPDATE emp
SET
sal = 2000
WHERE ename =
'SCOTT';
Rollback
segments
User A
SELECT *
FROM
emp;
User B
Read
consistent
image
changed
and
unchanged
data
before
change
old data
SQL>
SQL>
2
3
SET VERIFY ON
SELECT empno, ename, sal, deptno
FROM
emp
WHERE
empno = &employee_num;
WHERE condition
ORDER BY clause
Column expression
Table name
Entire SELECT statement
SELECT
FROM
WHERE
ORDER BY
ENAME
---------FORD
KING
SCOTT
JOB
SAL
--------- --------ANALYST
3000
PRESIDENT
5000
ANALYST
3000
SQL> SELECT
2 FROM
3 ORDER BY
== "sales"
"sales" (CHAR)
(CHAR)
[DISTINCT]
[DISTINCT] {*,
{*, column
column [alias],...}
[alias],...}
table;
table;
DNAME
-------------ACCOUNTING
RESEARCH
SALES
OPERATIONS
LOC
------------NEW YORK
DALLAS
CHICAGO
BOSTON
LOC
------------NEW YORK
DALLAS
CHICAGO
BOSTON
ENAME
JOB
COMM
---------- --------- --------KING
PRESIDENT
BLAKE
MANAGER
...
TURNER
SALESMAN
0
...
14 rows selected.
About PL/SQL
PL/SQL is an extension to SQL with
design features of programming
languages.
Data manipulation and query
statements of SQL are included within
procedural units of code.
Benefits of PL/SQL
Improved Performance
SQL
Application
Application
SQL
SQL
Other
Other DBMSs
DBMSs
SQL
Application
Application
SQL
IF...THEN
SQL
ELSE
SQL
END IF;
SQL
Oracle
Oracle with
with
PL/SQL
PL/SQL
Benefits of PL/SQL
Modularize program development
DECLARE
BEGIN
EXCEPTION
END;
Benefits of PL/SQL
It is portable.
You can declare identifiers.
Benefits of PL/SQL
You can program with procedural
language control structures.
It can handle errors.
Variables,
Variables,cursors,
cursors,user-defined
user-defined
exceptions
exceptions
BEGIN
BEGIN Mandatory
Mandatory
SQL
SQLstatements
statements
PL/SQL
PL/SQLstatements
statements
EXCEPTION
EXCEPTION Optional
Optional
Actions
Actionsto
toperform
performwhen
when
errors
errorsoccur
occur
END;
END; Mandatory
Mandatory
DECLARE
BEGIN
EXCEPTION
END;
DECLARE
BEGIN
EXCEPTION
END;
Block Types
Anonymous
Procedure Function
[DECLARE]
[DECLARE]
PROCEDURE
PROCEDURE name
name
IS
IS
BEGIN
BEGIN
--statements
--statements
BEGIN
BEGIN
--statements
--statements
[EXCEPTION]
[EXCEPTION]
[EXCEPTION]
[EXCEPTION]
FUNCTION
FUNCTION name
name
RETURN
RETURN datatype
datatype
IS
IS
BEGIN
BEGIN
--statements
--statements
RETURN
RETURN value;
value;
[EXCEPTION]
[EXCEPTION]
END;
END;
END;
END;
END;
END;
Use of Variables
Use variables for:
v_job
v_job
v_count
v_count
v_total_sal
v_total_sal
v_orderdate
v_orderdate
c_tax_rate
c_tax_rate
v_valid
v_valid
VARCHAR2(9);
VARCHAR2(9);
BINARY_INTEGER
BINARY_INTEGER :=
:= 0;
0;
NUMBER(9,2)
NUMBER(9,2) :=
:= 0;
0;
DATE
DATE :=
:= SYSDATE
SYSDATE ++ 7;
7;
CONSTANT
NUMBER(3,2)
CONSTANT NUMBER(3,2) :=
:= 8.25;
8.25;
BOOLEAN
BOOLEAN NOT
NOT NULL
NULL :=
:= TRUE;
TRUE;
Declaring Variables
with the %TYPE Attribute
Examples
...
...
v_ename
v_ename
v_balance
v_balance
v_min_balance
v_min_balance
...
...
emp.ename%TYPE;
emp.ename%TYPE;
NUMBER(7,2);
NUMBER(7,2);
v_balance%TYPE
v_balance%TYPE :=
:= 10;
10;