You are on page 1of 49

Oracle SQL

CREATING & MANAGING


TABLES AND DATA
CONSTRAINTS
Objectives
2

At the end of this session, you will be able to:

Understand history of SQL

Learn the features of SQL

Understand what are SQL Commands

Use DDL commands

Understand how to Enable, disable constraints

Learn to Create Sequence


Agenda
3

History of SQL
Features of SQL
SQL Commands
DDL commands
Create
Alter
Drop
Truncate

How to Enable, disable constraints


Create Sequence
History of SQL
4

SQL is an ANSI (American National Standards Institute) standard


computer language for accessing and manipulating database
systems

SQL statements are used to retrieve and update data in a database

SQL works with database programs like MS Access, DB2, Informix,


MS SQL Server, Oracle, Sybase, etc.

The first version of SQL was developed at IBM by Donald D.


Chamberlin and Raymond F. Boyce in the early 1970s

This version, initially called SEQUEL, was designed to manipulate


and retrieve data
Features of SQL
5

SQL stands for Structured Query Language

Is a Non-procedural query language

Sometimes referred to as a Database Gateway Language


as ANSI (American National Standards Institute) made it
a standard language for all DBMS

Used for creating, managing, manipulating and querying


the database objects such as tables, views etc.
SQL Commands
6

SQL commands are divided into following categories:

Data Definition Language


CREATE, ALTER, DROP,TRUNCATE

Data Manipulation Language


INSERT, UPDATE, DELETE

Data Query Language


SELECT

Data Control Language


GRANT, REVOKE

Transaction control Language


COMMIT, ROLLBACK, SAVEPOINT
Data Definition Language (DDL)
7

DDL commands are used to


Create database objects such as tables, indexes, views etc. in
the database

Alter/Modify the structure of existing database objects

Drop the existing database objects from the database


CREATE
ALTER
DROP
TRUNCATE
Creating a Table
8

CREATE TABLE tablename


(columnname1 data_type (size)
[constraints],
(columnname2 data_type (size)
[constraints],
);
Defining Database Tables
9

To create a table, you must specify:


Table name

Column names

Column data types

Column sizes

Constraints: restrictions on the data values that a column can


store
Names and Properties: Conventions
10

Series of rules Oracle Corporation established for


naming all database objects:
1. From 1 to 30 characters
2. Only alphanumeric characters, and special characters
($ , _, #)
3. Must begin with a letter and can not contain blank spaces or
hyphens

Are the following names valid? Why?


1. customer order
2. customer-order
3. #order
Data Types
11

Data type
Specifies kind of data that column stores

Provides means for error checking

Enables DBMS to use storage space more efficiently by


internally storing different types of data in different ways
Basic types
Character

Number

Date/time

Large object
Basic Built-in Data Types
12

Character
VARCHAR2 / NVARCHAR2

CHAR / NCHAR

Numeric
NUMBER

DATE
OTHERS
CLOB, BLOB, LONG, RAW, LONG RAW
Constraints
13

A rule that restricts the values that can be inserted into a column
A mechanism used to protect
the relationship between data within an Oracle table, or
the correspondence between data in two different tables

Constraint enforce rules at the table level.


Constraints prevent the deletion of a table if there are dependencies.
The following are the constraint types:
NOT NULL

UNIQUE

PRIMARY KEY

FOREIGN KEY

CHECK
Types of Constraints
14

Integrity constraints: define primary and foreign keys

Value constraints: define specific data values or data


ranges that must be inserted into columns and whether
values must be unique or not NULL

Table constraint: restricts the data value with respect to


all other values in the table

Column constraint: limits the value that can be placed in


a specific column, irrespective of values that exist in
other table records
Defining Constraints
15

CREATE TABLE table


(column datatype [DEFAULT expr] [column_constraint],
.
.
[table_constraint] [,.]);

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));
Integrity Constraints
16

Define Primary Key columns

Specify Foreign Keys and their corresponding table


and column references

Specify Composite Keys


Default Clause
17

Default: specifies a default value that is inserted


automatically

Syntax:
CREATE TABLE <tablename>(column name
datatype DEFAULT <value>);

Example:
CREATE TABLE employee
(empno NUMBER(6) PRIMARY KEY,
ename VARCHAR2(30) NOT NULL,
grade CHAR(3) DEFAULT TG0,
dob DATE, deptno number(2) );
Primary Key Constraints
18

Column-Level: the constraint will be given along with the


column definition. This is required when only one column is
to be made as a primary key
Table-level: this type is used when a compound primary key is
to be created i.e. super key
Properties of primary key:
Value cannot be NULL.
Value should be unique.

Syntax:
CREATE TABLE <table name>
(<Colname> <datatype>[(<size>)] [ [CONSTRAINT
constraint_name] PRIMARY KEY ],
<colname> <datatype>[(<size>)],
. . .);
Primary Key Constraints
19
Column Level Primary Key
20

CREATE TABLE employee


(empno NUMBER(6) CONSTRAINT
emp_empno_pk PRIMARY KEY,
ename VARCHAR2(30),
grade_class CHAR(2),
email varchar2(15),
dob DATE);
Table Level Primary Key Constraint
21

CREATE TABLE employee


(empno NUMBER(6),
ename VARCHAR2(30),
grade CHAR(2),
dob DATE,
CONSTRAINT emp_id_pk PRIMARY KEY
(empno,ename));
Oracle Constraint Naming Convention
22

tablename_ columnname_constraintID
Foreign Key Constraints
23

Can only be defined after column is defined as a primary key in the


parent table

Syntax:
Column level
CREATE TABLE <tablename>(Column name datatype CONSTRAINT
constraint_name
REFERENCES primary_key_table_name (column_name));

Table level
CREATE TABLE table_name
(column1 datatype null/not null, column2
datatype null/not null, ,CONSTRAINT
fk_column
FOREIGN KEY (column1, column2, ... column_n)
REFERENCES parent_table (column1, column2, ...
column_n)
);
Foreign Key Constraints
24

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

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, not
physical, pointers.
Foreign Key Constraints
25
Foreign Key Constraints - Column Level
26

CREATE TABLE dept


(deptno number(2) CONSTRAINT dept_deptno_pk PRIMARY KEY,
dname varchar2(20) NOT NULL,
loc varchar2(10));

CREATE TABLE employee


(empno NUMBER(6) CONTRAINT emp_empno_pk PRIMARY KEY,
ename VARCHAR2(30),
grade CHAR(2),
dob DATE,
deptno number(2) CONSTRAINT employee_deptno_fk
REFERENCES dept(deptno)
ON DELETE CASCADE);

ON DELETE CASCADE option permits deletions of referenced key values


in the parent table and automatically deletes dependent rows in the child
table to maintain referential integrity.
Foreign Key Constraints - Table Level
27

CREATE TABLE dept


( deptno number(2) dept_deptno_pk PRIMARY KEY,
dname varchar2(20) NOT NULL,
loc varchar2(10));

CREATE TABLE employee


(empno NUMBER(6) emp_empno_pk PRIMARY KEY,
ename VARCHAR2(30),
grade CHAR(2),
dob DATE,
deptno number(2), CONSTRAINT
employee_deptno_fk FOREIGN KEY (deptno)
REFERENCES dept(deptno)
);
Types of Value Constraints
28

Check condition: restricts to specific values


Syntax:
CREATE TABLE <table name>(Column name datatype, CHECK
(<condition>);

Example: column level

CREATE TABLE employee


(empno NUMBER(6) PRIMARY KEY
CHECK (empno > 2999), ename VARCHAR2(30),
grade CHAR(2),dob DATE, deptno number(2)
REFERENCES dept(deptno)
);
Check Constraint Example Table Level
29

CREATE TABLE employee


(empno NUMBER(6) PRIMARY KEY,
ename VARCHAR2(30),
grade CHAR(2),dob DATE,deptno
number(2) REFERENCES dept(deptno),
CHECK (empno > 2999 OR dob >= 01-
JAN-1988 );
Types of Value Constraints
30

Not NULL: specifies that a column cannot be empty


NULL is not allowed.

Syntax:
CREATE TABLE <tablename>(column name datatype NOT
NULL);

Example:
CREATE TABLE employee
(empno NUMBER(6) PRIMARY KEY,
ename VARCHAR2(30) NOT NULL,
grade CHAR(2),
dob DATE, deptno number(2) REFERENCES
dept(deptno),CHECK (empno > 2999));
Types of Value Constraints
31

Unique: specifies that a non-primary key column must have a unique value
Can contain a NULL Value
Duplicate is not allowed.

Syntax:
CREATE TABLE <table name>(column name datatype
CONSTRAINT term_term_desc_uk UNIQUE (term_desc));

Example:
CREATE TABLE employee
(empno NUMBER(6) PRIMARY KEY,
ename VARCHAR2(30) NOT NULL,
grade CHAR(2) DEFAULT TG0,
email varchar2(20) constraint em_email UNIQUE,
dob DATE, deptno number(2) REFERENCES
dept(deptno), CHECK (empno > 2999));
Create Table from Another Table
32

Syntax:
CREATE TABLE <tablename>
AS ( Select query);
Example:
CREATE TABLE empcopy
AS (SELECT *
FROM emp
WHERE empno > 1010);
Modifying and Deleting Database Tables
33

Modify existing database tables by


Changing the name of a table

Adding new columns

Deleting columns that are no longer needed

Changing the data type or maximum size of an existing column


ALTER TABLE command
34

ALTER TABLE command is used when


Add a new column
Modify an existing column
Define a default value for the new column
Drop a column
Add or drop a constraint, but not modify its structure
Enable or disable constraints
Add a NOT NULL constraint by using the MODIFY Clause
Renaming and Adding Columns
35

To change the name of a table use RENAME


Syntax
Rename old_tablename to new_tablename;
Example
RENAME employee TO EMP;

To add a column
Syntax
ALTER TABLE tablename ADD(<columnname>
data_declaration [constraints], <columnname>
data_declaration [constraints]);
Example:
ALTER TABLE emp ADD (Hire_date DATE);
New column would be initially NULL for all the rows.
Modifying Existing Column Data Definitions

36

Can only change data type to compatible data type


(i.e. varchar2 to char)
ALTER tablename MODIFY(columnname
new_data_declaration);
Examples
Changing the column width of grade from 2 to 4:
ALTER TABLE employee
MODIFY (grade CHAR(4));

ALTER TABLE employee RENAME COLUMN


email TO email_address;
Deleting a Column
37

Can be used to remove a column from a table


ALTER TABLE tablename DROP COLUMN
columnname;
Examples
ALTER TABLE employee
DROP COLUMN grade;
The column may or may not contain data.
Using the ALTER TABLE statement, only one column can be dropped at a
time.
The table must have at least one column remaining in it after it is altered.
Once a column is dropped, it cannot be recovered.
Deleting and Truncating Tables
38

To delete:
Drop table <tablename>; => DROP TABLE emp;
All data and structure in the table is deleted.
Any pending transactions are committed.
All indexes are dropped.
You cannot roll back the DROP TABLE statement.

Truncate Table <tablename> ; => TRUNCATE TABLE dept;


Removes all rows from a table
Does not delete the structure of the table.
You cannot roll back a TRUNCATE statement
Adding and Deleting Constraints
39

Add a constraint Syntax


ALTER TABLE tablename ADD CONSTRAINT
constraint_name constraint_definition;

Remove a constraint Syntax


ALTER TABLE tablename DROP CONSTRAINT
constraint name;

Examples
ALTER TABLE EMP
ADD CONSTRAINT emp_dept_id_fk
FOREIGN KEY(dept_id)
REFERENCES dept(dept_id);

ALTER TABLE emp


DROP CONSTRAINT emp_ename_uk;
Adding and Deleting Constraints
40

Remove the PRIMARY KEY constraint on the DEPARTMENTS table


and drop the associated FOREIGN KEY constraint on the
EMPLOYEES.DEPARTMENT_ID column.

ALTER TABLE departments


DROP PRIMARY KEY CASCADE;
Enabling and Disabling Constraints
41

When modifying a database it can be useful to disable constraints


Constraints are enabled by default

To disable a constraint:
ALTER TABLE tablename DISABLE CONSTRAINT constraint_name;
To enable a constraint:
ALTER TABLE tablename ENABLE CONSTRAINT constraint_name;

Execute the DISABLE clause of the ALTER TABLE statement to deactivate an


integrity constraint.
Apply the CASCADE option to disable dependent integrity constraints.
ALTER TABLE employees

DISABLE CONSTRAINT emp_emp_id_pk CASCADE;


Examples
42

ALTER TABLE emp


DISABLE CONSTRAINT emp_ename_uk;

ALTER TABLE emp


ENABLE CONSTRAINT emp_ename_uk;
Sequence
43

It is a database object from which users may generate


unique integers
It is used to automatically generate primary key values
When a sequence number is generated, the sequence is
incremented, independent of the transaction committing
or rolling back
Syntax
CREATE SEQUENCE sequence_name
START WITH integer
INCREMENT|DECREMENT BY integer
MAXVALUE integer
MINVALUE integer
CYCLE|NOCYLE
CACHE|NOCACHE;
Sequence
44

Example

CREATE SEQUENCE emp_seq


START WITH 10
INCREMENT BY 1
MAXVALUE 1000
NOCACHE
NOCYCLE;
Sequence
45

Verify your sequence values in the USER_SEQUENCES data dictionary table.


The LAST_NUMBER column displays the next available sequence number if
NOCACHE is specified.
SELECT sequence_name, min_value, max_value, increment_by,
last_number FROM user_sequences;
NEXTVAL returns the next available sequence value. It returns a unique value
every time it is referenced, even for different users.
CURRVAL obtains the current sequence value.
Using a Sequence
46

Insert a new department named Support in location ID 2500.

INSERT INTO departments


(department_id, department_name, location_id)
VALUES
(dept_deptid_seq.NEXTVAL, Support, 2500);

View the current value for the DEPT_DEPTID_SEQ sequence.


SELECT dept_deptid_seq.CURRVAL FROM dual;
Modifying a Sequence
47

Change the increment value, maximum value, minimum value, cycle option, or
cache option.

ALTER SEQUENCE dept_deptid_seq


INCREMENT BY 20
MAXVALUE 999999
NOCACHE
NOCYCLE;
Summary
48

In this session, we covered:

History of SQL

Features of SQL

SQL Commands

DDL commands

How to Enable & Disable constraints

Create Sequence
Thank You

You might also like