Oracle Fundamentals-4

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 193

Client-Server Object/Relational

Database System

Oracle8
Database

• Is a collection of interrelated data.


• E.g. Address book, Telephone directory, Railway train timings
• Manual (Paper-based) database vs. Computerized database
Quiz

• Can you come up with a few examples of databases you use


everyday?
Database Management System (DBMS)

• Is a system that enables the creation, usage and maintenance of a


database.
• E.g. Oracle8, Microsoft SQL Server, Sybase SQL Server, Informix,
DB2, IMS
• Types
• Relational (RDBMS)
• E.g. Oracle7, DB2
• Object-Relational (ORDBMS)
• E.g. Oracle8
• Object-Oriented (OODBMS)
• E.g. CA-Jasmine
• Network (NDBMS)
• E.g. ???
• Hierarchical (HDBMS)
• E.g. IMS
Relational Database

• Is a kind of database in which all information is stored in tables.


• A table contains rows and columns.

EMPLOYEES
EMP_NO NAME JOB HIRE_DATE DEPT_NO MGR_NO SALARY SPEC_ALL
001 Muthukrishnan K. Director 15-APR-1999 01 35500
002 Sridhara Rao Manager 19-APR-1999 02 001 21000 1500
004 Kumar P. Supervisor 03-MAY-1999 03 019 10500
005 Mani S. Tailor 03-MAY-1999 03 004 3500
006 Vasanthi K. Tailor 03-MAY-1999 03 004 3750
009 Venkataraman R. Manager 24-JUN-1999 01 001 14250 750
011 Prabhuram S. Designer 25-JUN-1999 03 019 15700 500
012 Denzil Ashok Sales Executive 12-JUL-1999 02 002 8000 750
014 Raghu M. Sales Executive 12-JUL-1999 02 002 7500 750
015 Subramaniam G. Manager 20-AUG-1999 04 001 13200
016 Ganesh P.R. Clerk 03-SEP-1999 01 009 3000
019 Ramarathnam R.S. Manager 16-OCT-1999 03 001 20450 1250
021 Row
Jayanthi M.S. Tailor Column
22-DEC-1999 03 004 3000
022 Prakash D. Sales Executive 22-DEC-1999 02 002 7500 750
023 Junaid Ismail Tailor 08-JAN-2000 03 004 3500
024 Suryakumar Sales Executive 15-FEB-2000 02 002 7250 500
Rows and Columns

EMPLOYEES
EMP_NO NAME JOB HIRE_DATE DEPT_NO MGR_NO SALARY SPEC_ALL
001 Muthukrishnan K. Director 15-APR-1999 01 35500
002 Sridhara Rao Manager 19-APR-1999 02 001 21000 1500
004 Kumar P. Supervisor 03-MAY-1999 03 019 10500
005 Mani S. Tailor 03-MAY-1999 03 004 3500
006 Vasanthi K. Tailor 03-MAY-1999 03 004 3750
009 Venkataraman R. Manager 24-JUN-1999 01 001 14250 750
011 Prabhuram S. Designer 25-JUN-1999 03 019 15700 500
012 Denzil Ashok Sales Executive 12-JUL-1999 02 002 8000 750
014 Raghu M. Sales Executive 12-JUL-1999 02 002 7500 750
015 Subramaniam G. Manager 20-AUG-1999 04 001 13200
016 Ganesh P.R. Clerk 03-SEP-1999 01 009 3000
019 Ramarathnam R.S. Manager 16-OCT-1999 03 001 20450 1250
A
021 row contains information
Jayanthi M.S. about
Tailorone A column contains
22-DEC-1999 03 one type of
004 information3000
entity - a thing,
022 a person
Prakash D. or anSales
event.
Executive about all entities.
22-DEC-1999 02 002 7500 750
023 Junaid Ismail Tailor 08-JAN-2000 03 004 3500
024 Suryakumar Sales Executive 15-FEB-2000 02 002 7250 500
Tables - Another Example

Table name
Column name

DEPARTMENTS
DEPT_NO NAME HEAD LOCATION
01 Admin/Accounts 001 City Office
02 Sales 002 City Office
03 Production 019 Factory
04 Purchase 015 Factory
Table Relationships

• A table can be related to other tables through related columns


EMPLOYEES
EMP_NO NAME JOB HIRE_DATE DEPT_NO MGR_NO SALARY SPEC_ALL
001 Muthukrishnan K. Director 15-APR-1999 01 35500
002 Sridhara Rao Manager 19-APR-1999 02 001 21000 1500
004 Kumar P. Supervisor 03-MAY-1999 03 019 10500
005 Mani S. Tailor 03-MAY-1999 03 004 3500
006 Vasanthi K. Tailor 03-MAY-1999 03 004 3750
009 Venkataraman R. Manager 24-JUN-1999 01 001 14250 750
011 Prabhuram S. Designer 25-JUN-1999 03 019 15700 500
012 Denzil Ashok Sales Executive 12-JUL-1999 02 002 8000 750
014 Raghu M. Sales Executive 12-JUL-1999 02 002 7500 750
015 Subramaniam G. Manager 20-AUG-1999 04 001 13200
016 Ganesh P.R. Clerk 03-SEP-1999 01 Relationship
009 3000
Prabhuram
019 works
Ramarathnam R.S. Manager 16-OCT-1999 03 001 20450 1250
021for Production
Jayanthi M.S. Tailor DEPARTMENTS
22-DEC-1999 03 004 3000
022 department.
Prakash D. DEPT_NO NAME
Sales Executive 22-DEC-1999 02 HEAD LOCATION
002 7500 750
023 Junaid Ismail Tailor 01 Admin/Accounts
08-JAN-2000 03 001 City
004 Office 3500
024 Suryakumar 02 Sales
Sales Executive 15-FEB-2000 02 002 City
002 Office 7250 500
03 Production 019 Factory
04 Purchase 015 Factory
Relational Database

• A relational database is constituted of many related tables.

SALARY_PAYMENTS

DEPARTMENTS

EMPLOYEES
LOAN_TYPES

LEAVE_TAKEN

LOANS

Relational
Database
Why ‘Relational’?

Why ‘Relational’?
• Not because the tables are ‘related’ - this is a common
misconception.
• Actual reason:
• The database stores and manipulates information in tables.
• Table manipulation is based on a mathematical subject called
‘relational algebra’ (or ‘relational calculus’) where the term
‘relation’ means a table structure.
• Hence the name ‘relational database’.
Structured Query Language (SQL)

• Is an English-like language used to create and query relational


databases.
• E.g. To list the names of all customers, a programmer may write the
following statement in SQL:
select name from customers;
• Has 3 parts:
• Data Definition Language (DDL)
• Data Manipulation Language (DML)
• Data Control Language (DCL) or Transaction Control Language (TCL)
Data Definition Language (DDL)

• Is the subset of SQL that is used to define the data structures (such
as tables, views etc.) in a relational database.

EMPLOYEES
EMP_NO NAME JOB HIRE_DATE DEPT_NO MGR_NO SALARY SPEC_ALL

DEPARTMENTS
DEPT_NO NAME HEAD LOCATION

Data structures
Data Manipulation Language (DML)

• Is the subset of SQL that is used to create, modify and delete data in
the tables.

EMPLOYEES
EMP_NO NAME JOB HIRE_DATE DEPT_NO MGR_NO SALARY SPEC_ALL
001 Muthukrishnan K. Director 15-APR-1999 01 35500
002 Sridhara Rao Manager 19-APR-1999 02 001 21000 1500
004 Kumar P. Supervisor 03-MAY-1999 03 019 10500
005 Mani S. Tailor 03-MAY-1999 03 004 3500

DEPARTMENTS
Data DEPT_NO NAME HEAD LOCATION
01 Admin/Accounts 001 City Office
02 Sales 002 City Office
03 Production 019 Factory
04 Purchase 015 Factory
Data Control Language (DCL)

• Is the subset of SQL that is used to perform transactions and control


user access to the database.

Databas
e
Data type

• Is the definition of the kind of data that a column can hold.

NAME holds text values HIRE_DATE holds date values SALARY holds numeric values

EMPLOYEES
EMP_NO NAME JOB HIRE_DATE DEPT_NO MGR_NO SALARY SPEC_ALL
001 Muthukrishnan K. Director 15-APR-1999 01 35500
002 Sridhara Rao Manager 19-APR-1999 02 001 21000 1500
004 Kumar P. Supervisor 03-MAY-1999 03 019 10500
005 Mani S. Tailor 03-MAY-1999 03 004 3500

• Data type also determines the kind of operations that can take place
on the column values.
• E.g. Numbers can be added but dates cannot be added; Text values can be
converted to upper case while numbers cannot be.
Quiz

• What data types do you come across in your everyday life?


Data types in Oracle8

• Number
• Varchar2
• Date
• Char
• Others
• Varchar
• Long
• Raw
• Long Raw
Primary Key

• In order to process any row, we first need to identify (or point out)
the row. E.g.
• To process the salary of a particular employee, we first need to mention which
employee it is.
• For instance, we may say ‘Kumar P.’ or we may say EMP_NO ‘004’.
• This column (EMP_NO) is called the ‘primary key’ of the EMPLOYEES table.

EMP_NO ‘004’ uniquely identifies a row.


Hence EMP_NO is the Primary Key.

EMPLOYEES
EMP_NO NAME JOB HIRE_DATE DEPT_NO MGR_NO SALARY SPEC_ALL
001 Muthukrishnan K. Director 15-APR-1999 01 35500
002 Sridhara Rao Manager 19-APR-1999 02 001 21000 1500
004 Kumar P. Supervisor 03-MAY-1999 03 019 10500
005 Mani S. Tailor 03-MAY-1999 03 004 3500

• Definition: The primary key of a table is that column (or set of


columns) which uniquely identifies a row in the table.
Composite Primary Key

• Sometimes a single column may not be sufficient to uniquely identify


a row. E.g.
• In the SALARY_PAYMENTS table, EMP_NO is not unique because
the same employee receives salaries for many months.
• Hence both EMP_NO and MONTH are required to uniquely identify a
row.
• Such a primary key is called a composite primary key.

SALARY_PAYMENTS
EMP_NO MONTH SALARY
001 APR 99 17750
002 APR 99 7000
… … …
001 MAY 99 35500
002 MAY 99 21000
… … … Composite primary key

• Definition: A composite primary key is a primary key that is


constituted of 2 or more columns.
Composite Primary Key - Common Mistake

This table has 2 primary keys!!!

If a primary key has 2 columns, many developers are


used to saying that the table has 2 primary keys. That
is an incorrect usage. A table can have only one
primary key; but the primary key may be constituted
of one or more columns.
Null

• ‘Null’ means ‘no value’.


• A ‘null column’ is one that can accept ‘null’ as a valid input.
• A ‘not-null column’ will expect a non-null valid value.

No nulls here! Nulls allowed here!

EMPLOYEES
EMP_NO NAME JOB HIRE_DATE DEPT_NO MGR_NO SALARY SPEC_ALL
001 Muthukrishnan K. Director 15-APR-1999 01 35500
002 Sridhara Rao Manager 19-APR-1999 02 001 21000 1500
004 Kumar P. Supervisor 03-MAY-1999 03 019 10500
005 Mani S. Tailor 03-MAY-1999 03 004 3500
More on Null

• ‘Null’ can connote ‘not applicable’ or ‘not known’.


• It is different from the idea of 0 (zero) or nothingness.
• While ‘0’ is an affirmation of nothingness, ‘null’ signifies the absence
of affirmation.

Null is different from 0 (zero) in a numeric context. E.g.


Column Value Meaning
SPEC_ALL Null Not applicable to the employee.
0 Determined to be Rs.0 for the employee.

Null is different from ‘’ (blank string) in a string context. E.g.


Column Value Meaning
MGR_NO Null Employee does not have a manager.
'' Employee has a manager identified as ‘’.

Null is different from ‘false’ in a boolean context. E.g.


Column Value Meaning
ALIVE Null We don't know if employee is alive.
'F' Employee is not alive.
More on Null

• An expression with a null in it evaluates to null. E.g.


• 5 + null = null (Contrast with 5 + 0 = 5)
• In Oracle8, the default assumption for a column is NULL (unless
explicitly stated otherwise as NOT NULL).

Nulls as Zeroes

If null should be treated as 0, that is, if we want


5 + null to be 5 rather that null, then we should
use a function called NVL. More on this later!
Primary Keys and Nulls

• Primary key columns can not contain nulls.


• Non-primary key columns may be NULL or NOT NULL columns.
Creating a table

• Need: To create the EMPLOYEES table.


• Solution: Use the create table (SQL DDL) statement:

create table EMPLOYEES


(EMP_NO varchar2(3) not null primary key,
NAME varchar2(25) not null,
JOB varchar2(20) not null,
HIRE_DATE date not null,
Table name DEPT_NO varchar2(2),
MGR_NO varchar2(3), Constraints
SALARY number(10) not null,
SPEC_ALL number(10));

Columns Data types


Constraint

• A constraint is a developer-defined rule that the DBMS promises to


maintain.
• Constraints help in maintaining the integrity of the database.
• Types
• NULL constraint
• PRIMARY KEY constraint
• Others we will see shortly
Implications for the Developer
• FOREIGN KEY constraint
• Pro
• UNIQUE constraint
• Less work on the application
• CHECK constraint side
• More data integrity
• Con
• Slightly more time for data
inserts and updates
Specifying Constraints

• Two ways to specify constraints


• as part of the column definition - called ‘column constraint’
• at the end of the CREATE TABLE statement - called ‘table constraint’

create table EMPLOYEES Column constraint


(EMP_NO varchar2(3) not null primary key,
NAME varchar2(25) not null,
JOB varchar2(20) not null,
HIRE_DATE date not null,
DEPT_NO varchar2(2),
MGR_NO varchar2(3), create table EMPLOYEES
SALARY number(10) not null, (EMP_NO varchar2(3) not null,
SPEC_ALL number(10)); NAME varchar2(25) not null,
JOB varchar2(20) not null,
HIRE_DATE date not null,
DEPT_NO varchar2(2),
MGR_NO varchar2(3),
SALARY number(10) not null,
Table constraint SPEC_ALL number(10),
primary key (EMP_NO));
Table Constraints

• Constraints with multiple columns have to be table constraints:

create table SALARY_PAYMENTS


(EMP_NO varchar2(3) not null,
MONTH date not null,
SALARY number(10) not null,
primary key (EMP_NO, MONTH));

Multiple columns in a constraint


Sidetrack: SQL*Plus

• Is a client-side tool to connect to an Oracle database and execute


SQL statements.
• Steps
• Execute SQL*Plus.
• Connect to the database with valid username and password.
• Execute SQL statements.
• Exit SQL*Plus.
Inserting data into tables

• Need: To enter data about employees in the EMPLOYEES table.


• Solution: Use the insert (SQL DML) statement:

insert into EMPLOYEES values (‘001’, ‘Muthukrishnan


K.’, ‘Director’, ‘15-APR-99’, NULL, NULL, 35500, NULL);

Numbers are entered literally

Text strings are entered in single quotes

Dates are entered in single quotes

NULL is entered literally


Inserting dates

• A date value should be entered


• within single quotes
• in the default format (DD-MON-YY)
• E.g. ‘15-APR-99’
• If the format of the date value needs to be different, use the
TO_DATE function with a formatting mask:

insert into EMPLOYEES values (‘001’, ‘Muthukrishnan


K.’, ‘Director’, TO_DATE(‘15-APR-1999’, ‘DD-MON-YYYY’),
NULL, NULL, 35500, NULL);

Formatting mask
Inserting values for only some columns

• Sometimes there is a need to insert values for only some columns.


• E.g. A table has 10 columns out of which 7 are null columns. We wish
to insert a row with the values of 4 columns and leave the remaining 6
null.
• In such cases, list the relevant columns alone in the insert
statement:
insert into EMPLOYEES (EMP_NO, NAME, JOB, HIRE_DATE,
SALARY) values (‘001’, ‘Muthukrishnan K.’, ‘Director’,
TO_DATE(‘15-APR-1999’, ‘DD-MON-YYYY’), 35500);

• For all non-listed columns, NULL will be inserted automatically.


• The non-listed columns should have been defined as NULL columns.
Next Step: Inserting other rows in the EMPLOYEES table

insert into EMPLOYEES values (‘002’, ‘Sridhara Rao’,


‘Manager’, ‘19-APR-99’, NULL, ‘001’, 21000, 1500);
Next Step: Insert DML for the EMPLOYEES table

INSERT INTO EMPLOYEES VALUES ('001', 'Muthukrishnan K.', 'Director', TO_DATE('15-APR-1999', 'DD-MON-YYYY'), '01',
NULL, 35500, NULL);
INSERT INTO EMPLOYEES VALUES ('002', 'Sridhara Rao', 'Manager', TO_DATE('19-APR-1999', 'DD-MON-YYYY'), '02',
'001', 21000, 1500);
INSERT INTO EMPLOYEES VALUES ('004', 'Kumar P.', 'Supervisor', TO_DATE('03-MAY-1999', 'DD-MON-YYYY'), '03',
'019', 10500, NULL);
INSERT INTO EMPLOYEES VALUES ('005', 'Mani S.', 'Tailor', TO_DATE('03-MAY-1999', 'DD-MON-YYYY'), '03', '004',
3500, NULL);
INSERT INTO EMPLOYEES VALUES ('006', 'Vasanthi K.', 'Tailor', TO_DATE('03-MAY-1999', 'DD-MON-YYYY'), '03', '004',
3750, NULL);
INSERT INTO EMPLOYEES VALUES ('009', 'Venkataraman R.', 'Manager', TO_DATE('24-JUN-1999', 'DD-MON-YYYY'), '01',
'001', 14250, 750);
INSERT INTO EMPLOYEES VALUES ('011', 'Prabhuram S.', 'Designer', TO_DATE('25-JUN-1999', 'DD-MON-YYYY'), '03',
insert into EMPLOYEES values (‘002’, ‘Sridhara Rao’,
'019', 15700, 500);
INSERT INTO EMPLOYEES VALUES
('012', 'Denzil Ashok', 'Sales Executive', TO_DATE('12-JUL-1999', 'DD-MON-YYYY'),
‘Manager’, ‘19-APR-99’,
'02', '002', 8000, 750); NULL, ‘001’, 21000, 1500);
INSERT INTO EMPLOYEES VALUES ('014', 'Raghu M.', 'Sales Executive', TO_DATE('12-JUL-1999', 'DD-MON-YYYY'), '02',
'002', 7500, 750);
INSERT INTO EMPLOYEES VALUES ('015', 'Subramaniam G.', 'Manager', TO_DATE('20-AUG-1999', 'DD-MON-YYYY'), '04',
'001', 13200, NULL);
INSERT INTO EMPLOYEES VALUES ('016', 'Ganesh P.R.', 'Clerk', TO_DATE('03-SEP-1999', 'DD-MON-YYYY'), '01', '009',
3000, NULL);
INSERT INTO EMPLOYEES VALUES ('019', 'Ramarathnam R.S.', 'Manager', TO_DATE('16-OCT-1999', 'DD-MON-YYYY'), '03',
'001', 20450, 1250);
INSERT INTO EMPLOYEES VALUES ('021', 'Jayanthi M.S.', 'Tailor', TO_DATE('22-DEC-1999', 'DD-MON-YYYY'), '03',
'004', 3000, NULL);
INSERT INTO EMPLOYEES VALUES ('022', 'Prakash D.', 'Sales Executive', TO_DATE('22-DEC-1999', 'DD-MON-YYYY'),
'02', '002', 7500, 750);
INSERT INTO EMPLOYEES VALUES ('023', 'Junaid Ismail', 'Tailor', TO_DATE('08-JAN-2000', 'DD-MON-YYYY'), '03',
'004', 3500, NULL);
INSERT INTO EMPLOYEES VALUES ('024', 'Suryakumar', 'Sales Executive', TO_DATE('15-FEB-2000', 'DD-MON-YYYY'),
'02', '002', 7250, 500);
Seeing the rows

• Need: To see the rows in the EMPLOYEES table.


• Solution: Use the SELECT (SQL DML) statement.

select * from
EMPLOYEES;

Meaning:
Show
all columns
from
this table.

More on Select statement later


Next Step: Creating DEPARTMENTS table

• Use CREATE TABLE (SQL DDL) again:

create table DEPARTMENTS


(DEPT_NO varchar2(2) not null primary key,
NAME varchar2(25) not null,
HEAD varchar2(3),
LOCATION varchar2(25));
Next Step: Insert rows into the DEPARTMENTS table

insert into DEPARTMENTS values ('01', 'Accounts/Admin',


NULL, 'City Office');
Insert DML for the DEPARTMENTS table

insert into DEPARTMENTS values ('01', 'Accounts/Admin', '001', 'City Office');


insert into DEPARTMENTS values ('02', 'Sales', '002', 'City Office');
insert into DEPARTMENTS values ('03', 'Production', '019', 'Factory');
insert into DEPARTMENTS values ('04', 'Purchase', '015', 'Factory');
Foreign Key

• Often a row in a table may need to make a reference to a row in


another table. E.g.
• In Patanjali Garments, Muthukrishnan works for the Accounts/Admin
department.
• Hence the ‘Muthukrishnan’ row in the EMPLOYEES table needs to
make a reference to the ‘Accounts/Admin’ row in the
DEPARTMENTS table.
• That is done with the DEPT_NO column in the EMPLOYEES table
which refers the primary key column (DEPT_NO) of the
DEPARTMENTS table.
• Such a reference is called the ‘foreign key’.
• Definition: A foreign key is a column (or set of columns) that refers
the primary key column (or set of columns) of another table.
Foreign Key

Primary Key of
EMPLOYEES table Foreign Key referring
DEPARTMENTS table
EMPLOYEES
EMP_NO NAME JOB HIRE_DATE DEPT_NO MGR_NO SALARY SPEC_ALL
001 Muthukrishnan K. Director 15-APR-1999 01 35500
002 Sridhara Rao Manager 19-APR-1999 02 001 21000 1500
004 Kumar P. Supervisor 03-MAY-1999 03 019 10500
005 Mani S. Tailor 03-MAY-1999 03 004 3500

Muthukrishnan K. works for Admin/Accounts.

Primary Key of DEPARTMENTS


DEPARTMENTS table DEPT_NO NAME HEAD LOCATION
01 Admin/Accounts 001 City Office
02 Sales 002 City Office
03 Production 019 Factory
04 Purchase 015 Factory
Foreign Key Constraint

• …ensures that a value entered in a foreign key column corresponds to a


value in the primary key column of the related table.
• Also called ‘referential integrity constraint’.
• Referential integrity means ‘correctness of reference’.
Violates referential integrity!
Foreign Key Constraint will
reject this data!
EMPLOYEES
EMP_NO NAME JOB HIRE_DATE DEPT_NO MGR_NO SALARY SPEC_ALL
001 Muthukrishnan K. Director 15-APR-1999 01 35500
002 Sridhara Rao Manager 19-APR-1999 02 001 21000 1500
004 Kumar P. Supervisor 03-MAY-1999 03
05 019 10500
005 Mani S. Tailor 03-MAY-1999 03 004 3500

DEPARTMENTS
DEPT_NO NAME HEAD LOCATION
01 Admin/Accounts 001 City Office
02 Sales 002 City Office
03 Production 019 Factory
04 Purchase 015 Factory
?
Tables, Primary Keys and Foreign Keys - Relationship

• A table can have only one primary key.


• A table can have zero or more foreign keys.
Composite Foreign Key

• Is a foreign key that is constituted of 2 or more columns.


• A composite foreign key will refer a composite primary key.
Foreign Keys and Nulls

• A foreign key column can contain nulls. E.g.


• In Patanjali Garments, an employee may temporarily not be assigned
any department. So the DEPT_NO column for the employee’s row will
be null.
EMPLOYEES
EMP_NO NAME JOB HIRE_DATE DEPT_NO MGR_NO SALARY SPEC_ALL
001 Muthukrishnan K. Director 15-APR-1999 01 35500
002 Sridhara Rao Manager 19-APR-1999 02 001 21000 1500
004 Kumar P. Supervisor 03-MAY-1999 03 019 10500
005 Mani S. Tailor 03-MAY-1999 03 004 3500

Mani has not been assigned any


department - An example of how
a foreign key column can be null.

• Whether a foreign key column can accept nulls or not is determined


by the user’s requirements.
Self-referring Foreign Keys

• A foreign key in a table can refer to (the primary key of) the same
table itself.

Primary Key of MGR_NO of EMPLOYEES refers


EMPLOYEES table Foreign Key referring
EMP_NO of EMPLOYEES EMPLOYEES table

EMPLOYEES
EMP_NO NAME JOB HIRE_DATE DEPT_NO MGR_NO SALARY SPEC_ALL
001 Muthukrishnan K. Director 15-APR-1999 01 35500
002 Sridhara Rao Manager 19-APR-1999 02 001 21000 1500
004 Kumar P. Supervisor 03-MAY-1999 03 019 10500
005 Mani S. Tailor 03-MAY-1999 03 004 3500

Sridhara Rao reports to Muthukrishnan K.


Quiz

• Can you think of some other foreign key that refers its own table?
• Are such self-referring tables common or rare?
Foreign Keys in EMPLOYEES table

Primary Key of Foreign Key referring Foreign Key referring


EMPLOYEES table DEPARTMENTS table EMPLOYEES table

EMPLOYEES
EMP_NO NAME JOB HIRE_DATE DEPT_NO MGR_NO SALARY SPEC_ALL
001 Muthukrishnan K. Director 15-APR-1999 01 35500
002 Sridhara Rao Manager 19-APR-1999 02 001 21000 1500
004 Kumar P. Supervisor 03-MAY-1999 03 019 10500
005 Mani S. Tailor 03-MAY-1999 03 004 3500

Primary Key of DEPARTMENTS


DEPARTMENTS table DEPT_NO NAME HEAD LOCATION
01 Admin/Accounts 001 City Office
02 Sales 002 City Office
03 Production 019 Factory
04 Purchase 015 Factory
Quiz

• What do you think will happen if the ‘Admin/Account’ row was


deleted from the DEPARTMENTS table?
Foreign Keys in DEPARTMENTS table

Primary Key of
EMPLOYEES table

EMPLOYEES
EMP_NO NAME JOB HIRE_DATE DEPT_NO MGR_NO SALARY SPEC_ALL
001 Muthukrishnan K. Director 15-APR-1999 01 35500
002 Sridhara Rao Manager 19-APR-1999 02 001 21000 1500
004 Kumar P. Supervisor 03-MAY-1999 03 019 10500
005 Mani S. Tailor 03-MAY-1999 03 004 3500

Foreign Key referring


EMPLOYEES table

Primary Key of DEPARTMENTS


DEPARTMENTS table DEPT_NO NAME HEAD LOCATION
01 Admin/Accounts 001 City Office
02 Sales 002 City Office
03 Production 019 Factory
04 Purchase 015 Factory
Creating a Foreign Key Constraint

• Use the ‘REFERENCES’ clause in the CREATE TABLE statement.

create table EMPLOYEES


(EMP_NO varchar2(3) not null primary key,
NAME varchar2(25) not null,
JOB varchar2(20) not null,
HIRE_DATE date not null,
DEPT_NO varchar2(2) references DEPARTMENTS(DEPT_NO),
MGR_NO varchar2(3) references EMPLOYEES(EMP_NO),
SALARY number(10) not null,
SPEC_ALL number(10));

Foreign Key Constraint specified


as a column constraint

Note: The referenced table should exist in


the database before the foreign key
constraint can created. Otherwise the SQL
statement will not execute.
Foreign Key Constraint as Table Constraint

• A foreign key constraint can also be specified as a table constraint.

create table EMPLOYEES


(EMP_NO varchar2(3) not null primary key,
NAME varchar2(25) not null,
JOB varchar2(20) not null,
HIRE_DATE date not null,
DEPT_NO varchar2(2),
MGR_NO varchar2(3),
SALARY number(10) not null,
SPEC_ALL number(10),
foreign key (DEPT_NO) references DEPARTMENTS(DEPT_NO),
foreign key (MGR_NO) references EMPLOYEES(EMP_NO);

Foreign Key Constraint specified


as a table constraint
Foreign Key Constraint - Trivia

• The name of the primary key column can be left out in the constraint
definition if it matches the name of the foreign key column.
• Applies to both column constraints and table constraints.

create table EMPLOYEES


(EMP_NO varchar2(3) not null primary key,
NAME varchar2(25) not null,
JOB varchar2(20) not null,
HIRE_DATE date not null,
DEPT_NO varchar2(2),
MGR_NO varchar2(3),
SALARY number(10) not null,
SPEC_ALL number(10),
foreign key (DEPT_NO) references DEPARTMENTS,
foreign key (MGR_NO) references EMPLOYEES(EMP_NO);

Primary key column name left out Not so here because the primary key
because it matches foreign key column name (EMP_NO) does not match
column name (DEPT_NO). foreign key column name (MGR_NO).
Next Step: Creating the Foreign Keys for DEPARTMENTS table

• SQL DDL with foreign key constraint for DEPARTMENTS table:

create table DEPARTMENTS


(DEPT_NO varchar2(2) not null primary key,
NAME varchar2(25) not null,
HEAD varchar2(3) references EMPLOYEES(EMP_NO),
LOCATION varchar2(25));
Quiz

• Do you find something intriguing in the following set of SQL


statements?
create table EMPLOYEES
(EMP_NO varchar2(3) not null primary key,
NAME varchar2(25) not null,
JOB varchar2(20) not null,
HIRE_DATE date not null,
DEPT_NO varchar2(2) references
DEPARTMENTS(DEPT_NO),
MGR_NO varchar2(3) references EMPLOYEES(EMP_NO),
SALARY number(10) not null,
SPEC_ALL
create number(10));
table DEPARTMENTS
(DEPT_NO varchar2(2) not null primary key,
NAME varchar2(25) not null,
HEAD varchar2(3) references EMPLOYEES(EMP_NO),
LOCATION varchar2(25));

• What do you think will happen if the above statements were


executed?
Quiz

• What will happen if the order of the SQL statements was changed?

create table DEPARTMENTS


(DEPT_NO varchar2(2) not null primary key,
NAME varchar2(25) not null,
HEAD varchar2(3) references EMPLOYEES(EMP_NO),
LOCATION varchar2(25));
create table EMPLOYEES
(EMP_NO varchar2(3) not null primary key,
NAME varchar2(25) not null,
JOB varchar2(20) not null,
HIRE_DATE date not null,
DEPT_NO varchar2(2) references
DEPARTMENTS(DEPT_NO),
MGR_NO varchar2(3) references EMPLOYEES(EMP_NO),
SALARY number(10) not null,
SPEC_ALL number(10));
Quiz

• How do you think such mutually referring tables can be created?


• Are mutually referring tables common or rare? Can you give some
other examples of mutually referring tables?
• What do you think will happen to the rows in the EMPLOYEES
table if the ‘Admin/Accounts’ row in the DEPARTMENTS table
was deleted?
Unique Constraint

• Sometimes there is a need to ensure that a column does not have any
duplicate values. E.g.
• No two departments in Patanjali Garments can have the same name.

DEPARTMENTS
DEPT_NO NAME HEAD LOCATION
01 Admin/Accounts 001 City Office
02 Sales 002 City Office
03 Production 019 Factory
04 Purchase 015 Factory

The names of departments have to be unique.

• In such cases, we specify a ‘unique constraint.’


• Definition: A unique constraint ensures that a column (or a set of
columns) contains unique values, i.e., the column does not contain
duplicates.
Unique Constraint - Clause in SQL

create table DEPARTMENTS


(DEPT_NO varchar2(2) not null primary key,
NAME varchar2(25) not null unique,
HEAD varchar2(3) references EMPLOYEES(EMP_NO),
LOCATION varchar2(25));

Unique constraint in column constraint form

create table DEPARTMENTS


(DEPT_NO varchar2(2) not null primary key,
NAME varchar2(25) not null,
HEAD varchar2(3) references EMPLOYEES(EMP_NO),
LOCATION varchar2(25),
unique (NAME));
Unique constraint in table constraint form
Quiz

• Given that both primary key constraint and unique constraint


ensures uniqueness of a column’s values, how are they different?
Primary Key Constraint vs. Unique Constraint

Primary Key Constraint Unique Key Constraint


Primary Purpose To uniquely identify a row for To ensure that the column does
processing. not have duplicate values.
Nulls Does not permit nulls. Permits nulls.
No. of constraints One table can have only one One table can have 0 or more
per table primary key constraint. unique key constraints.

• A primary key constraint, by itself, enforces uniqueness.


• Hence the primary key column should not be constrained again with a
unique constraint.
Check Constraint

• Many columns must have values that are within a certain range or
that satisfy certain conditions. E.g.
• The salary of an employee has to be greater than 0.
• The hire date of an employee has to be later than 15-APR-1999, the
date when the organization was started.

EMPLOYEES
EMP_NO NAME JOB HIRE_DATE DEPT_NO MGR_NO SALARY SPEC_ALL
001 Muthukrishnan K. Director 15-APR-1999 01 35500
002 Sridhara Rao Manager 19-APR-1999 02 001 21000 1500
004 Kumar P. Supervisor 03-MAY-1999 03 019 10500
005 Mani S. Tailor 03-MAY-1999 03 004 3500

Salary has to be greater than 0.

• Such conditions can be enforced with a ‘check constraint’.


• Definition: A check constraint ensures that a column (or a set of
columns) satisfies certain conditions.
Check Constraint - Clause in SQL

create table EMPLOYEES


(EMP_NO varchar2(3) not null primary key,
NAME varchar2(25) not null,
JOB varchar2(20) not null,
HIRE_DATE date not null check (HIRE_DATE > ‘15-APR-99’),
DEPT_NO varchar2(2) references DEPARTMENTS(DEPT_NO),
MGR_NO varchar2(3) references EMPLOYEES(EMP_NO),
SALARY number(10) not null check (SALARY > 0),
SPEC_ALL number(10));
Check constraints in column constraint form
create table EMPLOYEES
(EMP_NO varchar2(3) not null primary key,
NAME varchar2(25) not null,
JOB varchar2(20) not null,
HIRE_DATE date not null,
DEPT_NO varchar2(2) references DEPARTMENTS(DEPT_NO),
MGR_NO varchar2(3) references EMPLOYEES(EMP_NO),
SALARY number(10) not null,
SPEC_ALL number(10), Check constraints in table constraint form
check (HIRE_DATE > ‘15-APR-99’),
check (SALARY > 0));
Constraints - Summary

Constraint Purpose Other characteristics


Not Null Constraint To ensure that a column does not
have a null value.
Primary Key Constraint To uniquely identify a row for Ensures uniqueness of values.
processing. Does not permit nulls.
Foreign Key Constraint To enforce referential integrity Permits nulls.
across table references.
Unique Key Constraint To ensure that a column does not Permits nulls.
have duplicate values.
Check Constraint To ensure that a column satisfies
certain conditions.

More on constraints later


Quiz

• How do constraints help a developer?


• In the absence of constraints, what should the developer do to
accomplish the same tasks?
Altering a Table

• Sometimes we may need to alter a table structure


• to add a new column
• to modify an existing column
• Use the alter table (SQL DDL) statement.
Adding a New Column

• Need: To add a REMARKS column to the EMPLOYEES table.


(Note that REMARKS can be null).
• Solution:
alter table EMPLOYEES add
(REMARKS varchar2(200));
Adding a New Column - Quiz

• Need: To add a BIRTH_DATE column to the EMPLOYEES table.


(Note that BIRTH_DATE cannot be null).
• Solution:
alter table EMPLOYEES add
(BIRTH_DATE date not null);

• When the above statement is executed, do you think there will be a


problem? What is it?
Adding a New Column

• BIRTH_DATE is specified as NOT NULL.


• But for existing rows, the new column’s value will have to be null.
• Hence the statement won’t execute.
• Solution:
• Will see later.
Modifying an Existing Column

• Need: To enlarge an existing column. E.g.


• Enlarge the NAME column of the EMPLOYEES table from 25 to 30
characters.
• Solution:
alter table EMPLOYEES modify
(NAME varchar2(30) not null);

• Need: To change the NULL constraint status of a column. E.g.


• Permit the JOB column to contain nulls.
• Solution:
alter table EMPLOYEES modify
(JOB varchar2(20) null);
Modifying an Existing Column - More

• Need: To change the data type of a column. E.g.


• To change the data type of REMARKS from varchar2 to long.
• Solution:
alter table EMPLOYEES modify
(REMARKS long);

Changing a data type is permissible only if the


column value is NULL for all rows.
Revisit: Adding a New NOT NULL Column

• Need: To add a NOT NULL BIRTH_DATE column to the


EMPLOYEES table.
• Solution:
• First create the column without the NOT NULL constraint:
alter table EMPLOYEES add
(BIRTH_DATE date);
• Fill the birth dates for all rows.
• Then modify the row with a NOT NULL constraint.
alter table EMPLOYEES modify
(BIRTH_DATE date not null);
Rules for Altering a Table

• Adding a column • Modifying a column


• You may add a NULL column • You can increase the size of a
anytime. varchar2, char or number column
• You may add a NOT NULL anytime.
column only if the table is empty. • You can decrease the size of a
• To add a NOT NULL column varchar2, char or number column
even if the table contains rows: only if the column is NULL for all
• Add the column without rows.
specifying NOT NULL.
• You can increase or decrease the
• Fill the column values for all
rows.
number of digits in a number
• Modify the column to be NOT anytime.
NULL. • You can change the datatype of a
column only if the column is
NULL for all rows.
• You can change from NOT
NULL to NULL anytime.
• You can change from NULL to
NOT NULL only if there are no
nulls in the column currently.
Patanjali Garments - SQL DDL as of now - Problem

create table EMPLOYEES


(EMP_NO varchar2(3) not null primary key,
NAME varchar2(25) not null,
JOB varchar2(20) not null,
HIRE_DATE date not null check (HIRE_DATE > ‘15-APR-99’),
DEPT_NO varchar2(2) references DEPARTMENTS(DEPT_NO),
MGR_NO varchar2(3) references EMPLOYEES(EMP_NO),
SALARY number(10) not null check (SALARY > 0),
SPEC_ALL number(10));
create table DEPARTMENTS
(DEPT_NO varchar2(2) not null primary key,
NAME varchar2(25) not null unique,
HEAD varchar2(3) references EMPLOYEES(EMP_NO),
LOCATION varchar2(25));

Mutually referring tables.


This SQL cannot execute!
Mutually Referring Tables - Solution 1

• Steps
• Let only one the latter table have a foreign key reference to the former table.
• Then ALTER the former table to include the foreign key reference to the latter
table.
create table EMPLOYEES
(EMP_NO varchar2(3) not null primary key,
NAME varchar2(25) not null,
JOB varchar2(20) not null,
HIRE_DATE date not null check (HIRE_DATE > ‘15-APR-99’),
DEPT_NO varchar2(2),
MGR_NO varchar2(3) references EMPLOYEES(EMP_NO),
SALARY number(10) not null check (SALARY > 0),
SPEC_ALL number(10));
create table DEPARTMENTS
(DEPT_NO varchar2(2) not null primary key,
NAME varchar2(25) not null unique,
HEAD varchar2(3) references EMPLOYEES(EMP_NO),
LOCATION varchar2(25));
alter table EMPLOYEES add
(foreign key (DEPT_NO) references DEPARTMENTS(DEPT_NO));
Mutually Referring Tables - Solution 2
• Steps
• Let table definitions have no foreign key references.
• After all table definitions, alter the tables to include all foreign key references.
• Ideal solution/ Also professional practice
create table EMPLOYEES
(EMP_NO varchar2(3) not null primary key,
NAME varchar2(25) not null,
JOB varchar2(20) not null,
HIRE_DATE date not null check (HIRE_DATE > ‘15-APR-99’),
DEPT_NO varchar2(2),
MGR_NO varchar2(3),
SALARY number(10) not null check (SALARY > 0),
SPEC_ALL number(10));
create table DEPARTMENTS
(DEPT_NO varchar2(2) not null primary key,
NAME varchar2(25) not null unique,
HEAD varchar2(3),
LOCATION varchar2(25));
alter table EMPLOYEES add
(foreign key (DEPT_NO) references DEPARTMENTS(DEPT_NO),
foreign_key (MGR_NO) references EMPLOYEES(EMP_NO));
alter table DEPARTMENTS add
(foreign key (HEAD) references EMPLOYEES(EMP_NO));
Seeing the Rows

• Need: To see the rows in the EMPLOYEES table.


• Solution: Use the SELECT (SQL DML) statement.

select * from
EMPLOYEES;

Meaning:
Show
all columns
from
this table.
Select: Entire table

• Need: To see all the column details of all the rows in a table.
• See all the details of all the employees.
• Solution:
select * from
EMPLOYEES;
EMP_NO NAME JOB HIRE_DATE DEPT_NO MGR_NO SALARY SPEC_ALL
001 Muthukrishnan K. Director 15-APR-1999 01 35500
002 Sridhara Rao Manager 19-APR-1999 02 001 21000 1500
004 Kumar P. Supervisor 03-MAY-1999 03 019 10500
005 Mani S. Tailor 03-MAY-1999 03 004 3500
006 Vasanthi K. Tailor 03-MAY-1999 03 004 3750
009 Venkataraman R. Manager 24-JUN-1999 01 001 14250 750
011 Prabhuram S. Designer 25-JUN-1999 03 019 15700 500
012 Denzil Ashok Sales Executive 12-JUL-1999 02 002 8000 750
014 Raghu M. Sales Executive 12-JUL-1999 02 002 7500 750
015 Subramaniam G. Manager 20-AUG-1999 04 001 13200
016 Ganesh P.R. Clerk 03-SEP-1999 01 009 3000
019 Ramarathnam R.S. Manager 16-OCT-1999 03 001 20450 1250
021 Jayanthi M.S. Tailor 22-DEC-1999 03 004 3000
022 Prakash D. Sales Executive 22-DEC-1999 02 002 7500 750
023 Junaid Ismail Tailor 08-JAN-2000 03 004 3500
024 Suryakumar Sales Executive 15-FEB-2000 02 002 7250 500
Select: One column

• Need: To see only one column in a table.


• See the names of all employees.
• Solution:
select NAME from EMPLOYEES;
EMP_NO NAME JOB HIRE_DATE DEPT_NO MGR_NO SALARY SPEC_ALL
001 Muthukrishnan K. Director 15-APR-1999 01 35500
002 Sridhara Rao Manager 19-APR-1999 02 001 21000 1500
004 Kumar P. Supervisor 03-MAY-1999 03 019 10500
005 Mani S. Tailor 03-MAY-1999 03 004 3500
006 Vasanthi K. Tailor 03-MAY-1999 03 004 3750
009 Venkataraman R. Manager 24-JUN-1999 01 001 14250 750
011 Prabhuram S. Designer 25-JUN-1999 03 019 15700 500
012 Denzil Ashok Sales Executive 12-JUL-1999 02 002 8000 750
014 Raghu M. Sales Executive 12-JUL-1999 02 002 7500 750
015 Subramaniam G. Manager 20-AUG-1999 04 001 13200
016 Ganesh P.R. Clerk 03-SEP-1999 01 009 3000
019 Ramarathnam R.S. Manager 16-OCT-1999 03 001 20450 1250
021 Jayanthi M.S. Tailor 22-DEC-1999 03 004 3000
022 Prakash D. Sales Executive 22-DEC-1999 02 002 7500 750
023 Junaid Ismail Tailor 08-JAN-2000 03 004 3500
024 Suryakumar Sales Executive 15-FEB-2000 02 002 7250 500
Select: Some columns

• Need: To see only some selected columns in a table.


• See the names and jobs of all employees.
• Solution:
select NAME, JOB from EMPLOYEES;
EMP_NO NAME JOB HIRE_DATE DEPT_NO MGR_NO SALARY SPEC_ALL
001 Muthukrishnan K. Director 15-APR-1999 01 35500
002 Sridhara Rao Manager 19-APR-1999 02 001 21000 1500
004 Kumar P. Supervisor 03-MAY-1999 03 019 10500
005 Mani S. Tailor 03-MAY-1999 03 004 3500
006 Vasanthi K. Tailor 03-MAY-1999 03 004 3750
009 Venkataraman R. Manager 24-JUN-1999 01 001 14250 750
011 Prabhuram S. Designer 25-JUN-1999 03 019 15700 500
012 Denzil Ashok Sales Executive 12-JUL-1999 02 002 8000 750
014 Raghu M. Sales Executive 12-JUL-1999 02 002 7500 750
015 Subramaniam G. Manager 20-AUG-1999 04 001 13200
016 Ganesh P.R. Clerk 03-SEP-1999 01 009 3000
019 Ramarathnam R.S. Manager 16-OCT-1999 03 001 20450 1250
021 Jayanthi M.S. Tailor 22-DEC-1999 03 004 3000
022 Prakash D. Sales Executive 22-DEC-1999 02 002 7500 750
023 Junaid Ismail Tailor 08-JAN-2000 03 004 3500
024 Suryakumar Sales Executive 15-FEB-2000 02 002 7250 500
Select: Conditions

• Need: To see only those rows that satisfy a condition.


• See the employees with salaries greater than 10000.
• Solution:
select * from EMPLOYEES where SALARY > 10000;

EMP_NO NAME JOB HIRE_DATE DEPT_NO MGR_NO SALARY SPEC_ALL


001 Muthukrishnan K. Director 15-APR-1999 01 35500
002 Sridhara Rao Manager 19-APR-1999 02 001 21000 1500
004 Kumar P. Supervisor 03-MAY-1999 03 019 10500
009 Venkataraman R. Manager 24-JUN-1999 01 001 14250 750
011 Prabhuram S. Designer 25-JUN-1999 03 019 15700 500
015 Subramaniam G. Manager 20-AUG-1999 04 001 13200
019 Ramarathnam R.S. Manager 16-OCT-1999 03 001 20450 1250
Select: Some columns and conditions

• Need: To see only selected columns of those rows that satisfy a


condition.
• See the names, jobs and hire dates of those employees who work for
department ‘02’.
• Solution:
select NAME, JOB, HIRE_DATE from EMPLOYEES
where DEPT_NO = ‘02’;

EMP_NO NAME JOB HIRE_DATE DEPT_NO MGR_NO SALARY SPEC_ALL


002 Sridhara Rao Manager 19-APR-1999 02 001 21000 1500
012 Denzil Ashok Sales Executive 12-JUL-1999 02 002 8000 750
014 Raghu M. Sales Executive 12-JUL-1999 02 002 7500 750
022 Prakash D. Sales Executive 22-DEC-1999 02 002 7500 750
024 Suryakumar Sales Executive 15-FEB-2000 02 002 7250 500
Select: Multiple conditions

• Need: To see rows that satisfy many conditions.


• See the names, jobs, hire dates and salaries of those employees who
joined prior to 1 Jun 1999 and receive salaries less than 5000.
• Solution:

select NAME, JOB, HIRE_DATE, SALARY from EMPLOYEES


where HIRE_DATE < TO_DATE(‘01-JUN-1999’, ‘DD-MON-YYYY’)
and SALARY < 5000;

EMP_NO NAME JOB HIRE_DATE SALARY SPEC_ALL


005 Mani S. Tailor 03-MAY-1999 3500
006 Vasanthi K. Tailor 03-MAY-1999 3750
Select: Multiple conditions: Or

• Need: To see those rows that satisfy any of some conditions.


• See the employees who report to manager ‘001’ or who work for
department ‘01’.
• Solution:
select * from EMPLOYEES where MGR_NO = ‘001’ or DEPT_NO
= ‘01’;
Select: Complex multiple conditions

• Need: To see those rows that satisfy some complex conditions.


• See the employees who are work in department ‘01’ or ‘02’ with a
salary less than 10000.
• Solution:
select * from EMPLOYEES where (DEPT_NO = ‘01’ or
DEPT_NO = ‘02’) and SALARY < 10000;

Parentheses are used to alter the


precedence of operations.

More on conditions later.


Select: Ordering rows

• Need: To see the rows in a sorted order.


• See the employee details in the order of their names.
• Solution:
select * from EMPLOYEES order by NAME;
EMP_NO NAME JOB HIRE_DATE DEPT_NO MGR_NO SALARY SPEC_ALL
012 Denzil Ashok Sales Executive 12-JUL-1999 02 002 8000 750
016 Ganesh P.R. Clerk 03-SEP-1999 01 009 3000
021 Jayanthi M.S. Tailor 22-DEC-1999 03 004 3000
023 Junaid Ismail Tailor 08-JAN-2000 03 004 3500
004 Kumar P. Supervisor 03-MAY-1999 03 019 10500
005 Mani S. Tailor 03-MAY-1999 03 004 3500
001 Muthukrishnan K. Director 15-APR-1999 01 35500
011 Prabhuram S. Designer 25-JUN-1999 03 019 15700 500
022 Prakash D. Sales Executive 22-DEC-1999 02 002 7500 750
014 Raghu M. Sales Executive 12-JUL-1999 02 002 7500 750
019 Ramarathnam R.S. Manager 16-OCT-1999 03 001 20450 1250
002 Sridhara Rao Manager 19-APR-1999 02 001 21000 1500
015 Subramaniam G. Manager 20-AUG-1999 04 001 13200
024 Suryakumar Sales Executive 15-FEB-2000 02 002 7250 500
006 Vasanthi K. Tailor 03-MAY-1999 03 004 3750
009 Venkataraman R. Manager 24-JUN-1999 01 001 14250 750
Select: Ordering rows in reverse

• Need: To see some columns of some selected rows in a descending


order.
• See the emp nos, names, jobs and salaries of employees who are
managers in the descending order of salaries.
• Solution:
select EMP_NO, NAME, JOB, SALARY from EMPLOYEES where
JOB = ‘Manager’ order by SALARY desc;
EMP_NO NAME JOB SALARY
002 Sridhara Rao Manager 21000
019 Ramarathnam R.S. Manager 20450
009 Venkataraman R. Manager 14250
015 Subramaniam G. Manager 13200
Select: Ordering rows by multiple columns

• Need: To see the rows sorted by more than one column (i.e. sorted first by
one column and, within that, sorted by another column.)
• See the employee details ordered by their departments and then by their jobs.
• Solution:
select * from EMPLOYEES order by DEPT_NO, JOB;
EMP_NO NAME JOB HIRE_DATE DEPT_NO MGR_NO SALARY SPEC_ALL
016 Ganesh P.R. Clerk 03-SEP-1999 01 009 3000
001 Muthukrishnan K. Director 15-APR-1999 01 35500
009 Venkataraman R. Manager 24-JUN-1999 01 001 14250 750
002 Sridhara Rao Manager 19-APR-1999 02 001 21000 1500
012 Denzil Ashok Sales Executive 12-JUL-1999 02 002 8000 750
014 Raghu M. Sales Executive 12-JUL-1999 02 002 7500 750
022 Prakash D. Sales Executive 22-DEC-1999 02 002 7500 750
024 Suryakumar Sales Executive 15-FEB-2000 02 002 7250 500
011 Prabhuram S. Designer 25-JUN-1999 03 019 15700 500
019 Ramarathnam R.S. Manager 16-OCT-1999 03 001 20450 1250
004 Kumar P. Supervisor 03-MAY-1999 03 019 10500
005 Mani S. Tailor 03-MAY-1999 03 004 3500
006 Vasanthi K. Tailor 03-MAY-1999 03 004 3750
021 Jayanthi M.S. Tailor 22-DEC-1999 03 004 3000
023 Junaid Ismail Tailor 08-JAN-2000 03 004 3500
015 Subramaniam G. Manager 20-AUG-1999 04 001 13200
Select: Effect of changing ordering columns

• Changing the position of the ordering columns results in a different


ordering of rows.
• See the employee details ordered by their jobs and then by their departments.
• Solution:
select * from EMPLOYEES order by JOB, DEPT_NO;
EMP_NO NAME JOB HIRE_DATE DEPT_NO MGR_NO SALARY SPEC_ALL
016 Ganesh P.R. Clerk 03-SEP-1999 01 009 3000
011 Prabhuram S. Designer 25-JUN-1999 03 019 15700 500
001 Muthukrishnan K. Director 15-APR-1999 01 35500
009 Venkataraman R. Manager 24-JUN-1999 01 001 14250 750
002 Sridhara Rao Manager 19-APR-1999 02 001 21000 1500
015 Subramaniam G. Manager 20-AUG-1999 04 001 13200
019 Ramarathnam R.S. Manager 16-OCT-1999 03 001 20450 1250
012 Denzil Ashok Sales Executive 12-JUL-1999 02 002 8000 750
014 Raghu M. Sales Executive 12-JUL-1999 02 002 7500 750
022 Prakash D. Sales Executive 22-DEC-1999 02 002 7500 750
024 Suryakumar Sales Executive 15-FEB-2000 02 002 7250 500
004 Kumar P. Supervisor 03-MAY-1999 03 019 10500
005 Mani S. Tailor 03-MAY-1999 03 004 3500
006 Vasanthi K. Tailor 03-MAY-1999 03 004 3750
021 Jayanthi M.S. Tailor 22-DEC-1999 03 004 3000
023 Junaid Ismail Tailor 08-JAN-2000 03 004 3500
Select: Combining multiple columns and ordering sequence

• Need: To see the rows sorted by more than one column and in a
descending order.
• See the employee details ordered by their departments in the descending order
and then by their jobs in the ascending order.
• Solution:
select * from EMPLOYEES order by DEPT_NO desc, JOB;
EMP_NO NAME JOB HIRE_DATE DEPT_NO MGR_NO SALARY SPEC_ALL
015 Subramaniam G. Manager 20-AUG-1999 04 001 13200
011 Prabhuram S. Designer 25-JUN-1999 03 019 15700 500
019 Ramarathnam R.S. Manager 16-OCT-1999 03 001 20450 1250
004 Kumar P. Supervisor 03-MAY-1999 03 019 10500
005 Mani S. Tailor 03-MAY-1999 03 004 3500
006 Vasanthi K. Tailor 03-MAY-1999 03 004 3750
021 Jayanthi M.S. Tailor 22-DEC-1999 03 004 3000
023 Junaid Ismail Tailor 08-JAN-2000 03 004 3500
002 Sridhara Rao Manager 19-APR-1999 02 001 21000 1500
012 Denzil Ashok Sales Executive 12-JUL-1999 02 002 8000 750
014 Raghu M. Sales Executive 12-JUL-1999 02 002 7500 750
022 Prakash D. Sales Executive 22-DEC-1999 02 002 7500 750
024 Suryakumar Sales Executive 15-FEB-2000 02 002 7250 500
016 Ganesh P.R. Clerk 03-SEP-1999 01 009 3000
001 Muthukrishnan K. Director 15-APR-1999 01 35500
009 Venkataraman R. Manager 24-JUN-1999 01 001 14250 750
Select: Pattern matching: Matching multiple characters

• Need: To see the rows where a column matches a pattern.


• See the employees whose name starts with something like ‘Surya’.
• Solution:
select * from EMPLOYEES where NAME like ‘Surya%’;

% is a wildcard standing for 0 or


more characters.
Select: Pattern matching: Matching a single character

• Need: To see the rows where a column matches a pattern.


• See the employees whose emp no starts with ‘02’ and ends with a
single character.
• Solution:
select * from EMPLOYEES where EMP_NO like ‘02_’;

_ is a position marker standing for


exactly 1 character.
Select: Looking for Null

• Need: To see the rows in which a column’s value is null.


• See the employees whose MGR_NO is null.
• Solution:
select * from EMPLOYEES where MGR_NO is null;

Warning:
‘ = null’ will not work!
Select: Looking for Not Null

• Need: To see the rows in which a column’s value is not null.


• See the employee rows where special allowance is not null.
• Solution:
select * from EMPLOYEES where SPEC_ALL is not null;
Select: Testing against multiple values

• Need: To see the rows where a column’s value is among a list of


values.
• See the employees who are either managers or supervisors or sales
executives.
• Earlier solution:
select * from EMPLOYEES where JOB = ‘Manager’ or JOB =
‘Supervisor’ or JOB = ‘Sales Executive’;

• Better solution:
select * from EMPLOYEES where JOB in
(‘Manager’, ‘Supervisor’, ‘Sales Executive’);
Select: Not in a list of values

• Need: To see the rows where a column’s value is not among a list of
values.
• See the employees who do not work in department ‘01’ or ‘03’.
• Earlier solution:
select * from EMPLOYEES where DEPT_NO <> ‘01’ and
DEPT_NO <> ‘03’;

• Better solution:
select * from EMPLOYEES where DEPT_NO not in
(‘01’, ‘03’);
Select: Range of values

• Need: To see the rows where a column’s value is within a range of


values.
• See the employees who receive salaries between 10000 and 20000.
• Earlier solution:
select * from EMPLOYEES where SALARY >= 10000 and
SALARY <= 20000;

• Better solution:
select * from EMPLOYEES where SALARY between 10000 and
20000;
Select: Not in a range of values

• Need: To see the rows where a column’s value is not within a range
of values.
• See the employees who did not join between ‘1 Jun 1999’ and ‘31 Dec
1999’
• Earlier solution:
select * from EMPLOYEES where
HIRE_DATE < to_date(‘01-JUN-1999’, ‘DD-MON-YYYY’) or
HIRE_DATE > to_date(‘31-DEC-1999’, ‘DD-MON-YYYY’);

• Better solution:
select * from EMPLOYEES where HIRE_DATE not between
to_date(‘01-JUN-1999’, ‘DD-MON-YYYY’) and
to_date(‘31-DEC-1999’, ‘DD-MON-YYYY’);
Modifying the Contents of a Table

• The rows in a table may need to be modified or updated.


• Solution: Use the UPDATE (SQL DML) command.
Update: Single column/row

• Need: To change the value of a single column of a row.


• Change the salary of Jayanthi to 3500.
• Solution:
update EMPLOYEES set SALARY = 3500
where NAME = ‘Jayanthi’;

Changing of column values

Condition for selecting the row


Update: The importance of the ‘where’ clause

• The ‘where’ clause is very critical in the UPDATE command.

update EMPLOYEES set SALARY = 3500


where NAME = ‘Jayanthi’;

Warning:
1) The absence of the where clause will result
in all the rows getting updated.
2) An improper where clause can affect
unwanted rows.

Implications for the developer:


1) Check the where clause carefully to see if it is
proper.
2) Query the rows after the update to see if the
expected changes took place correctly.
Update: Usage of primary key for updating a single row

update EMPLOYEES set SALARY = 3500 where NAME =


‘Jayanthi’;

Names make poor identifiers. (There could be two Jayanthis.)


Hence, typically, the primary key is used to identify the row to be updated.

update EMPLOYEES set SALARY = 3500 where EMP_NO =


‘021’;
Update: Single column/multiple rows

• Need: To change the value of a single column for a set of rows.


• Increase the salary of all tailors by Rs.250.
• Solution:
update EMPLOYEES set SALARY = SALARY + 250 where
JOB = ‘Tailor’;
Update: Multiple columns/multiple rows

• Need: To change the value of many columns for a set of rows.


• Increase the salary of all sales executives by 5% and their special
allowances by Rs.100.
• Solution:
update EMPLOYEES set SALARY = SALARY * 1.05, SPEC_ALL =
SPEC_ALL + 100 where JOB = ‘Sales Executive’;
Update: All rows

• Need: To change a column for all rows.


• Give a salary raise of Rs.200 to all employees.
• Solution:

update EMPLOYEES set SALARY = SALARY + 200;

No where clause - Updates all rows.


Update: Null

• Need: To change the value of a column to NULL.


• Set the DEPT_NO column of Ganesh (EMP_NO 016) to NULL.
• Solution:
update EMPLOYEES set DEPT_NO = null
where EMP_NO = ‘016’;
Deleting the Contents of a Table

• We may want to delete one or more rows in a table.


• Solution: Use the delete (SQL DML) command.
Delete: Single row

• Need: To delete a single row.


• Delete Raghu from the employees table.
• Solution:
delete from EMPLOYEES where NAME =‘Raghu M.’;
Delete: The importance of the ‘where’ clause

• The ‘where’ clause is very critical in the DELETE command.

delete from EMPLOYEES where NAME =‘Raghu M.’;

Warning:
1) The absence of the where clause will result
in all the rows getting deleted.
2) An improper delete clause can delete rows
that we may not want to remove.

Implications for the developer:


1) Check the where clause carefully to see if it is
proper.
2) Query the table after the deletion to see if only
the required rows were deleted.
Update: Usage of primary key for deleting a single row

delete from EMPLOYEES where NAME =‘Raghu M.’;

Names make poor identifiers. (There could be two ‘Raghu M.’s.)


Hence, typically, the primary key is used to identify the row to be deleted.

delete from EMPLOYEES where EMP_NO = ‘014’;


Delete: Multiple rows

• Need: To delete multiple rows.


• Delete all sales executives.
• Solution:
delete from EMPLOYEES where JOB = ‘Sales Executive’;
Delete: All rows

• Need: To delete all rows.


• Delete all employees.
• Solution:
delete from EMPLOYEES;
• Another solution:
truncate EMPLOYEES;
Sidetrack: The Concept of Actions

Action

Operation Non-operation
(Causes state change) (No state change)

Create Modify Destroy See


Actions and SQL DML

Action

Operation Non-operation
(Causes state change) (No state change)

Create Modify Destroy See

SQL DML

Action Query Select Query

INSERT UPDATE DELETE SELECT


Actions and SQL DDL

Action

Operation Non-operation
(Causes state change) (No state change)

Create Modify Destroy See

SQL DDL

(No Name) (No Name)

CREATE ALTER DROP SELECT


Committing and Rolling Back
Action and its danger

• Sometimes when we perform an action, we may make a mistake.


• We may then want to undo the mistake.
• This is accomplished with the features of commit and rollback.
Commit

• Changes made to the rows of a table (through inserts, updates and deletes)
are actually not made final in the database until they are committed.
• Changes are also not visible to other users until committed.
• Committing makes the changes final and also makes the changes visible to
other users.
insert into EMPLOYEES values (‘001’, ‘Muthukrishnan
K.’, ‘Director’, ‘15-APR-99’, NULL, NULL, 35500, NULL);

1 row inserted.

commit;

commit complete

The Muthukrishnan row is added to the table but not made permanent.
The row is available to this user but not to other users.

Now the Muthukrishnan row is made permanent and is available to other


users.
Rollback
• rollback reverses or undoes the changes made to the rows.

insert into EMPLOYEES values (‘001’, ‘Muthukrishnan


K.’, ‘Director’, ‘15-APR-99’, NULL, NULL, 35500, NULL);

1 row inserted.

rollback;

rollback complete

The Muthukrishnan row is added to


the table but not made permanent.

Now the Muthukrishnan row is


removed from the table.
Commit/Rollback: Scope of operation
• commit and rollback respectively save and undo all the
previous changes.
insert into EMPLOYEES values (‘001’, ‘Muthukrishnan K.’,
‘Director’, ‘15-APR-99’, NULL, NULL, 35500, NULL);

1 row inserted.

insert into EMPLOYEES values (‘002’, ‘Sridhara Rao’,


‘Manager’, ‘19-APR-99’, ‘02’, ‘001’, 11000, 1500);

1 row inserted.

update EMPLOYEES set SALARY = 21000 where EMP_NO = ‘002’;

1 row updated.

rollback;

rollback complete

Rolls back all the previous changes (2 inserts and 1 update).


Commit/Rollback: Scope of operation
• commit and rollback respectively save and undo only the
previous uncommitted changes i.e. upto the last commit or rollback.
insert into EMPLOYEES values (‘001’, ‘Muthukrishnan K.’,
‘Director’, ‘15-APR-99’, NULL, NULL, 25500, NULL);
1 row inserted.

insert into EMPLOYEES values (‘002’, ‘Sridhara Rao’,


‘Manager’, ‘19-APR-99’, ‘02’, ‘001’, 11000, 1500);
1 row inserted.

commit;
commit complete

update EMPLOYEES set SALARY = 21000 where EMP_NO = ‘002’;


1 row updated.

rollback;
rollback complete
Commits all the previous uncommitted changes (2 inserts).

Rolls back only the uncommitted changes (1 update).


Rollback: Misconception
• rollback undoes only the previous uncommitted changes.

insert into EMPLOYEES values (‘001’, ‘Muthukrishnan K.’,


‘Director’, ‘15-APR-99’, NULL, NULL, 25500, NULL);
1 row inserted.

insert into EMPLOYEES values (‘002’, ‘Sridhara Rao’,


‘Manager’, ‘19-APR-99’, ‘02’, ‘001’, 11000, 1500);
1 row inserted.

commit;
commit complete

rollback;
rollback complete

Warning:
This message is misleading. Since there are no
uncommitted changes, rollback has actually done
nothing.
Committing: Explicit and Implicit
• ‘commit’ command explicitly commits the changes.
• Under certain circumstances, Oracle automatically commits the
changes.
• This is called ‘implicit commit’.
• Commands for which implicit commit takes place:
• quit
• exit
• create table or create view
• drop table or drop view
• grant or revoke
• connect or disconnect
• alter
• audit or noaudit
Quiz

• Suppose we have made some changes to a table but not committed


them yet; now if there is a power failure or a computer failure, what
will happen to the changes?
• What should happen to the changes?
System Failures and Auto Rollback

• If the machine or the database goes down, Oracle automatically rolls


back all the uncommitted changes.
• This is called ‘Auto Rollback’.
• Quiz: How can Oracle roll back the changes when the machine itself
is down?
• Answer: Oracle rolls back the uncommitted changes the next time
the database is brought up.
• This is something like a ‘cleanup work’ that Oracle performs.
Typical System Failures

• Power failure
• Computer failure
• Network failure
• Hard disk crash
• Database crash
Commit and Rollback: A Scenario

Command/Event Contents of table Contents of table


for this user for other users
insert into DEPARTMENTS (DEPT_NO, NAME) 10 Quality
values (‘10’, ‘Quality’);
commit; 10 Quality 10 Quality
insert into DEPARTMENTS (DEPT_NO, NAME) 10 Quality 10 Quality
values (‘11’, ‘HRD’); 11 HRD
rollback; 10 Quality 10 Quality
insert into DEPARTMENTS (DEPT_NO, NAME) 10 Quality 10 Quality
values (‘11’, ‘HRD’); 11 HRD
insert into DEPARTMENTS (DEPT_NO, NAME) 10 Quality 10 Quality
values (‘12’, ‘Training’); 11 HRD
12 Training
exit; 10 Quality 10 Quality
(Implicit commit takes place) 11 HRD 11 HRD
12 Training 12 Training
update DEPARTMENTS set NAME = 'R&D' 10 Quality 10 Quality
where DEPT_NO = '11' 11 R&D 11 HRD
12 Training 12 Training
(System failure. Auto rollback takes 10 Quality 10 Quality
place the next time the database is up.) 11 HRD 11 HRD
12 Training 12 Training
delete from DEPARTMENTS 11 HRD 10 Quality
where NAME = 'Quality'; 12 Training 11 HRD
12 Training
rollback; 10 Quality 10 Quality
11 HRD 11 HRD
12 Training 12 Training
Autocommit

• Sometimes there is a need to automatically commit the changes


without explicitly telling so (by using the commit command).
• In such cases, use the autocommit feature:

set autocommit on
insert into EMPLOYEES values (‘001’, ‘Muthukrishnan K.’,
‘Director’, ‘15-APR-99’, NULL, NULL, 35500, NULL);
1 row inserted.

update EMPLOYEES set SALARY = 35500 where EMP_NO = ‘001’;


1 row updated.

The inserted row is automatically committed.

The updated row is automatically committed.

• set autocommit is an SQL*Plus command - not an SQL


command.
• The default for autocommit is off.
Backtrack: Truncate
• truncate deletes all rows from a table.
truncate EMPLOYEES;
• The same task can be achieved with the delete command:
delete from EMPLOYEES;
• However the truncate command cannot be rolled back.

Warning:
The truncate command cannot be rolled
back. Hence be cautious in using it.
More on Selecting Rows
Selecting Distinct Entries

• Suppose we wanted to find all jobs in the company.


select JOB from EMPLOYEES;

JOB
--------------------
Director
Manager
Supervisor
Tailor
Tailor
Manager
Designer
Sales Executive
Sales Executive
Manager Many entries appear several times.
Clerk
Manager
Tailor
Sales Executive
Tailor
Sales Executive

16 rows selected.
Selecting Distinct Entries

• To avoid duplicate entries and select them distinctly, use the


DISTINCT clause
select distinct JOB from EMPLOYEES;

JOB
--------------------
Clerk
Designer
Director
Manager
Sales Executive
Supervisor
Tailor

7 rows selected.

Entries appear only once. No duplicates.


Expressions
Select: Using expressions

• Until now, we have selected mere columns of data.


• However, often we may want to combine columns or use
expressions for selecting data. E.g.
• See the total salary (salary + special allowance) for all employees.
• This is possible by using expressions in select statements.
Select: Add two columns

• Need: To add two columns of data. E.g.


• See the total salary (salary + special allowance) for all employees.
• Solution:
select NAME, SALARY + SPEC_ALL from EMPLOYEES;

NAME SALARY+SPEC_ALL
------------------------- --------------- Expression
Muthukrishnan K.
Sridhara Rao 22500
Kumar P.
Mani S.
Vasanthi K.
By the way, why are many
Venkataraman R. 15000
Prabhuram S. 16200
total salaries null? We will
Denzil Ashok 8750 see later.
Raghu M. 8250
Subramaniam G.
Ganesh P.R.
Ramarathnam R.S. 21700
Jayanthi M.S.
Prakash D. 8250
Junaid Ismail
Suryakumar 7750
Expressions

• Any valid expression is permitted in the select statement.


• Some examples:
• Show the joining dates of employees in the ‘MM/DD/YYYY’ format
along with their names.
select NAME, TO_CHAR(HIRE_DATE, ‘MM/DD/YYYY’) from
EMPLOYEES;

• Show the employee names along with their special allowances


increased by 10%.
select NAME, 1.1 * SPEC_ALL from EMPLOYEES;
• Show the names of employees in uppercase.
select UPPER(NAME) from EMPLOYEES;

TO_CHAR, UPPER are functions. We


will see functions later.
Expressions with literals

• The expression need not refer a column at all.


• It may merely use literals.
• Example:
select NAME, ‘works in department no:’, DEPT_NO from
EMPLOYEES;

NAME 'WORKSINDEPARTMENTNO:' DE
-------------------- ----------------------- -- Literal
Muthukrishnan K. works in department no: 01
Sridhara Rao works in department no: 02
Kumar P. works in department no: 03
Mani S. works in department no: 03
Vasanthi K. works in department no: 03
...

The literal expression is the same for all rows. This is


what makes it uninteresting in a select statement.

• Expressions with mere literals are used very rarely.


Aliasing

• Sometimes we may want to identify a selected expression (or


column) by another name. E.g.
• We may want to call the expression SALARY+SPEC_ALL as
TOTAL_SALARY.
• We may want to call JOB as DESIGNATION.
• This is done with aliasing.
• Definition: An alias is an alternate name for a column or expression
or even a table.
Creating an alias

• The alias is defined after the column name or expression:


select NAME, JOB DESIGNATION,
Aliases
SALARY+SPEC_ALL TOTAL_SALARY from EMPLOYEES;

NAME DESIGNATION TOTAL_SALARY


-------------------- -------------------- ------------
Muthukrishnan K. Director
Sridhara Rao Manager 22500
Kumar P. Supervisor
Mani S. Tailor
Vasanthi K. Tailor
Venkataraman R. Manager 15000
Prabhuram S. Designer 16200
Denzil Ashok Sales Executive 8750
Raghu M. Sales Executive 8250
Subramaniam G. Manager
Ganesh P.R. Clerk
Ramarathnam R.S. Manager 21700
Jayanthi M.S. Tailor
Prakash D. Sales Executive 8250
Junaid Ismail Tailor
Suryakumar Sales Executive 7750
Sidetrack: NVL
select NAME, SALARY, SPEC_ALL, SALARY+SPEC_ALL TOTAL_SALARY
from EMPLOYEES;
NAME SALARY SPEC_ALL TOTAL_SALARY
------------------------- ---------- ---------- ------------
Muthukrishnan K. 35500
Sridhara Rao 21000 1500 22500
Kumar P. 10500
Mani S. 3500
Vasanthi K. 3750 Expression
Venkataraman R. 14250 750 15000
Prabhuram S. 15700 500 16200
...

• When null is used in an expression, the expression evaluates to null.


• 35500 + null = null (not 35500)
• But here we want a null to be treated as 0.
• We want 35500 + null = 35500
• This is possible with the NVL function.
Sidetrack: NVL
select NAME, SALARY, SPEC_ALL, SALARY + NVL(SPEC_ALL,0)
TOTAL_SALARY from EMPLOYEES;

NAME SALARY SPEC_ALL TOTAL_SALARY


------------------------- ---------- ---------- ------------
Muthukrishnan K. 35500 35500
Sridhara Rao 21000 1500 22500
Kumar P. 10500 10500
Mani S. 3500 3500
Expression
Vasanthi K. 3750 3750
Venkataraman R. 14250 750 15000
Prabhuram S. 15700 500 16200
...

Null has been treated as 0.


Functions
Functions

• There is often a need to process numbers, character strings and dates


while using them. For instance,
• we may need to calculate
• the average of a set of numbers
• the square root of a number
• the absolute value of a signed number
• the trigonometric sine value of a number
• the logarithmic value of a number
• we may need to
• find the length of a character string
• combine two strings to form one string
• convert a string to upper case
• we may need to find
• the number of days between two dates
• the date which comes ‘n’ days after a given date
• Oracle provides numerous functions for performing such tasks.
Grouping Functions

Function Purpose
SUM(column) Finds the sum of a column's values.
MAX(column) Finds the maximum value in a column.
MIN(column) Finds the minimum value in a column.
AVG(column) Finds the average value in a column.
COUNT(*) Counts the number of rows.
COUNT(column) Counts the number of non-null values in a column.
STDDEV(column) Finds the standard deviation in a column.
VARIANCE(column) Finds the variance in a column.

We will see Group Functions later.


Important Numeric Functions

Function Purpose
ROUND(value, precision) Rounding of value to the given precision
EXP(value) 'e' raised to the value (evalue)
POWER(value, exponent) Value raised to the exponent (valueexponent)
MOD(value, divisor) Modulus of value with respect to given divisor
ABS(value) Absolute value
LN(value) Natural logarithm of value
LOG(value) Base 10 logarithm of value
SIN(value) Trigonometric sine of value
Important String Functions

Function Purpose
|| Concatenates two strings
CONCAT Concatenates two strings. Same as ||
LENGTH Number of characters in the string
LOWER String in lowercase
UPPER String in uppercase
SUBSTR Extracts the substring from 'string'
INSTR Finds the location of a substring in a string
INITCAP String in InitCap format
SOUNDEX Finds words that sound like given string
Important Date Functions

Function Purpose
MONTHS_BETWEEN Number of months between two dates
ADD_MONTHS Adds months to a given date
LAST_DAY Last date of the month that the given date is in
Important Generic Functions

Function Purpose
NVL(value, substitute) Substitute for value if value is null
GREATEST(value1, value2, …) Greatest of the values (For numbers, the largest number;
for strings, the last in the alphabetical order; for dates, the
latest date)
LEAST(value1, value2, …) Least of the values (For numbers, the smallest number;
for strings, the first in the alphabetical order; for dates,
the earliest date)
DECODE Conditional value
Important Conversion Functions

Function Purpose
TO_CHAR Converts a number or date to a character string
TO_DATE Converts a string or number to a date
TO_NUMBER Converts a string to a number
Function types

• Functions are categorized into 3 types:


• Single-value functions
• Functions that operate on a single value (such as a single column value).
• E.g. The name of an employee in uppercase.
• UPPER(NAME)
• Group-value functions
• Functions that operate on a set of row values for a single column.
• E.g. The average salary of all employees
• AVG(SALARY)
• List functions
• Functions that operate on a list of values (such as a set of columns).
• E.g. The larger one between salary and special allowance
• GREATEST(SALARY, SPEC_ALL)
Grouping Rows Together

Group-Value Functions
Select: Applying functions on rows

• Until now, we have selected mere rows of data.


• However, we may often want to treat all the rows together as a
group and find something about the group itself instead of the rows.
• For instance, treating all the employee rows as a group, we may want
to find out
• the total salary disbursement in the company.
• the maximum salary in the company.
• the maximum special allowance in the company.
• the number of employees in the company.
• This need is fulfilled by the ‘group-value functions’.
Select: Sum of a column

• Need:To find the sum of a column’s values. E.g.


• Find the total salary disbursement in Patanjali Garments.
• Solution:
select sum(SALARY) from EMPLOYEES;

SUM(SALARY)
-----------
177600
Select: Average of a column

• Need:To find the average value of a column’s values. E.g.


• Find the average salary of employees in Patanjali Garments.
• Solution:
select avg(SALARY) from EMPLOYEES;

AVG(SALARY)
-----------
11100
Select: Maximum of a column

• Need:To find the maximum value of a column’s values. E.g.


• Find the maximum special allowance in the company.
• Solution:
select max(SPEC_ALL) from EMPLOYEES;

MAX(SPEC_ALL)
-------------
1500
Select: Counting the rows

• Need:To count the number of rows in a table.


• Find the number of employees in Patanjali Garments.
• Solution:
select count(*) from EMPLOYEES;

COUNT(*)
----------
16

• You can also use a column in the count function:


select count(EMP_NO) from EMPLOYEES;
select count(NAME) from EMPLOYEES;

COUNT(NAME)
-----------
16 P.Srinivasan:
Introduce
DISTINCT
Group-value functions - List

Function Purpose
sum(column) Finds the sum of a column's values.
max(column) Finds the maximum value in a column.
min(column) Finds the minimum value in a column.
avg(column) Finds the average value in a column.
count(*) Counts the number of rows.
count(column) Counts the number of non-null values in a column.
stddev(column) Finds the standard deviation in a column.
variance(column) Finds the variance in a column.
Group-value functions and Nulls

• Group functions ignore nulls.


• Examples:
• Find the total special allowance disbursed by the company.
select sum(SPEC_ALL) from EMPLOYEES;
SUM(SPEC_ALL)
-------------
6750

Ignores nulls and sums all non-null values.

• Find the average special allowance in the company.


select avg(SPEC_ALL) from EMPLOYEES;
AVG(SPEC_ALL)
-------------
843.75

Ignores nulls, sums all non-null values and divides


the sum by the number of non-null values.
count function and Nulls
• count(*) function counts the number of rows.
• Hence it is independent of nulls in columns.
• However, count(column) function ignores the nulls and counts
the number of non-null values in the column. E.g.
• Find the number of employees who receive a special allowance.
select count(SPEC_ALL) from EMPLOYEES;

COUNT(SPEC_ALL)
---------------
8

Ignores nulls and counts only non-null values.

Tips:
COUNT(column) is very useful to find the
number of non-null entries in a column.
Multiple group functions in a select statement

• Sometimes we may need to see many grouped values in a single


select operation. E.g.
• Find the maximum, average and minimum salaries in the company.
• Solution:
select max(SALARY), avg(SALARY), min(SALARY) from
EMPLOYEES;

MAX(SALARY) AVG(SALARY) MIN(SALARY)


----------- ----------- -----------
35500 11100 3000
Expressions in group functions

• We may sometimes want to evaluate an expression and then apply a


group function. E.g.
• Find the average total salary (salary+special allowance) in the
company.
• This is done by using expressions (in place of columns) in the group
function.
Expressions in group functions

• Need: Find the average total salary (salary+special allowance) in the


company.
• Solution:
select avg(SALARY+NVL(SPEC_ALL,0)) from EMPLOYEES;

AVG(SALARY+NVL(SPEC_ALL,0))
---------------------------
11521.875
DISTINCT in group functions

• Suppose we wanted to find the number of bosses (i.e., those reported


to by others) in the company.
• Tentative solution:
select count(MGR_NO) from EMPLOYEES;

COUNT(MGR_NO)
-------------
15

This result is incorrect because it has counted duplicate entries.

Reminder:
count(column) will not include
nulls in the counting process.
DISTINCT in group functions

• To avoid duplicate entries in group functions, use the DISTINCT


clause.
• Solution:
select count(distinct MGR_NO) from EMPLOYEES;

COUNT(DISTINCTMGR_NO)
---------------------
5

Now only distinct entries have been counted.


Grouping Rows On Specific Columns

Group By, Having Clauses


Grouping Rows on Specific Columns

• Until now, we had grouped all rows in a table and found out
something about the group.
• Sometimes we may want to group the rows in the table on some
column and then find something about the groups. E.g.
• We may want to group the employees according to their departments
and find the number of employees in each department.
• We may want to group the employees based on their jobs and find the
maximum salary in each job.
• We may want to group the employees based on their bosses and find
the number of subordinates for every boss.
• This is done by using the GROUP BY clause.
Group By

• Need: Group the employees according to their departments to find


the number of employees in each department.
• Solution:
select DEPT_NO, COUNT(*) from EMPLOYEES group by DEPT_NO;

DE COUNT(*)
-- ----------
01 3
02 5
03 7
04 1

Group by the department


and
find the number of employees in each department
Group By - Another Example

• Need: Group the employees based on their jobs and find the
maximum salary in each job.
• Solution:
select JOB, MAX(SALARY) from EMPLOYEES group by JOB;

JOB MAX(SALARY)
-------------------- -----------
Clerk 3000
Designer 15700
Director 35500
Manager 21000
Sales Executive 8000
Supervisor 10500
Tailor 3750
Group By - Rules for the selected columns

• Once the rows are grouped together, only group-values (like sum,
average, maximum etc.) of columns can be obtained. The row values
cannot be obtained.
• Hence all items in the select statement should be group-value
functions; the only exception is the grouping column itself.

select JOB, MAX(SALARY) from EMPLOYEES group by JOB;

Barring the grouping column


all other items should be group functions
Group By - Example of incorrect usage

select JOB, SALARY from EMPLOYEES group by JOB;

select JOB, SALARY from EMPLOYEES group by JOB


*
ERROR at line 1:
ORA-00979: not a GROUP BY expression

Once the rows are grouped by job, the individual salaries are not
available. Hence this statement will cause an error.
Grouping - The Concept of its Working

• Example: Find the maximum salary in every department.


select DEPT_NO, MAX(SALARY) from EMPLOYEES group by
DEPT_NO;

DE MAX(SALARY)
-- -----------
01 35500
02 21000
03 20450
04 13200

• How does the grouping operation work conceptually?


Group By - What does it do?

1 When you group by a column, the rows are segregated into different
groups based on that column.
EMP NAME JOB HIRE_DATE DE MGR SALARY
SPEC_ALL
--- -------------------- -------------------- --------- -- --- ----------
---------
001 Muthukrishnan K. Director 15-APR-99 01 35500
009 Venkataraman R. Manager 24-JUN-99 01 001 14250
750
016 Ganesh P.R. Clerk 03-SEP-99 01 009 3000

002 Sridhara Rao Manager 19-APR-99 02 001 21000


1500
024 Suryakumar Sales Executive 15-FEB-00 02 002 7250
500
022 Prakash D. Sales Executive 22-DEC-99 02 002 7500
750
014 Raghu M. Sales Executive 12-JUL-99 02 002 7500
750
012 Denzil Ashok Sales Executive 12-JUL-99 02 002 8000
750

004 Kumar P. Supervisor 03-MAY-99 03 019 10500


023 Junaid Ismail Tailor 08-JAN-00 03 004 3500
021 Jayanthi M.S. Tailor 22-DEC-99 03 004 3000
Group By - What does it do?

2 The group function is then applied for every group and one output row is
produced for every group.
EMP NAME JOB HIRE_DATE DE MGR SALARY
SPEC_ALL
--- -------------------- -------------------- --------- -- --- ----------
---------
001 Muthukrishnan K. Director 15-APR-99 01 35500
009 Venkataraman R. Manager 24-JUN-99 01 001 14250
750
016 Ganesh P.R. Clerk 03-SEP-99 01 009 3000

002 Sridhara Rao Manager 19-APR-99 02 001 21000


1500
024 Suryakumar Sales Executive 15-FEB-00 02 002 7250
500
022 Prakash D. Sales Executive 22-DEC-99 02 002 7500
750
014 Raghu M. Sales Executive 12-JUL-99 02 002 7500
750
012 Denzil Ashok Sales Executive 12-JUL-99 02 002 8000
750

004 Kumar P. Supervisor 03-MAY-99 03 019 10500


023 Junaid Ismail Tailor 08-JAN-00 03 004 3500
021 Jayanthi M.S. Tailor 22-DEC-99 03 004 3000
Group By - What does it do?

• Hence the result contains one row for every group.

DE MAX(SALARY)
-- -----------
01 35500
02 21000
03 20450
04 13200
Group By

• You can use many group functions on many columns in a single


grouping operation.
• E.g.
select DEPT_NO, COUNT(*) STRENGTH,
MIN(SALARY), MAX(SPEC_ALL),
SUM(SALARY+NVL(SPEC_ALL,0)) TOTAL_SALARY
from EMPLOYEES
group by DEPT_NO;

DE STRENGTH MIN(SALARY) MAX(SPEC_ALL) TOTAL_SALARY


-- ---------- ----------- ------------- ------------
01 3 3000 750 53500
02 5 7250 1500 55500
03 7 3000 1250 62150
04 1 13200 13200
Group By and Where Clause

• Sometimes we may want to use the WHERE clause to restrict the


rows and then apply the grouping operation. E.g.
• Show the number of new employees who joined after 1/1/2000 in a
department-wise manner.
• Solution:
select DEPT_NO, COUNT(*) from EMPLOYEES where HIRE_DATE >
TO_DATE('01-JUL-1999', 'DD-MON-YYYY') group by DEPT_NO;

DE COUNT(*)
-- ----------
01 1
02 4
03 3
04 1

The where clause first restricts the rows that are grouped.
Then the rows are grouped and the group functions are performed.
Selecting Specific Groups

• Just as we selected specific rows (using the WHERE clause), we


may want to select only specific groups. E.g.
• Show department-wise, the average of the salaries, if the average
salary exceeds Rs.12,000/-
• Here we are selecting only those groups (departments) which fulfil
the stipulated condition.
• Selection of specific groups can be accomplished by using the
having clause.

Note:
WHERE clause restricts rows while
HAVING clause restricts groups.
Having clause

• Need: To show department-wise, the average of the salaries, if the


average salary exceeds Rs.12,000/-
• Solution:
select DEPT_NO, AVG(SALARY) from EMPLOYEES group by
DEPT_NO having AVG(SALARY) > 12000;

DE AVG(SALARY)
-- -----------
01 17583.3333
04 13200

Note that the HAVING clause appears


after the GROUP BY clause
Having clause - Another example

• Need: To show department-wise, the average of the salaries, only if


there are atleast 5 employees in the department.
• Solution:
select DEPT_NO, AVG(SALARY) from EMPLOYEES group by
DEPT_NO having COUNT(*) >= 5;

DE AVG(SALARY)
-- -----------
02 10250
03 8628.57143
Having - Rules for the conditions

• Much like the rules for the selected columns in grouping operations,
the conditions in the HAVING clause should also be only group-
value functions.
select DEPT_NO, AVG(SALARY) from EMPLOYEES group by
DEPT_NO having COUNT(*) >= 5;

DE AVG(SALARY)
-- -----------
02 10250
03 8628.57143

The HAVING clause can have only group functions.

• The only exception is the usage of the grouping column itself.


However if there is such a need, it can be better done in the WHERE
clause itself.
Why the having clause need not have the grouping column

• If there is a need to select groups based on the grouping column


itself, it can be accomplished with the where clause itself.
select DEPT_NO, AVG(SALARY) from EMPLOYEES group by
DEPT_NO having DEPT_NO in ('01', '02');

DE AVG(SALARY)
-- -----------
01 17583.3333
02 10250

• Better alternative:
select DEPT_NO, AVG(SALARY) from EMPLOYEES
where DEPT_NO in ('01', '02') group by DEPT_NO;

DE AVG(SALARY)
-- ----------- This approach is faster because it
01 17583.3333 eliminates rows even before grouping!
02 10250
Grouping on multiple columns

• It is possible to group the rows on multiple columns. E.g.


• Show department-wise and year-wise, the number of new employees
recruited.

select DEPT_NO, TO_CHAR(HIRE_DATE, 'YYYY') YEAR, COUNT(*)


from EMPLOYEES
group by DEPT_NO, TO_CHAR(HIRE_DATE, 'YYYY');

DE YEAR COUNT(*)
-- ---- ----------
01 1999 3
02 1999 4
02 2000 1
03 1999 6
03 2000 1
04 1999 1

Grouping on multiple columns


Ordering the grouped result

• Normally the output of a group operation will be ordered by the


grouping column.
select DEPT_NO, AVG(SALARY)
from EMPLOYEES
group by DEPT_NO;

DE AVG(SALARY)
-- -----------
01 17583.3333
02 10250
03 8628.57143
04 13200

Ordered by the grouping column

• However we can change the order of the output by explicitly using


the order by clause.
Ordering the grouped result

• Need: Show the department-wise average salaries in descending


order.
• Solution:
select DEPT_NO, AVG(SALARY)
from EMPLOYEES
group by DEPT_NO
order by AVG(SALARY) desc;

DE AVG(SALARY)
-- -----------
01 17583.3333 Ordered explicitly
04 13200
02 10250
03 8628.57143
Ordering - Rules for the ordering columns

• Much like the rules for the selected columns and the having
conditions in grouping operations, the order by clause can only
use either group-value functions or the grouping columns.
select DEPT_NO, AVG(SALARY)
from EMPLOYEES
group by DEPT_NO
order by AVG(SALARY) desc;

DE AVG(SALARY)
-- -----------
01 17583.3333
04 13200
02 10250
03 8628.57143

The order by clause can use only group functions or the grouping columns.
Combining all clauses

• All the clauses - where, group by, having, order by


can be combined in a single select statement.

select JOB, AVG(SALARY)


from EMPLOYEES
where HIRE_DATE < TO_DATE('01-JAN-2000', 'DD-MON-YYYY')
group by JOB
having AVG(SALARY) < 15000
order by AVG(SALARY);

JOB AVG(SALARY)
-------------------- -----------
Clerk 3000
Tailor 3416.66667
Sales Executive 7666.66667
Supervisor 10500
Order of Execution

1) First the relevant rows are chosen based on the where clause
where HIRE_DATE < TO_DATE('01-JAN-2000', 'DD-MON-YYYY')

EMP NAME JOB HIRE_DATE DE MGR SALARY SPEC_ALL


--- -------------------- -------------------- --------- -- --- ---------- ----------
001 Muthukrishnan K. Director 15-APR-99 01 35500
002 Sridhara Rao Manager 19-APR-99 02 001 21000 1500
004 Kumar P. Supervisor 03-MAY-99 03 019 10500
005 Mani S. Tailor 03-MAY-99 03 004 3500
006 Vasanthi K. Tailor 03-MAY-99 03 004 3750
009 Venkataraman R. Manager 24-JUN-99 01 001 14250 750
011 Prabhuram S. Designer 25-JUN-99 03 019 15700 500
012 Denzil Ashok Sales Executive 12-JUL-99 02 002 8000 750
014 Raghu M. Sales Executive 12-JUL-99 02 002 7500 750
015 Subramaniam G. Manager 20-AUG-99 04 001 13200
016 Ganesh P.R. Clerk 03-SEP-99 01 009 3000
019 Ramarathnam R.S. Manager 16-OCT-99 03 001 20450 1250
021 Jayanthi M.S. Tailor 22-DEC-99 03 004 3000
022 Prakash D. Sales Executive 22-DEC-99 02 002 7500 750

Only 14 rows fulfill the where condition. 2 rows are eliminated.


Order of Execution

2) The groups are segregated based on the group by clause.


group by JOB

EMP NAME JOB HIRE_DATE DE MGR SALARY SPEC_ALL


--- -------------------- -------------------- --------- -- --- ---------- ----------
016 Ganesh P.R. Clerk 03-SEP-99 01 009 3000

011 Prabhuram S. Designer 25-JUN-99 03 019 15700 500

001 Muthukrishnan K. Director 15-APR-99 01 35500

002 Sridhara Rao Manager 19-APR-99 02 001 21000 1500


015 Subramaniam G. Manager 20-AUG-99 04 001 13200
009 Venkataraman R. Manager 24-JUN-99 01 001 14250 750
019 Ramarathnam R.S. Manager 16-OCT-99 03 001 20450 1250

012 Denzil Ashok Sales Executive 12-JUL-99 02 002 8000 750


014 Raghu M. Sales Executive 12-JUL-99 02 002 7500 750
022 Prakash D. Sales Executive 22-DEC-99 02 002 7500 750

004 Kumar P. Supervisor 03-MAY-99 03 019 10500

005 Mani S. Tailor 03-MAY-99 03 004 3500


006 Vasanthi K. Tailor 03-MAY-99 03 004 3750
021 Jayanthi M.S. Tailor 22-DEC-99 03 004 3000
Order of Execution

3) The group functions are calculated for each group.


select JOB, AVG(SALARY)

EMP NAME JOB HIRE_DATE DE MGR SALARY Average is:


SPEC_ALL
--- -------------------- -------------------- --------- -- --- ---------- ----------
016 Ganesh P.R. Clerk 03-SEP-99 01 009 3000 3000

011 Prabhuram S. Designer 25-JUN-99 03 019 15700 15700


500
35500
001 Muthukrishnan K. Director 15-APR-99 01 35500

002 Sridhara Rao Manager 19-APR-99 02 001 21000 1500


015 Subramaniam G. Manager 20-AUG-99 04 001 13200 17225
009 Venkataraman R. Manager 24-JUN-99 01 001 14250 750
019 Ramarathnam R.S. Manager 16-OCT-99 03 001 20450 1250

012 Denzil Ashok Sales Executive 12-JUL-99 02 002 8000 750


014 Raghu M. Sales Executive 12-JUL-99 02 002 7500 7666.6667
750
022 Prakash D. Sales Executive 22-DEC-99 02 002 7500 750

004 Kumar P. Supervisor 03-MAY-99 03 019 10500


10500
005 Mani S. Tailor 03-MAY-99 03 004 3500
006 Vasanthi K. Tailor 03-MAY-99 03 004 3750
021 Jayanthi M.S. Tailor 22-DEC-99 03 004 3000 3416.6667
Order of Execution

• One row is formed for every group. The intermediate result looks
like this:

select JOB, AVG(SALARY)

JOB AVG(SALARY)
-------------------- -----------
Clerk 3000
Designer 15700
Director 35500
Manager 17225
Sales Executive 7666.66667
Supervisor 10500
Tailor 3416.66667
Order of Execution

4) The groups are chosen based on the having clause.

having AVG(SALARY) < 15000

JOB AVG(SALARY)
-------------------- -----------
Clerk 3000
Sales Executive 7666.66667
Supervisor 10500
Tailor 3416.66667

Only 4 groups fulfill the having condition. 3 groups are eliminated.


Order of Execution

5) The output is ordered based on the order by clause.

order by AVG(SALARY);

JOB AVG(SALARY)
-------------------- -----------
Clerk 3000
Tailor 3416.66667
Sales Executive 7666.66667
Supervisor 10500

This is the final output.


Order of execution and SQL syntax

• Fortunately, the SQL syntax itself clearly depicts the order of execution:

select JOB, AVG(SALARY)


from EMPLOYEES
1) where - chooses the relevant rows where HIRE_DATE < TO_DATE
2) group by - groups the rows and calculates group functions JAN-2000', 'DD-MON-YYYY')
3) having - chooses the relevant groups group by JOB
4) order by - orders the output having AVG(SALARY) < 1500
order by AVG(SALARY);

JOB AVG(
-------------------- ----
Clerk
Tailor 341
Sales Executive 766
Supervisor
Dummy slide (not part of presentation)

EMPLOYEES
EMP_NO NAME JOB HIRE_DATE DEPT_NO MGR_NO SALARY SPEC_ALL
001 Muthukrishnan K. Director 15-APR-1999 01 35500
002 Sridhara Rao Manager 19-APR-1999 02 001 21000 1500
004 Kumar P. Supervisor 03-MAY-1999 03 019 10500
005 Mani S. Tailor 03-MAY-1999 03 004 3500
006 Vasanthi K. Tailor 03-MAY-1999 03 004 3750
009 Venkataraman R. Manager 24-JUN-1999 01 001 14250 750
011 Prabhuram S. Designer 25-JUN-1999 03 019 15700 500
012 Denzil Ashok Sales Executive 12-JUL-1999 02 002 8000 750
014 Raghu M. Sales Executive 12-JUL-1999 02 002 7500 750
015 Subramaniam G. Manager 20-AUG-1999 04 001 13200
016 Ganesh P.R. Clerk 03-SEP-1999 01 009 3000
019 Ramarathnam R.S. Manager 16-OCT-1999 03 001 20450 1250
021 Jayanthi M.S. Tailor 22-DEC-1999 03 004 3000
022 Prakash D. Sales Executive 22-DEC-1999 02 002 7500 750
023 Junaid Ismail Tailor 08-JAN-2000 03 004 3500
024 Suryakumar Sales Executive 15-FEB-2000 02 002 7250 500

You might also like