SlideShare a Scribd company logo
DDL and DCL
Naming Rules
• Table names and column names:
– Must begin with a letter
– Must be 1–30 characters long
– Must contain only A–Z, a–z, 0–9, _, $, and #
– Must not duplicate the name of another object
owned by the same user
– Must not be an Oracle server reserved word
Data Types
Data Type Description
VARCHAR2(size) Variable-length character data
CHAR(size) Fixed-length character data
NUMBER(p,s) Variable-length numeric data
DATE Date and time values
Creating Tables
– Create the table.
– Confirm table creation.
DESCRIBE dept
CREATE TABLE dept
(deptno NUMBER(2),
dname VARCHAR2(14),
loc VARCHAR2(13),
create_date DATE DEFAULT SYSDATE);
Table created.
Constraints
– Create a constraint at either of the following times:
• At the same time as the table is created
• After the table has been created
– Define a constraint at the column or table level.
– View a constraint in the data dictionary.
• NOT NULL
• UNIQUE
• PRIMARY KEY
• FOREIGN KEY
Constraints...
– Column-level constraint:
– Table-level constraint:
column [CONSTRAINT constraint_name] constraint_type,
column,...
[CONSTRAINT constraint_name] constraint_type
(column, ...),
Defining Constraints
– Column-level constraint:
– Table-level constraint:
CREATE TABLE employees(
employee_id NUMBER(6)
CONSTRAINT emp_emp_id_pk PRIMARY KEY,
first_name VARCHAR2(20),
...);
CREATE TABLE employees(
employee_id NUMBER(6),
first_name VARCHAR2(20),
...
job_id VARCHAR2(10) NOT NULL,
CONSTRAINT emp_emp_id_pk
PRIMARY KEY (EMPLOYEE_ID));
1
2
The NOT NULL Constraint
• The NOT NULL constraint ensures that the column
has a value and the value is not a null value
• A space or a numeric zero is not a null value
• At the column level ONLY, the constraint is defined
by:
Name VARCHAR2(15) CONSTRAINT faculty_name_nn NOT NULL,
UNIQUE Constraint
• Defined at either the table level or the column
level:CREATE TABLE employees(
employee_id NUMBER(6),
last_name VARCHAR2(25) NOT NULL,
email VARCHAR2(25),
salary NUMBER(8,2),
commission_pct NUMBER(2,2),
hire_date DATE NOT NULL,
...
CONSTRAINT emp_email_uk UNIQUE(email));
FOREIGN KEY Constraint
DEPARTMENTS
EMPLOYEES
FOREIGN
KEY
INSERT INTO
Not allowed
(9 does not
exist)
Allowed
PRIMARY
KEY
…
…
FOREIGN KEY Constraint
• Defined at table level only:
CREATE TABLE employees(
employee_id NUMBER(6),
last_name VARCHAR2(25) NOT NULL,
email VARCHAR2(25),
salary NUMBER(8,2),
commission_pct NUMBER(2,2),
hire_date DATE NOT NULL,
...
department_id NUMBER(4),
CONSTRAINT emp_dept_fk FOREIGN KEY (department_id)
REFERENCES departments(department_id),
CONSTRAINT emp_email_uk UNIQUE(email));
FOREIGN KEY Constraint:
Keywords
– FOREIGN KEY: Defines the column in the child
table at the table-constraint level
– REFERENCES: Identifies the table and column in
the parent table
CHECK Constraint
– Defines a condition that each row must
satisfy
..., salary NUMBER(2)
CONSTRAINT emp_salary_min
CHECK (salary > 0),...
CREATE TABLE: Example
CREATE TABLE employees
( employee_id NUMBER(6)
CONSTRAINT emp_employee_id PRIMARY KEY
, first_name VARCHAR2(20)
, last_name VARCHAR2(25)
CONSTRAINT emp_last_name_nn NOT NULL
, email VARCHAR2(25)
CONSTRAINT emp_email_nn NOT NULL
CONSTRAINT emp_email_uk UNIQUE
, phone_number VARCHAR2(20)
, hire_date DATE
CONSTRAINT emp_hire_date_nn NOT NULL
, job_id VARCHAR2(10)
CONSTRAINT emp_job_nn NOT NULL
, salary NUMBER(8,2)
CONSTRAINT emp_salary_ck CHECK (salary>0)
, commission_pct NUMBER(2,2)
, manager_id NUMBER(6)
, department_id NUMBER(4)
CONSTRAINT emp_dept_fk REFERENCES
departments (department_id));
UPDATE employees
*
ERROR at line 1:
ORA-02291: integrity constraint (HR.EMP_DEPT_FK)
violated - parent key not found
UPDATE employees
SET department_id = 55
WHERE department_id = 110;
Violating Constraints
Violating Constraints
• You cannot delete a row that contains a
primary key that is used as a foreign key in
another table.DELETE FROM departments
WHERE department_id = 60;
DELETE FROM departments
*
ERROR at line 1:
ORA-02292: integrity constraint (HR.EMP_DEPT_FK)
violated - child record found
Creating a Table
by Using a Subquery
– Create a table and insert rows by combining the
CREATE TABLE statement and the AS
subquery option.
– Match the number of specified columns to the
number of subquery columns.
– Define columns with column names and
default values.
CREATE TABLE table
[(column, column...)]
AS subquery;
CREATE TABLE dept80
AS
SELECT employee_id, last_name,
salary*12 ANNSAL,
hire_date
FROM employees
WHERE department_id = 80;
Table created.
Creating a Table
by Using a Subquery
DESCRIBE dept80
ALTER TABLE Statement
• Use the ALTER TABLE statement to:
– Add a new column
– Modify an existing column
– Define a default value for the new column
– Drop a column
– Drop Constraint
Adding a New Column to an
Existing Table
• The general syntax to add a column to an
existing table is
ALTER TABLE tablename
ADD columnname datatype;
SQL> ALTER TABLE student
2 ADD SocialSecurity CHAR(9);
Table altered.
SQL>
Modifying an Existing Column
• The general syntax to modify an existing column is
ALTER TABLE tablename
MODIFY columnname newdatatype;
where newdatatype is the new data type or the new size for the
column.
SQL> ALTER TABLE student
2 MODIFY SocialSecurity VARCHAR2(11);
Table altered.
SQL>
Adding a Constraint
• To add a constraint using ALTER TABLE, the syntax for table
level constraint is used. The general syntax of ALTER TABLE is
ALTER TABLE tablename
ADD [CONSTRAINT constraint_name] constraint_type
(column, …),
SQL> ALTER TABLE COURSE
2 ADD CONSTRAINT COURSE_PREREQ_FK FOREIGN KEY (PREREQ)
3 REFERENCES COURSE(COURSEID);
Table altered.
SQL>
Dropping a Column and constrain
The general syntax is
• ALTER TABLE tablename DROP COLUMN columnname;
• ALTER TABLE tablename DROP CONSTRAINT constraintname;
Renaming a Table
– Additional DDL statements include the RENAME
statement, which is used to rename a table, view,
sequence.
– Syntax
– RENAME old_name TO new_name;
– In the syntax:
– old_name is the old name of the
table, view, sequence.
– new_name is the new name of the
table, view, sequence.
Views
• Provide security
• Create view viewName as select * from
tablename
• Create view.
• View can be insert/updated/deleted to reflect
changes in base table only if all not null
columns included in table and also view is
created by a single table.
More SQL Data Definition
Sequences
• Often we want to assign
each row a unique number
– These are useful as primary
keys
• In most versions of SQL we
can use autoincrementing
fields to do this
– Usually the first entry is
assigned 1, the next 2, and so
on, but Oracle lets you
change this
More SQL Data Definition
Sequences
• In Oracle we use a Sequence
– A sequence is a source of numbers
– We can declare several sequences, giving each a
name, a start point, and a step size
– We can then generate unique numbers by asking
for the next element from a sequence
More SQL Data Definition
Sequences in Oracle
• To declare a sequence:
CREATE SEQUENCE <name>
[START WITH <value>]
[INCREMENT BY <value>]
– If no START WITH or INCREMENT BY values
are given they default to 1
• To get the next value from a sequence
<sequence name>.nextVal
More SQL Data Definition
Sequence Example
• Creating a sequence
CREATE SEQUENCE mySeq START WITH 1
• Using a sequence
SELECT mySeq.nextVal FROM DUAL;
INSERT INTO Student
(stuID, stuName, stuAddress)
VALUES
(mySeq.nextVal, 'Steve Mills',
'13 Elm Street')
More SQL Data Definition
Oracle Data Dictionary
• To find the details of a table use
DESCRIBE <table name>
• Example:
SQL> DESCRIBE Student;
Name Null? Type
------------ -------- ----------
STUID NOT NULL NUMBER(38)
STUNAME NOT NULL VARCHAR2(50)
STUADDRESS VARCHAR2(50)
STUYEAR NUMBER(38)
Create synonym
• create synonyms so that other schemas can
access the new database objects (ie: tables)
without having to prefix the object names
• SELECT * FROM new_schema.suppliers;
• If you then created a synonym for
the suppliers table as follows:
• CREATE PUBLIC SYNONYM suppliers FOR
new_schema.suppliers;You could run the SELECT
statement as follows:
• SELECT * FROM suppliers;th the schema name.
33
DCL: Data Control Language
• Controlling Access to database objects such as tables
and views
• Example : Granting “Mary” the access to Table “student” (for inserting,
updating and deleting)
– GRANT INSERT, UPDATE, DELETE ON Emp TO Mary
– GRANT <privileges> ON <object name>
TO <grantee> [ <comma> <grantee> ... ]
[ WITH GRANT OPTION ]
– WITH GRANT OPTION: allows the grantee to further grant privileges
– Can be limited to a column of a table, Ex: GRANT UPDATE(name) ON emp TO
Mary
– To revoke privileges : REVOKE
• Grant all privilleges to user
• GRANT <privileges> ON <object name>
TO <grantee> [ <comma> <grantee> ... ]
[ WITH GRANT OPTION ]
• Create table u7.table8(id int);
• Grant Privileges on Functions/Procedures
• When dealing with functions and procedures, you
can grant users the ability to EXECUTE these
functions and procedures.
• Syntax
• GRANT EXECUTE ON object TO user;
• Create tablespace ts1 datafile ‘E:Oracle_lectsts1.dbf’ size
100M’
• ………………………………………………………….
• CREATE USER jward
• IDENTIFIED BY aZ7bC2
• DEFAULT TABLESPACE data_ts;
• GRANT connect TO jward;
• ........................................
• grant connect to craig;
• alter user craig quota unlimited on CRAIG_DATA;
• grant create table to craig;
• .................................
• create role rolename;
• grant connect to rolename;
• grant rollname to username;
Granting privileges
• GRANT
– Grants a privilege to a user
– Can grant privilege only if you have been granted
that privilege (or if you are the administrator)
grant <privilege> to <user>;
Grant create table to user_name with admin option
Examples of granting roles
• grant create table to john;
• grant all on CD_MASTER to tom;
• grant SELECT ON CD_MASTER.CD_NAME to
john;
• grant select, update on CD_DB to tom;
• grant references(CD_NO) on CD_DB to john;
Revoking roles
• REVOKE
– Revokes a privilege from a user
– Can revoke privilege only if you have been granted
that privilege (or if you are the administrator)
revoke <privilege> from <user>;
Dropping a Table
– All data and structure in the table are deleted.
– All indexes are dropped.
– All constraints are dropped.
– You cannot roll back the DROP TABLE
statement.
DROP TABLE dept80;
Table dropped.
Dropping a Table
• The general syntax is
DROP TABLE tablename [CASCADE CONSTRAINTS];
• For example,
DROP TABLE sample;
• Oracle displays a “Table dropped” message when a table is
successfully dropped.
• If you add optional CASCADE CONSTRAINTS clause, it removes
foreign key references to the table also.
More SQL Data Definition
Oracle Data Dictionary
• SELECT DISTINCT OBJECT_NAME FROM
USER_OBJECTS
• To find out what tables and sequences you
have defined use
SELECT tablespace_name,table_name
FROM user_tables
– The user_tables table is maintained by Oracle
– It has lots of columns, so don’t use
SELECT * FROM user_tables
Oracle Data Dictionary
• Select username from dba_users;
• select privilege
from dba_sys_privs
where grantee = 'RESOURCE':
•
PRIVILEGE
--------------------------------------
CREATE TYPE
CREATE TABLE
CREATE CLUSTER
CREATE TRIGGER
CREATE OPERATOR
CREATE SEQUENCE
CREATE INDEXTYPE
CREATE PROCEDURE
• select * from session_privs;
• PRIVILEGE ----------------------------------------
CREATE SESSION UNLIMITED TABLESPACE
CREATE TABLE
View Description
DBA_USERS Describes all users of the database
ALL_USERS Lists users visible to the current user, but does
not describe them
USER_USERS Describes only the current user

More Related Content

PPTX
DML using oracle
Farhan Aslam
 
PPTX
SQL Commands
Sachidananda M H
 
PDF
SQL Overview
Stewart Rogers
 
DOC
A must Sql notes for beginners
Ram Sagar Mourya
 
PPTX
Sql commands
Pooja Dixit
 
PPT
Introduction to-sql
BG Java EE Course
 
PPT
Introduction to structured query language (sql)
Sabana Maharjan
 
PPT
Sql server T-sql basics ppt-3
Vibrant Technologies & Computers
 
DML using oracle
Farhan Aslam
 
SQL Commands
Sachidananda M H
 
SQL Overview
Stewart Rogers
 
A must Sql notes for beginners
Ram Sagar Mourya
 
Sql commands
Pooja Dixit
 
Introduction to-sql
BG Java EE Course
 
Introduction to structured query language (sql)
Sabana Maharjan
 
Sql server T-sql basics ppt-3
Vibrant Technologies & Computers
 

What's hot (19)

PDF
Chapter 4 Structured Query Language
Eddyzulham Mahluzydde
 
PPTX
Introduction to SQL
Ehsan Hamzei
 
PPTX
Chapter 1 introduction to sql server
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
SQL Server Learning Drive
TechandMate
 
PPTX
SQL
Shyam Khant
 
PPTX
Introduction to SQL (for Chicago Booth MBA technology club)
Jennifer Berk
 
PPTX
Sql Basics And Advanced
rainynovember12
 
PPTX
Introduction to SQL
Amin Choroomi
 
PDF
Sql notes, sql server,sql queries,introduction of SQL, Beginner in SQL
Prashant Kumar
 
PPTX
SQL for interview
Aditya Kumar Tripathy
 
PPT
MySql slides (ppt)
webhostingguy
 
PDF
Sql tutorial
Rumman Ansari
 
PPTX
Basic SQL and History
SomeshwarMoholkar
 
PPTX
SQL Basics
Hammad Rasheed
 
PPT
SQL : introduction
Shakila Mahjabin
 
PPTX
SQL - DML and DDL Commands
Shrija Madhu
 
PPTX
introdution to SQL and SQL functions
farwa waqar
 
ODP
Ms sql-server
Md.Mojibul Hoque
 
PPTX
SQL commands
GirdharRatne
 
Chapter 4 Structured Query Language
Eddyzulham Mahluzydde
 
Introduction to SQL
Ehsan Hamzei
 
Chapter 1 introduction to sql server
baabtra.com - No. 1 supplier of quality freshers
 
SQL Server Learning Drive
TechandMate
 
Introduction to SQL (for Chicago Booth MBA technology club)
Jennifer Berk
 
Sql Basics And Advanced
rainynovember12
 
Introduction to SQL
Amin Choroomi
 
Sql notes, sql server,sql queries,introduction of SQL, Beginner in SQL
Prashant Kumar
 
SQL for interview
Aditya Kumar Tripathy
 
MySql slides (ppt)
webhostingguy
 
Sql tutorial
Rumman Ansari
 
Basic SQL and History
SomeshwarMoholkar
 
SQL Basics
Hammad Rasheed
 
SQL : introduction
Shakila Mahjabin
 
SQL - DML and DDL Commands
Shrija Madhu
 
introdution to SQL and SQL functions
farwa waqar
 
Ms sql-server
Md.Mojibul Hoque
 
SQL commands
GirdharRatne
 
Ad

Similar to DDL(Data defination Language ) Using Oracle (20)

PPTX
SQL _UNIT_DBMS_PRESENTSTATION_SQL _UNIT_DBMS_PRESENTSTATION
deeptanshudas100
 
PPTX
Database
NoorullahZamindar
 
PPT
Structure query language - Data definition language.ppt
munmunitjusl
 
PPT
Using ddl statements to create and manage tables
Syed Zaid Irshad
 
PPT
Les10.ppt
AlhassanFederated
 
PPT
Les09
Sudharsan S
 
PPT
Les09 (using ddl statements to create and manage tables)
Achmad Solichin
 
PDF
CS3481_Database Management Laboratory .pdf
Kirubaburi R
 
PPT
Dbms oracle
Abrar ali
 
PPT
plsql Les09
sasa_eldoby
 
PPT
Module 3 _SQL Database Management System
prajwalr3501
 
PDF
SQL-8 Table Creation.pdf
HannanKhalid4
 
PPTX
3. ddl create
Amrit Kaur
 
PPT
Introduction to sql
VARSHAKUMARI49
 
PPTX
SQL.pptx
SAIFKHAN41507
 
PDF
3. DDL.pdf
Sunita Milind Dol
 
PPTX
2. DBMS Experiment - Lab 2 Made in SQL Used
TheVerse1
 
SQL _UNIT_DBMS_PRESENTSTATION_SQL _UNIT_DBMS_PRESENTSTATION
deeptanshudas100
 
Structure query language - Data definition language.ppt
munmunitjusl
 
Using ddl statements to create and manage tables
Syed Zaid Irshad
 
Les09 (using ddl statements to create and manage tables)
Achmad Solichin
 
CS3481_Database Management Laboratory .pdf
Kirubaburi R
 
Dbms oracle
Abrar ali
 
plsql Les09
sasa_eldoby
 
Module 3 _SQL Database Management System
prajwalr3501
 
SQL-8 Table Creation.pdf
HannanKhalid4
 
3. ddl create
Amrit Kaur
 
Introduction to sql
VARSHAKUMARI49
 
SQL.pptx
SAIFKHAN41507
 
3. DDL.pdf
Sunita Milind Dol
 
2. DBMS Experiment - Lab 2 Made in SQL Used
TheVerse1
 
Ad

Recently uploaded (20)

PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
PDF
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
PPTX
Stamford - Community User Group Leaders_ Agentblazer Status, AI Sustainabilit...
Amol Dixit
 
PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
PPTX
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
PDF
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
PPTX
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
PDF
Chapter 1 Introduction to CV and IP Lecture Note.pdf
Getnet Tigabie Askale -(GM)
 
PDF
Doc9.....................................
SofiaCollazos
 
PDF
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
PDF
Best ERP System for Manufacturing in India | Elite Mindz
Elite Mindz
 
PDF
Revolutionize Operations with Intelligent IoT Monitoring and Control
Rejig Digital
 
PDF
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
PPTX
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
PPTX
Coupa-Overview _Assumptions presentation
annapureddyn
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
Stamford - Community User Group Leaders_ Agentblazer Status, AI Sustainabilit...
Amol Dixit
 
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
Chapter 1 Introduction to CV and IP Lecture Note.pdf
Getnet Tigabie Askale -(GM)
 
Doc9.....................................
SofiaCollazos
 
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
Best ERP System for Manufacturing in India | Elite Mindz
Elite Mindz
 
Revolutionize Operations with Intelligent IoT Monitoring and Control
Rejig Digital
 
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
Coupa-Overview _Assumptions presentation
annapureddyn
 

DDL(Data defination Language ) Using Oracle

  • 2. Naming Rules • Table names and column names: – Must begin with a letter – Must be 1–30 characters long – Must contain only A–Z, a–z, 0–9, _, $, and # – Must not duplicate the name of another object owned by the same user – Must not be an Oracle server reserved word
  • 3. Data Types Data Type Description VARCHAR2(size) Variable-length character data CHAR(size) Fixed-length character data NUMBER(p,s) Variable-length numeric data DATE Date and time values
  • 4. Creating Tables – Create the table. – Confirm table creation. DESCRIBE dept CREATE TABLE dept (deptno NUMBER(2), dname VARCHAR2(14), loc VARCHAR2(13), create_date DATE DEFAULT SYSDATE); Table created.
  • 5. Constraints – Create a constraint at either of the following times: • At the same time as the table is created • After the table has been created – Define a constraint at the column or table level. – View a constraint in the data dictionary. • NOT NULL • UNIQUE • PRIMARY KEY • FOREIGN KEY
  • 6. Constraints... – Column-level constraint: – Table-level constraint: column [CONSTRAINT constraint_name] constraint_type, column,... [CONSTRAINT constraint_name] constraint_type (column, ...),
  • 7. Defining Constraints – Column-level constraint: – Table-level constraint: CREATE TABLE employees( employee_id NUMBER(6) CONSTRAINT emp_emp_id_pk PRIMARY KEY, first_name VARCHAR2(20), ...); CREATE TABLE employees( employee_id NUMBER(6), first_name VARCHAR2(20), ... job_id VARCHAR2(10) NOT NULL, CONSTRAINT emp_emp_id_pk PRIMARY KEY (EMPLOYEE_ID)); 1 2
  • 8. The NOT NULL Constraint • The NOT NULL constraint ensures that the column has a value and the value is not a null value • A space or a numeric zero is not a null value • At the column level ONLY, the constraint is defined by: Name VARCHAR2(15) CONSTRAINT faculty_name_nn NOT NULL,
  • 9. UNIQUE Constraint • Defined at either the table level or the column level:CREATE TABLE employees( employee_id NUMBER(6), last_name VARCHAR2(25) NOT NULL, email VARCHAR2(25), salary NUMBER(8,2), commission_pct NUMBER(2,2), hire_date DATE NOT NULL, ... CONSTRAINT emp_email_uk UNIQUE(email));
  • 10. FOREIGN KEY Constraint DEPARTMENTS EMPLOYEES FOREIGN KEY INSERT INTO Not allowed (9 does not exist) Allowed PRIMARY KEY … …
  • 11. FOREIGN KEY Constraint • Defined at table level only: CREATE TABLE employees( employee_id NUMBER(6), last_name VARCHAR2(25) NOT NULL, email VARCHAR2(25), salary NUMBER(8,2), commission_pct NUMBER(2,2), hire_date DATE NOT NULL, ... department_id NUMBER(4), CONSTRAINT emp_dept_fk FOREIGN KEY (department_id) REFERENCES departments(department_id), CONSTRAINT emp_email_uk UNIQUE(email));
  • 12. FOREIGN KEY Constraint: Keywords – FOREIGN KEY: Defines the column in the child table at the table-constraint level – REFERENCES: Identifies the table and column in the parent table
  • 13. CHECK Constraint – Defines a condition that each row must satisfy ..., salary NUMBER(2) CONSTRAINT emp_salary_min CHECK (salary > 0),...
  • 14. CREATE TABLE: Example CREATE TABLE employees ( employee_id NUMBER(6) CONSTRAINT emp_employee_id PRIMARY KEY , first_name VARCHAR2(20) , last_name VARCHAR2(25) CONSTRAINT emp_last_name_nn NOT NULL , email VARCHAR2(25) CONSTRAINT emp_email_nn NOT NULL CONSTRAINT emp_email_uk UNIQUE , phone_number VARCHAR2(20) , hire_date DATE CONSTRAINT emp_hire_date_nn NOT NULL , job_id VARCHAR2(10) CONSTRAINT emp_job_nn NOT NULL , salary NUMBER(8,2) CONSTRAINT emp_salary_ck CHECK (salary>0) , commission_pct NUMBER(2,2) , manager_id NUMBER(6) , department_id NUMBER(4) CONSTRAINT emp_dept_fk REFERENCES departments (department_id));
  • 15. UPDATE employees * ERROR at line 1: ORA-02291: integrity constraint (HR.EMP_DEPT_FK) violated - parent key not found UPDATE employees SET department_id = 55 WHERE department_id = 110; Violating Constraints
  • 16. Violating Constraints • You cannot delete a row that contains a primary key that is used as a foreign key in another table.DELETE FROM departments WHERE department_id = 60; DELETE FROM departments * ERROR at line 1: ORA-02292: integrity constraint (HR.EMP_DEPT_FK) violated - child record found
  • 17. Creating a Table by Using a Subquery – Create a table and insert rows by combining the CREATE TABLE statement and the AS subquery option. – Match the number of specified columns to the number of subquery columns. – Define columns with column names and default values. CREATE TABLE table [(column, column...)] AS subquery;
  • 18. CREATE TABLE dept80 AS SELECT employee_id, last_name, salary*12 ANNSAL, hire_date FROM employees WHERE department_id = 80; Table created. Creating a Table by Using a Subquery DESCRIBE dept80
  • 19. ALTER TABLE Statement • Use the ALTER TABLE statement to: – Add a new column – Modify an existing column – Define a default value for the new column – Drop a column – Drop Constraint
  • 20. Adding a New Column to an Existing Table • The general syntax to add a column to an existing table is ALTER TABLE tablename ADD columnname datatype; SQL> ALTER TABLE student 2 ADD SocialSecurity CHAR(9); Table altered. SQL>
  • 21. Modifying an Existing Column • The general syntax to modify an existing column is ALTER TABLE tablename MODIFY columnname newdatatype; where newdatatype is the new data type or the new size for the column. SQL> ALTER TABLE student 2 MODIFY SocialSecurity VARCHAR2(11); Table altered. SQL>
  • 22. Adding a Constraint • To add a constraint using ALTER TABLE, the syntax for table level constraint is used. The general syntax of ALTER TABLE is ALTER TABLE tablename ADD [CONSTRAINT constraint_name] constraint_type (column, …), SQL> ALTER TABLE COURSE 2 ADD CONSTRAINT COURSE_PREREQ_FK FOREIGN KEY (PREREQ) 3 REFERENCES COURSE(COURSEID); Table altered. SQL>
  • 23. Dropping a Column and constrain The general syntax is • ALTER TABLE tablename DROP COLUMN columnname; • ALTER TABLE tablename DROP CONSTRAINT constraintname;
  • 24. Renaming a Table – Additional DDL statements include the RENAME statement, which is used to rename a table, view, sequence. – Syntax – RENAME old_name TO new_name; – In the syntax: – old_name is the old name of the table, view, sequence. – new_name is the new name of the table, view, sequence.
  • 25. Views • Provide security • Create view viewName as select * from tablename
  • 26. • Create view. • View can be insert/updated/deleted to reflect changes in base table only if all not null columns included in table and also view is created by a single table.
  • 27. More SQL Data Definition Sequences • Often we want to assign each row a unique number – These are useful as primary keys • In most versions of SQL we can use autoincrementing fields to do this – Usually the first entry is assigned 1, the next 2, and so on, but Oracle lets you change this
  • 28. More SQL Data Definition Sequences • In Oracle we use a Sequence – A sequence is a source of numbers – We can declare several sequences, giving each a name, a start point, and a step size – We can then generate unique numbers by asking for the next element from a sequence
  • 29. More SQL Data Definition Sequences in Oracle • To declare a sequence: CREATE SEQUENCE <name> [START WITH <value>] [INCREMENT BY <value>] – If no START WITH or INCREMENT BY values are given they default to 1 • To get the next value from a sequence <sequence name>.nextVal
  • 30. More SQL Data Definition Sequence Example • Creating a sequence CREATE SEQUENCE mySeq START WITH 1 • Using a sequence SELECT mySeq.nextVal FROM DUAL; INSERT INTO Student (stuID, stuName, stuAddress) VALUES (mySeq.nextVal, 'Steve Mills', '13 Elm Street')
  • 31. More SQL Data Definition Oracle Data Dictionary • To find the details of a table use DESCRIBE <table name> • Example: SQL> DESCRIBE Student; Name Null? Type ------------ -------- ---------- STUID NOT NULL NUMBER(38) STUNAME NOT NULL VARCHAR2(50) STUADDRESS VARCHAR2(50) STUYEAR NUMBER(38)
  • 32. Create synonym • create synonyms so that other schemas can access the new database objects (ie: tables) without having to prefix the object names • SELECT * FROM new_schema.suppliers; • If you then created a synonym for the suppliers table as follows: • CREATE PUBLIC SYNONYM suppliers FOR new_schema.suppliers;You could run the SELECT statement as follows: • SELECT * FROM suppliers;th the schema name.
  • 33. 33 DCL: Data Control Language • Controlling Access to database objects such as tables and views • Example : Granting “Mary” the access to Table “student” (for inserting, updating and deleting) – GRANT INSERT, UPDATE, DELETE ON Emp TO Mary – GRANT <privileges> ON <object name> TO <grantee> [ <comma> <grantee> ... ] [ WITH GRANT OPTION ] – WITH GRANT OPTION: allows the grantee to further grant privileges – Can be limited to a column of a table, Ex: GRANT UPDATE(name) ON emp TO Mary – To revoke privileges : REVOKE
  • 34. • Grant all privilleges to user • GRANT <privileges> ON <object name> TO <grantee> [ <comma> <grantee> ... ] [ WITH GRANT OPTION ] • Create table u7.table8(id int); • Grant Privileges on Functions/Procedures • When dealing with functions and procedures, you can grant users the ability to EXECUTE these functions and procedures. • Syntax • GRANT EXECUTE ON object TO user;
  • 35. • Create tablespace ts1 datafile ‘E:Oracle_lectsts1.dbf’ size 100M’ • …………………………………………………………. • CREATE USER jward • IDENTIFIED BY aZ7bC2 • DEFAULT TABLESPACE data_ts; • GRANT connect TO jward; • ........................................ • grant connect to craig; • alter user craig quota unlimited on CRAIG_DATA; • grant create table to craig; • ................................. • create role rolename; • grant connect to rolename; • grant rollname to username;
  • 36. Granting privileges • GRANT – Grants a privilege to a user – Can grant privilege only if you have been granted that privilege (or if you are the administrator) grant <privilege> to <user>; Grant create table to user_name with admin option
  • 37. Examples of granting roles • grant create table to john; • grant all on CD_MASTER to tom; • grant SELECT ON CD_MASTER.CD_NAME to john; • grant select, update on CD_DB to tom; • grant references(CD_NO) on CD_DB to john;
  • 38. Revoking roles • REVOKE – Revokes a privilege from a user – Can revoke privilege only if you have been granted that privilege (or if you are the administrator) revoke <privilege> from <user>;
  • 39. Dropping a Table – All data and structure in the table are deleted. – All indexes are dropped. – All constraints are dropped. – You cannot roll back the DROP TABLE statement. DROP TABLE dept80; Table dropped.
  • 40. Dropping a Table • The general syntax is DROP TABLE tablename [CASCADE CONSTRAINTS]; • For example, DROP TABLE sample; • Oracle displays a “Table dropped” message when a table is successfully dropped. • If you add optional CASCADE CONSTRAINTS clause, it removes foreign key references to the table also.
  • 41. More SQL Data Definition Oracle Data Dictionary • SELECT DISTINCT OBJECT_NAME FROM USER_OBJECTS • To find out what tables and sequences you have defined use SELECT tablespace_name,table_name FROM user_tables – The user_tables table is maintained by Oracle – It has lots of columns, so don’t use SELECT * FROM user_tables
  • 42. Oracle Data Dictionary • Select username from dba_users; • select privilege from dba_sys_privs where grantee = 'RESOURCE': • PRIVILEGE -------------------------------------- CREATE TYPE CREATE TABLE CREATE CLUSTER CREATE TRIGGER CREATE OPERATOR CREATE SEQUENCE CREATE INDEXTYPE CREATE PROCEDURE
  • 43. • select * from session_privs; • PRIVILEGE ---------------------------------------- CREATE SESSION UNLIMITED TABLESPACE CREATE TABLE
  • 44. View Description DBA_USERS Describes all users of the database ALL_USERS Lists users visible to the current user, but does not describe them USER_USERS Describes only the current user

Editor's Notes

  • #4: Data Types When you identify a column for a table, you need to provide a data type for the column. There are several data types available:
  • #5: Creating Tables The example in the slide creates the DEPT table, with four columns: DEPTNO, DNAME, LOC, and CREATE_DATE. The CREATE_DATE column has a default value. If a value is not provided for an INSERT statement, the system date is automatically inserted. It further confirms the creation of the table by issuing the DESCRIBE command. Because creating a table is a DDL statement, an automatic commit takes place when this statement is executed.
  • #8: Defining Constraints (continued) Constraints are usually created at the same time as the table. Constraints can be added to a table after its creation and also temporarily disabled. Both slide examples create a primary key constraint on the EMPLOYEE_ID column of the EMPLOYEES table. 1. The first example uses the column-level syntax to define the constraint. 2. The second example uses the table-level syntax to define the constraint. More details about the primary key constraint are provided later in this lesson.
  • #10: UNIQUE Constraint (continued) UNIQUE constraints can be defined at the column level or table level. A composite unique key is created by using the table-level definition. The example in the slide applies the UNIQUE constraint to the EMAIL column of the EMPLOYEES table. The name of the constraint is EMP_EMAIL_UK.. Note: The Oracle server enforces the UNIQUE constraint by implicitly creating a unique index on the unique key column or columns.
  • #11: FOREIGN KEY Constraint The FOREIGN KEY (or referential integrity) constraint designates a column or combination of columns as a foreign key and establishes a relationship between a primary key or a unique key in the same table or a different table. In the example in the slide, DEPARTMENT_ID has been defined as the foreign key in the EMPLOYEES table (dependent or child table); it references the DEPARTMENT_ID column of the DEPARTMENTS table (the referenced or parent table). Guidelines A foreign key value must match an existing value in the parent table or be NULL. Foreign keys are based on data values and are purely logical, rather than physical, pointers.
  • #12: FOREIGN KEY Constraint (continued) FOREIGN KEY constraints can be defined at the column or table constraint level. A composite foreign key must be created by using the table-level definition. The example in the slide defines a FOREIGN KEY constraint on the DEPARTMENT_ID column of the EMPLOYEES table, using table-level syntax. The name of the constraint is EMP_DEPTID_FK. The foreign key can also be defined at the column level, provided the constraint is based on a single column. The syntax differs in that the keywords FOREIGN KEY do not appear. For example: CREATE TABLE employees (... department_id NUMBER(4) CONSTRAINT emp_deptid_fk REFERENCES departments(department_id), ... )
  • #13: FOREIGN KEY Constraint: Keywords The foreign key is defined in the child table, and the table containing the referenced column is the parent table. The foreign key is defined using a combination of the following keywords: FOREIGN KEY is used to define the column in the child table at the table-constraint level. REFERENCES identifies the table and column in the parent table. ON DELETE CASCADE indicates that when the row in the parent table is deleted, the dependent rows in the child table are also deleted. ON DELETE SET NULL converts foreign key values to null when the parent value is removed. The default behavior is called the restrict rule, which disallows the update or deletion of referenced data. Without the ON DELETE CASCADE or the ON DELETE SET NULL options, the row in the parent table cannot be deleted if it is referenced in the child table.
  • #15: The CREATE TABLE Example The example shows the statement used to create the EMPLOYEES table in the HR schema.
  • #16: Integrity Constraint Error When you have constraints in place on columns, an error is returned to you if you try to violate the constraint rule. For example, if you attempt to update a record with a value that is tied to an integrity constraint, an error is returned. In the example in the slide, department 55 does not exist in the parent table, DEPARTMENTS, and so you receive the parent key violation ORA-02291.
  • #18: Creating a Table from Rows in Another Table A second method for creating a table is to apply the AS subquery clause, which both creates the table and inserts rows returned from the subquery. In the syntax: table is the name of the table column is the name of the column, default value, and integrity constraint subquery is the SELECT statement that defines the set of rows to be inserted into the new table Guidelines The table is created with the specified column names, and the rows retrieved by the SELECT statement are inserted into the table. The column definition can contain only the column name and default value. If column specifications are given, the number of columns must equal the number of columns in the subquery SELECT list. If no column specifications are given, the column names of the table are the same as the column names in the subquery. The integrity rules are not passed to the new table; only the column data type definitions are passed.
  • #19: Creating a Table from Rows in Another Table (continued) The slide example creates a table named DEPT80, which contains details of all the employees working in department 80. Notice that the data for the DEPT80 table comes from the EMPLOYEES table. You can verify the existence of a database table and check column definitions by using the iSQL*Plus DESCRIBE command. Be sure to provide a column alias when selecting an expression. The expression SALARY*12 is given the alias ANNSAL. Without the alias, the following error is generated: ERROR at line 3: ORA-00998: must name this expression with a column alias
  • #40: Dropping a Table The DROP TABLE statement removes the definition of an Oracle table. When you drop a table, the database loses all the data in the table and all the indexes associated with it. Syntax DROP TABLE table In the syntax, table is the name of the table. Guidelines All data is deleted from the table. Any views and synonyms remain but are invalid. Any pending transactions are committed. Only the creator of the table or a user with the DROP ANY TABLE privilege can remove a table. Note: The DROP TABLE statement, once executed, is irreversible. The Oracle server does not question the action when you issue the DROP TABLE statement. If you own that table or have a high-level privilege, then the table is immediately removed. As with all DDL statements, DROP TABLE is committed automatically.