Upload
doandieu
View
238
Download
0
Embed Size (px)
Citation preview
LECTURE8:
SQL OVERVIEW , ORACLE DATA
TYPE , DDL AND CONSTRAINTS
Ref. Chapter6 from
“Database Systems: A Practical Approach to Design, Implementation and Management.”
Thomas Connolly, Carolyn Begg.
I S 2 2 0 : D a t ab a s e F u n d a m e n t a l s
Chapter Objectives
In this chapter you will learn:
The data types supported by the SQL standard.
How to define integrity constraints using SQL including:
required data;
domain constraints;
entity integrity;
referential integrity;
general constraints.
How to use the integrity constraints in the CREATE and ALTER
TABLE
2
The Process of Database Design 3
Conceptual Design (ERD)
Logical Design
(Relational Model)
Physical Design
Create schema
(DDL)
Load Data
(DML)
SQL Overview
Official pronunciation is ‘S-Q-L‘ or ( see-qual)
SQL: Structured Query Language
The standard for relational database management systems
(RDBMS) such as Oracle Database.
All SQL statements are instructions to the database.
Easy to learn:
Consists of standard English words, case insensitive
It is a non-procedural language:
you specify what information you require, rather than how to
get it. In other words, SQL does not require you to specify the
access methods to the data
5
SQL in Oracle
• SQL is made up of 4 components:
1. Data Definition Language (DDL)
2. Data Manipulation Language (DML)
3. Data Control Language (DCL)
4. Transaction control statements
6
SQL Components
1. The Data Definition Language (DDL)
This component of the SQL language is used for defining the
database structure and to create and modify tables and
other objects in the database.
For tables there are three main commands:
1. CREATE TABLE tablename : to create a table in the
database
2. DROP TABLE tablename : to remove a table from the
database
3. ALTER TABLE tablename : to add or remove columns from
a table in the database
7
SQL Components
2. The Data Manipulation Language (DML)
component of the SQL language is used for retrieving and
updating data
There are four main commands:
1. SELECT : to select rows of data from a table.
2. INSERT : to insert rows of data into a table.
3. UPDATE : to change rows of data in a table.
4. DELETE : to remove rows of data from a table.
8
SQL Components
3. The Data Control Language (DCL)
This component of the SQL language is used to create
privileges to allow users access to, and manipulation of, the
database.
There are two main commands:
1. GRANT : to grant a privilege to a user
2. REVOKE : to revoke (remove) a privilege from a user
4. Transaction control statements
• COMMIT, ROLLBACK
9
Data Definition (Creating a table)
CREATING A TABLE Syntax:
Table Name CONDITIONS :
can not exceed 30 characters long
Must begin with an alphabetic character
May contain letters, numbers, $, # and _
Should not be an oracle reserved word
Should be descriptive
11
create table table-name (
column-name1 datatype ,
……..
column-nameN datatype );
Built-In Oracle Data type Summary
Built-in Data type Description Max Size: Oracle 9i/10g
VARCHAR2(size
[BYTE | CHAR]) Variable length character string having
maximum length size bytes.
You must specify size
4000 bytes
minimum is 1
CHAR(size)
Fixed length character data of length size
bytes. This should be used for fixed length
data. Such as codes A100, B102...
2000 bytes
Default and minimum size is 1
byte.
NUMBER(p,s) Number having precision p and scale s. The precision
p can range from 1 to 38.
The scale s can range from -84 to127.
The precision p can range from 1
to 38.
The scale s can range from -84 to
127.
DATE Valid date range from January 1, 4712 BC to
December 31, 9999 AD.
from January 1, 4712 BC to
December 31, 9999 AD.
TIMESTAMP[timePre
csion]
Year, month, and day values of date, as well as
hour,minute, and second values of time,
Accepted values of
fractional_seconds_precision are 0
to 9. (default = 6)
12
NUMBER(p,s)
Syntax for specifying numbers
Number (precision, scale)
Precision is the maximum digits of numbers
Scale specifies the position of decimal point.
E.g.
Number(5) 5 digit integer, ex) 12345
Number(6,2) 6 digit (not including decimal point)
decimal number with 2 digits after the decimal point ,
ex) 1234.56
Can store 1—38 digits precision
13
String
To store strings, you can choose from:
Char (size)
stores fixed-length character strings of up to 2000
characters. Eg. char(10)
Use it to store short strings
Varchar2 (size)
Stores variable-length strings of up to 4000 characters
long. Eg. Varchar2(50)
Preferred for most string types
Must specify the size
String values are quoted with single quotes
Eg ‘12234’, ‘abcd’, ‘a12’
14
Date and time
Oracle uses the date data type to store both date and time
Always uses 7 bytes for date-time data.
Oracle date has rich formats, you need to specify it
SS second 0-59
MI Minute 0-59
HH Hour 1-12
HH24 Military hour 1-24
DD day of month 1-31 (depends on month)
DAY day of the week Sunday-Saturday
D day of the week 1-7
MM month number 1-12
MON month abbreviated Jan—Dec
Month Month spelled out January-December
YY last 2 digits of year eg, 98
YYYY full year value eg, 1998
15
Date and time
Example of date format:
‘dd-mon-yyyy’ 01-dec-2001
‘dd/mm/yyyy’ 01/12/2001
‘mm-dd-yy hh:mi:ss’ 12-01-01 12:30:59
Default format: ‘dd-mon-yyyy’
Current date and time:
Sysdate
16
Example
CREATE TABLE Persons
( P_Id char(5) ,
LastName varchar2(255),
FirstName varchar2(255),
Sex char(2),
);
17
Integrity Constraints
An integrity constraint defines a business rule for a table
column.
When enabled, the rule will be enforced by oracle
constraints can be defined at either the table level or the
column level.
If the results of an INSERT or UPDATE statement violate an
integrity constraint, the statement will be rolled back.
Note : If you don’t give the constraint name, the system will
generate a name automatically, but the name is hard for
human understanding.
19
Integrity Constraints
Constraint clauses can appear in the following statements:
1. CREATE TABLE
2. ALTER TABLE
3. CREATE VIEW
4. ALTER VIEW
20
The types of integrity constraint
1. NOT NULL constraint
2. UNIQUE constraint
3. PRIMARY KEY constraint
4. FOREIGN KEY constraint
5. CHECK constraint
21
NOT NULL constraint
The NOT NULL constraint enforces a field to always contain a
value. This means that you cannot insert a new record, or
update a record without adding a value to this field.
Defined at column level ONLY
Syntax:
OR
22
CREATE TABLE table-name (
column-name1 datatype NOT NULL );
CREATE TABLE table-name (
column-name1 datatype CONSTRAINT
constraint_name NOT NULL );
CREATE TABLE employees(
employee_id NUMBER(6),
last_name VARCHAR2(25) NOT NULL,
salary NUMBER(8,2),
commission_pct NUMBER(2,2),
hire_date DATE CONSTRAINT emp_hire_date NOT NULL );
Example: NOT NULL
23
System named
User named
SQL NULL
If a column in a table is optional, we can insert a new record or
update an existing record without adding a value to this column. This
means that the field will be saved with a NULL value.
NULL values are treated differently from other values.
NULL is used as a placeholder for unknown or inapplicable values.
Note: It is not possible to compare NULL and 0; they are not
equivalent.
It is not possible to test for NULL values with comparison
operators, such as =, <, or <>.
We will have to use the IS NULL and IS NOT NULL operators
instead.
24
UNIQUE constraint
The UNIQUE constraint prohibits multiple rows from having the same
value in the same column or combination of columns but allows some
values to be null.
Defined at either the table level or the column level
Unique columns are not automatically NOT NULL
Syntax:
25
1- column level
CREATE TABLE table-name (
column-name1 datatype UNIQUE );
2- table level
CREATE TABLE table-name (
…….
[CONSTRAINT constraint-name] UNIQUE (Columns_list)) ;
Example: UNIQUE
The following SQL creates a UNIQUE constraint on the "P_Id" column when the "Persons" table is created:
CREATE TABLE Persons (
P_Id char(5) NOT NULL UNIQUE, LastName varchar2(255) NOT NULL, FirstName varchar2(255), Address varchar2(255),
Telephone varchar2(10), City varchar2(255),
UNIQUE (LastName, FirstName),
CONSTRAINT tel_unique UNIQUE (telephone) );
27
Column level
Table level
Primary Key Constraint
A primary key constraint combines a NOT NULL constraint
and a UNIQUE constraint in a single declaration. That is, it
prohibits multiple rows from having the same value in the
same column or combination of columns and prohibits values
from being null.
A PRIMARY KEY constraint automatically has a UNIQUE
constraint defined on it.
Defined at either the table level or the column level
Note that you can have many UNIQUE constraints per table,
but only one PRIMARY KEY constraint per table.
28
Primary Key Constraint
OR
29
1- Table level
CREATE TABLE table-name (
column-name1 datatype,
……..
column-nameN datatype,
[CONSTRAINT constraint-name] PRIMARY KEY (columns-name));
2- Column level
CREATE TABLE table-name (
column-name1 datatype PRIMARY KEY,
……..
column-nameN datatype);
Example: Primary Key
Column Level
CREATE TABLE Department (
Dept_no char(4) PRIMARY KEY,
Dept_name varchar2(25));
OR Table Level
CREATE TABLE Department (
dept_no char(4),
Dept_name varchar2(25),
CONSTRAINT dept_PK PRIMARY KEY (dept_no));
30
Column level
Table level
FOREIGN KEYS constraint
foreign key constraint requires values in one table to match
values in another table.
Syntax:
31
CREATE TABLE table-name ( column-name1 datatype,
……
……
[CONSTRAINT constraint-name] FOREIGN KEY
(Column_name) REFERENCES referenced_table
(column_in_referenced_table) );
Example: Foreign Keys
Create table Employee(
EMPLOYEE_ID NUMBER(3) PRIMARY KEY,
LAST_NAME varchar2(20),
DEPARTMENT_ID NUMBER(3),
CONSTRAINT EMP_Fk FOREIGN KEY (DEPARTMENT_ID)
REFERENCES Department (DEPARTMENT_ID));
32
The FOREIGN KEY Constraint
33
Department
Employee
FOREIGN
KEY
INSERT INTO Not allowed (9 does not
exist)
Allowed
PRIMARY
KEY
90
Referential integrity constraints
When you delete or update a value of the columns referenced
by other tables, the referential integrity constraints may be
violated.
ON DELETE/UPDATE Clause
The ON DELETE / ON UPDATE clause lets you determine
how Oracle Database automatically maintains referential
integrity if you remove or update a referenced primary key
value. If you omit this clause, then Oracle does not allow you
to delete referenced key values in the parent table that
have dependent rows in the child table.
34
referential integrity constraints
Four options are supported when the user attempt to delete the CK and there matching FKs:
ON DELETE/UPDATE CASCADE: delete or update the CK row from the
parent table and all matching FK rows in the child table.
ON DELETE/UPDATE SET NULL: delete or update the CK row from the
parent table and set the FK values to NULL in the child table. This is
valid only if the foreign key columns do not have the NOT NULL
qualifier specified.
ON DELETE/UPDATE SET Default: delete or update the CK row from the
parent table and set the FK values to the specified default value in
the child table. Valid only if DEFAULT constraint is specified
No action: Reject the delete operation from the parent table. This is the
default setting if the ON DELETE rule is omitted.
35
36
CREATE TABLE Department (
DeptNo CHAR(3) PRIMARY KEY,
DeptName VARCHAR2(20) );
CREATE TABLE Employee (
EmpId CHAR(1) PRIMARY KEY,
EmpName VARCHAR2(25),
DeptNo CHAR(3) ,
CONSTRAINT dept_fk FOREIGN KEY (DeptNo) REFERENCES
Department(DeptNo) ON DELETE CASCADE );
delete from Department where DeptNo=103
EmpId EmpName DeptNo
1 Ali 101
2 Sally 101
3 John 103
DeptNo DeptName
101 AAA
102 BBB
103 CCC
PK
FK
DeptNo DeptName
101 AAA
102 BBB
EmpId EmpName DeptNo
1 Ali 101
2 Sally 101
Department Employee
ON DELETE/UPDATE CASCADE
37
CREATE TABLE Department (
DeptNo CHAR(3) PRIMARY KEY,
DeptName VARCHAR2(20) );
CREATE TABLE Employee (
EmpId CHAR(1) PRIMARY KEY,
EmpName VARCHAR2(25),
DeptNo CHAR(3) ,
CONSTRAINT dept_fk FOREIGN KEY (DeptNo) REFERENCES
Department(DeptNo) ON DELETE SET NULL );
delete from Department where DeptNo=103
EmpId EmpName DeptNo
1 Ali 101
2 Sally 101
3 John 103
DeptNo DeptName
101 AAA
102 BBB
103 CCC
PK
FK
DeptNo DeptName
101 AAA
102 BBB
Department Employee
ON DELETE/UPDATE SET NULL
EmpId EmpName DeptNo
1 Ali 101
2 Sally 101
3 John NULL
38
CREATE TABLE Department (
DeptNo CHAR(3) PRIMARY KEY,
DeptName VARCHAR2(20) );
CREATE TABLE Employee (
EmpId CHAR(1) PRIMARY KEY,
EmpName VARCHAR2(25),
DeptNo CHAR(5) Default ‘Empty’,
CONSTRAINT dept_fk FOREIGN KEY (DeptNo) REFERENCES
Department(DeptNo) ON DELETE SET Default);
delete from Department where DeptNo=103
EmpId EmpName DeptNo
1 Ali 101
2 Sally 101
3 John 103
DeptNo DeptName
101 AAA
102 BBB
103 CCC
PK
FK
DeptNo DeptName
101 AAA
102 BBB
Department Employee
ON DELETE/UPDATE SET Default
EmpId EmpName DeptNo
1 Ali 101
2 Sally 101
3 John Empty
Check Constraints
The CHECK constraint is used to limit the value range that can be placed in a column.
If you define a CHECK constraint on a single column it allows only certain values for this column.
If you define a CHECK constraint on a table it can limit the values in certain columns based on values in other columns in the row.
Defined at either the table level or the column level
39
Check Constraints
Syntax:
OR
40
create table table-name (
column-name1 datatype CHECK (Check_condition) ) ;
create table table-name (
…….
…….
[CONSTRAINT constraint-name] CHECK (Check_condition) );
Example : Check
Create table staff(
Staff_no char(3),
Staff_name varchar2(20) not null,
Staff_gender char(1) CHECK (staff_gender in (‘M’, ‘F’)),
Staff_salary number(8,2) not null,
Dept_no char(4),
Constraint staff_pk Primary key (staff_no),
Constraint staff_fk Foreign key (dept_no) references department (dept_no),
Constraint staff_sal CHECK (staff_salary >10000.00));
41
Table level
Column level
Check Condition Examples
1- The Age entered should be greater than or equal 18?
CHECK (AGE >= 18 )
2- the age grade is greater than 18 OR the nationality is ‘Saudi’ ?
CHECK (Age >18 OR nationality=‘Saudi' )
3- the supplier name either IBM or Microsoft or NVIDIA?
CHECK (supplier_name IN ('IBM', 'Microsoft', 'NVIDIA'))
42
DEFAULT constraint
The DEFAULT constraint is used to insert a default value
into a column.
The default value will be added to all new records, if no
other value is specified.
Syntax:
43
create table table-name (
column-name1 datatype DEFAULT (Default_value)
);
Example: DEFAULT
Example : The following SQL creates a DEFAULT constraint
on the "City" column when the "Persons" table is created:
CREATE TABLE Persons
(
P_Id char(5) NOT NULL,
LastName varchar2(255) NOT NULL,
FirstName varchar2(255),
Address varchar2(255),
City varchar2(255) DEFAULT 'Sandnes'
);
44
Example : All Constraints
Create table staff(
Staff_no char(3),
Staff_name varchar2(20) NOT NULL,
DateofBirth date,
Staff_nationality char(10) DEFAULT ‘Saudi’,
Staff_salary number(8,2) NOT NULL,
Dept_no char(4),
Constraint staff_pk PRIMARY KEY (staff_no),
Constraint staff_fk FOREIGN KEY (dept_no) references department (dept_no) on delete set null on update cascade,
Constraint staff_sal CHECK (staff_salary >10000.00),
UNIQUE(staff_name, DateofBirth));
45
Summary
46
Constraint Name Type Define it at
NOT NULL Simple( single column) Column-level ONLY
UNIQUE Simple ( single column) Column-level or Table-level
Composite (on multiple ) columns Table-level ONLY
PRIMARY KEY Simple (single column) Column-level or Table-level
Composite (on multiple (columns Table-level ONLY
FOREIGN KEY
Simple ( single column) Column-level or Table-level
Composite (on multiple) columns
Table-level ONLY.
CHECK -- Column-level or Table-level
Defualt -- Column-level ONLY
ALTER TABLE
ALTER TABLE statement used for changing the structure of a
table once it has been created.
The definition of the ALTER TABLE statement in the ISO
standard consists of six options to:
1. add a new column to a table;
2. drop a column from a table;
3. add a new table constraint;
4. drop a table constraint;
5. set a default for a column;
6. drop a default for a column.
49
Data Definition (Creating a table)
ALTERING A TABLE Syntax:
50
ALTER TABLE TableName
[ ADD columnName dataType ]
[ DROP COLUMN columnName [ RESTRICT | CASCADE]]
[ ADD [ CONSTRAINT [ConstraintName]]tableConstraintDefinition]
[ DROP CONSTRAINT ConstraintName [ RESTRICT | CASCADE]]
[ ALTER columnName SET DEFAULT defaultOption]
[ ALTER columnName DROP DEFAULT]
* Use [CASCADE CONSTRAINTS] to drop PRIMARY KEY column with dependent
integrity constraints.
RESTRICT and CASCADE
RESTRICT
With restrict if any other objects depend for their
existence on continued existence of this table, SQL
does not allow request.
CASCADE
With CASCADE, SQL drops all dependent objects (and objects dependent on these objects).
51
Example
(a) Change the Staff table by removing the default of ‘Assistant’ for the position column and setting the default for the sex column to female (‘F’).
ALTER TABLE Staff
ALTER position DROP DEFAULT;
ALTER TABLE Staff
ALTER sex SET DEFAULT ‘F’;
(b) Change the PropertyForRent table by removing the constraint that staff are not allowed to handle more than 100 properties at a time. Change the Client table by adding a new column representing the preferred number of rooms.
ALTER TABLE PropertyForRent
DROP CONSTRAINT StaffNotHandlingTooMuch;
ALTER TABLE Client
ADD prefNoRooms Number(2);
52
ALTER TABLE - Delete Column or Constraint
create table parent
(id number(2) primary key);
create table child
(id number(2),
Constraint id_fk foreign key (id) references parent(id));
ALTER TABLE parent
drop column id;
ERROR at line 1: ORA-12992: cannot drop parent key column
ALTER TABLE Parent
DROP PRIMARY KEY;
ERROR at line 1:ORA-02273: this unique/primary key is referenced by some foreign keys
53
Use Cascade Constraint
oracle Drops ID in Parent table and removes all
reference constraints to this key. So the foreign key
in Child table is removed.
Alter table parent
drop column id CASCADE CONSTRAINTS;
Table altered.
54
DROP TABLES
Pay attention to referential integrity constraints when dropping
tables.
If Cascade Constraints is used, the constraints will be dropped first.
56
Drop table table_name;
OR
Drop table table_name [Cascade Constraints];
Over time, the structure of a database will change; new tables will be created and
some tables will no longer be needed. We can remove a redundant table from the
database using the DROP TABLE statement
Syntax
Example
For example, to remove the PropertyForRent table
we use the command:
DROP TABLE PropertyForRent ;
57
Example
SQL> drop table Department;
drop table Department
*
ERROR at line 1:ORA02449: unique/primary keys in table reference
d by foreign keys
SQL> drop table Department Cascade Constraints ;
Table dropped.
58
EmpId EmpName DeptNo
1 Ali 101
2 Sally 101
3 John 103
DeptNo DeptName
101 AAA
102 BBB
103 CCC
PK
FK
Employee Department
Viewing Table Structures
To see the structure of a table, type
SQL> describe airlines;
59
DESCRIBE table_name;
or
DESC table_name ;