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.

IS220 : Database Fundamentals

Chapter Objectives

2 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 The Process of Database Design

3

Logical Design Conceptual Design (ERD) (Relational Physical Design Model)

Create schema Load Data (DDL) (DML) STRUCTURED QUERY LANGUAGE SQL

SQL Overview

5

 Official pronunciation is ‘S-Q-L‘ or ( see-qual)

 SQL: Structured Query Language

 The standard for 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

SQL in Oracle

6

• 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

SQL Components

7

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

SQL Components

8

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 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.

SQL Components

9

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

DATA DEFINITION LANGUAGE ( DDL )

Table Creation

10 Data Definition (Creating a table)

11 CREATING A TABLE Syntax:

create table table-name (

-name1 datatype , …….. column-nameN datatype );

 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 Built-In Oracle Data type Summary

12

Built-in Data type Description Max Size: Oracle 9i/10g

VARCHAR2(size 4000 bytes Variable length character string having [BYTE | CHAR]) minimum is 1 maximum length size bytes. You must specify size

Fixed length character data of length size 2000 bytes CHAR(size) bytes. This should be used for fixed length Default and minimum size is 1 data. Such as codes A100, B102... byte. NUMBER(p,s) Number having precision p and scale s. The precision The precision p can range from 1 p can range from 1 to 38. to 38. The scale s can range from -84 to127. The scale s can range from -84 to 127. DATE Valid date range from January 1, 4712 BC to from January 1, 4712 BC to December 31, 9999 AD. December 31, 9999 AD.

TIMESTAMP[timePre Year, month, and day values of date, as well as Accepted values of csion] hour,minute, and second values of time, fractional_seconds_precision are 0 to 9. (default = 6) NUMBER(p,s)

13

 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 String

14 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’ Date and time

15

 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 Date and time

16

 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 Example

17 CREATE TABLE Persons ( P_Id char(5) , LastName varchar2(255), FirstName varchar2(255), Sex char(2), );

18 Integrity Constraints

19

 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.

Integrity Constraints

20

 Constraint clauses can appear in the following statements:

1. CREATE TABLE

2. ALTER TABLE

3. CREATE VIEW

4. ALTER VIEW The types of integrity constraint

21

1. NOT NULL constraint

2. UNIQUE constraint

3. PRIMARY KEY constraint

4. FOREIGN KEY constraint

5. CHECK constraint NOT NULL constraint

22

 The NOT NULL constraint enforces a field to always contain a value. This means that you cannot insert a new record, or a record without adding a value to this field.

 Defined at column level ONLY Syntax: CREATE TABLE table-name ( column-name1 datatype NOT NULL ); OR CREATE TABLE table-name ( column-name1 datatype CONSTRAINT constraint_name NOT NULL ); Example: NOT NULL

23

CREATE TABLE employees( employee_id NUMBER(6), System last_name VARCHAR2(25) NOT NULL, named salary NUMBER(8,2), commission_pct NUMBER(2,2), hire_date DATE CONSTRAINT emp_hire_date NOT NULL ); User named SQL NULL

24

 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.

UNIQUE constraint

25

 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 .

 Defined at either the table level or the column level

 Unique columns are not automatically NOT NULL Syntax:

1 - column level CREATE TABLE table-name ( column-name1 datatype UNIQUE );

2 - table level CREATE TABLE table-name ( ……. [CONSTRAINT constraint-name] UNIQUE (Columns_list)) ; The UNIQUE Constraint

26 UNIQUE constraint EMPLOYEES

Allowed Not allowed: already exists Example: UNIQUE

27

 The following SQL creates a UNIQUE constraint on the "P_Id" column when the "Persons" table is created:

CREATE TABLE Persons Column level ( P_Id char(5) NOT NULL UNIQUE, LastName varchar2(255) NOT NULL, FirstName varchar2(255), Address varchar2(255), Telephone varchar2(10), Table level City varchar2(255), UNIQUE (LastName, FirstName), CONSTRAINT tel_unique UNIQUE (telephone) ); Primary Key Constraint

28

 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.

Primary Key Constraint

29

1- Table level CREATE TABLE table-name ( column-name1 datatype, …….. column-nameN datatype,

[CONSTRAINT constraint-name] PRIMARY KEY (columns-name)); OR

2- Column level CREATE TABLE table-name ( column-name1 datatype PRIMARY KEY, …….. column-nameN datatype); Example: Primary Key

30 Column Level CREATE TABLE Department ( Column level Dept_no char(4) PRIMARY KEY, Dept_name varchar2(25));

OR Table Level CREATE TABLE Department ( dept_no char(4), Table level Dept_name varchar2(25), CONSTRAINT dept_PK PRIMARY KEY (dept_no));

FOREIGN KEYS constraint

31 foreign key constraint requires values in one table to match values in another table.

Syntax:

CREATE TABLE table-name ( column-name1 datatype, …… …… [CONSTRAINT constraint-name] FOREIGN KEY (Column_name) REFERENCES referenced_table (column_in_referenced_table) );

Example: Foreign Keys

32 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)); The FOREIGN KEY Constraint

33 Department

PRIMARY KEY 90

Employee FOREIGN KEY

Not allowed INSERT INTO (9 does not exist) Allowed Referential integrity constraints

34

 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. referential integrity constraints

35

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. ON DELETE/UPDATE CASCADE

CREATE TABLE Department ( PK DeptNo DeptName DeptNo CHAR(3) PRIMARY KEY, AAA DeptName VARCHAR2(20) ); 101 BBB 102 103 CCC CREATE TABLE Employee ( FK

EmpId CHAR(1) PRIMARY KEY, EmpId EmpName DeptNo EmpName VARCHAR2(25), 1 Ali 101 DeptNo CHAR(3) , 2 Sally 101 CONSTRAINT dept_fk FOREIGN KEY (DeptNo) REFERENCES 3 John 103 Department(DeptNo) ON DELETE CASCADE );

 delete from Department DeptNo=103 Department Employee DeptNo DeptName EmpId EmpName DeptNo

101 AAA 1 Ali 101 36 102 BBB 2 Sally 101 ON DELETE/UPDATE SET NULL

CREATE TABLE Department ( PK DeptNo DeptName DeptNo CHAR(3) PRIMARY KEY, AAA DeptName VARCHAR2(20) ); 101 BBB 102 103 CCC CREATE TABLE Employee ( FK

EmpId CHAR(1) PRIMARY KEY, EmpId EmpName DeptNo EmpName VARCHAR2(25), 1 Ali 101 DeptNo CHAR(3) , 2 Sally 101 CONSTRAINT dept_fk FOREIGN KEY (DeptNo) REFERENCES 3 John 103 Department(DeptNo) ON DELETE SET NULL );

 delete from Department where DeptNo=103 Department Employee DeptNo DeptName EmpId EmpName DeptNo 1 Ali 101 101 AAA 2 Sally 101 37 102 BBB 3 John NULL ON DELETE/UPDATE SET Default

CREATE TABLE Department ( PK DeptNo DeptName DeptNo CHAR(3) PRIMARY KEY, AAA DeptName VARCHAR2(20) ); 101 BBB 102 103 CCC CREATE TABLE Employee ( FK

EmpId CHAR(1) PRIMARY KEY, EmpId EmpName DeptNo EmpName VARCHAR2(25), 1 Ali 101 DeptNo CHAR(5) Default ‘Empty’, 2 Sally 101 CONSTRAINT dept_fk FOREIGN KEY (DeptNo) REFERENCES 3 John 103 Department(DeptNo) ON DELETE SET Default);

 delete from Department where DeptNo=103 Department Employee DeptNo DeptName EmpId EmpName DeptNo 1 Ali 101 101 AAA 2 Sally 101 38 102 BBB 3 John Empty Check Constraints

39

 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

Check Constraints

40 Syntax:

create table table-name ( column-name1 datatype CHECK (Check_condition) ) ;

OR

create table table-name ( ……. ……. [CONSTRAINT constraint-name] CHECK (Check_condition) ); Example : Check

41

Create table staff( Column level 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));

Table level

Check Condition Examples 42 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'))

DEFAULT constraint

43

 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:

create table table-name ( column-name1 datatype DEFAULT (Default_value) ); Example: DEFAULT

44

 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' ); Example : All Constraints

45 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));

Summary

46

Constraint Name Type Define it at NOT NULL Simple( single column) Column-level ONLY

Simple ( single column) Column-level or Table-level UNIQUE Composite (on multiple ) columns Table-level ONLY

Simple (single column) Column-level or Table-level PRIMARY KEY Composite (on multiple (columns Table-level ONLY

Simple ( single column) Column-level or Table-level FOREIGN KEY Composite (on multiple) columns Table-level ONLY.

CHECK -- Column-level or Table-level

Defualt -- Column-level ONLY 47 DATA DEFINITION LANGUAGE ( DDL )

Alter Table

48 ALTER TABLE

49

 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.

Data Definition (Creating a table)

50

ALTERING A TABLE Syntax:

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

51

 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).

Example

52 (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);

ALTER TABLE - Delete Column or Constraint

53 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

Use Cascade Constraint

54

 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.

DATA DEFINITION LANGUAGE ( DDL )

Drop Table

55 DROP TABLES

56

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 Drop table table_name; OR Drop table table_name [Cascade Constraints];

 Pay attention to referential integrity constraints when dropping tables.

 If Cascade Constraints is used, the constraints will be dropped first.

Example

57 For example, to remove the PropertyForRent table we use the command:

 DROP TABLE PropertyForRent ;

Example

58 FK PK DeptNo DeptName EmpId EmpName DeptNo 1 Ali 101 101 AAA 2 Sally 101 102 BBB 3 John 103 103 CCC Department Employee

 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.

Viewing Table Structures

59

 To see the structure of a table, type

DESCRIBE table_name; or DESC table_name ;

SQL> describe airlines; 60