You are on page 1of 138

SQL

Structured Query Language

12/8/21 12/8/21 1 Copyright © Argam, 2006. All rights reserved.


SQL

• COALESCE • Partitioned Outer Join


• CASE enhanced • MEDIAN Function
• JOINS syntax • FLASH BACK – VERSIONS
• FULL OUTER JOIN • MODEL clause
• FLASHBACK – AS OF Functions CV() , PRESENTV(),
• DEFAULT keyword PRESENTNNV(),
• INSERT – Multi-table – Direct Path ITERATION_NUMBER
• MERGE • MERGE – DELETE clause
• Date Data types
TIMESTAMP,
TIMESTAMP WITH TIME ZONE,
TIMESTAMP WITH LOCAL TIME ZONE
• DATETIME functions
TZ_OFFSET, CURRENT_DATE,
LOCALTIMESTAMP
• Multi-Table Insert
Un-conditional, Conditional ALL, FIRST
• Create Index with create table statement
12/8/21 12/8/21 2 Copyright © Argam, 2006. All rights reserved.
SQL

Introduction
Basic SELECT statements
Restricting and Sorting Data
Single Row Function
Displaying Data from Multiple Tables
Aggregating Data using Group Functions
Sub-Queries
Manipulating Data
Creating and Managing Tables
Constraints
Views
Sequence Index Synonym
Controlling User Access
Using SET operators
Enhancement to the GROUP BY Clause
Advanced Sub-queries
Hierarchical Retrieval
Extensions to DML

12/8/21 12/8/21 3 Copyright © Argam, 2006. All rights reserved.


SQL

Introduction

12/8/21 12/8/21 4 Copyright © Argam, 2006. All rights reserved.


SQL

Database

 Every Organization had some information needs.


 Organizations can store ‘pieces of information’ called DATA.
 Data stored in different formats, hard copy document, electronic spread
sheet or in database.
 A database is an organized collection of information.
 DBMS a program that stores retrieves and modifies data in the database
on request.
 Types of Database – Hierarchical, Network, Relational, Object Relational.

12/8/21 12/8/21 5 Copyright © Argam, 2006. All rights reserved.


SQL

History of SQL
1970s, Dr. E. F. Codd an IBM researcher Codd's work led to
the definition of the relational data model and a language
called DSL/Alpha for manipulating data in a relational
database.

IBM built a project called System/R based on Codd's work.

System/R developed a simplified version of DSL called


SQUARE, which was later renamed SEQUEL, and finally
renamed SQL.

American National Standards Institute (ANSI), released its


first SQL standard in 1986, followed by updates in 1989,
1992, and 1999.

12/8/21 12/8/21 6 Copyright © Argam, 2006. All rights reserved.


SQL

Relational Database Concept

 Dr. EF. Codd proposed the relational model for database systems in 1970,
“A Relational Model of data for Large Shared Data Banks”.
 It is the basis for RDBMS
 The Relational model consists of the following :
- Collection of objects or relations.
- Set of operators to act on the relations.
- Data Integrity for accuracy and consistency.
 Definition :
A relational database is a collection of relations or
two-dimensional tables (rows & columns).

12/8/21 12/8/21 7 Copyright © Argam, 2006. All rights reserved.


SQL

Entity Relationship Model


 Entity / Table : A thing of significance about which information needs to be known.
e.g. Employees, Departments, Students, and Orders.
 Attribute / Column : Something that qualifies an entity. eg. eno, ename, ordno.,
 Relationship : Association between entities showing cardinality / degree.

EMPLOYEES DEPARTMENTS
number number
name name
job title location

Scenario:
- “ … assign one or more employees to a department…”
- “ … some departments do not yet have assigned employees…”

12/8/21 12/8/21 8 Copyright © Argam, 2006. All rights reserved.


SQL

Entity Relationship Modeling Conventions


Entity - Table Attribute - Column
Soft box Singular name
Singular, unique name Lowercase
Uppercase Mandatory marked with *
Synonym in parentheses Optional marked with o

EMPLOYEE DEPARTMENT
assigned to
# * number # * number
* name * name
composed of
o job title o location

Unique Identifier UID Relationships


Primary marked with # Dashed Line Optional “may be”
Secondary marked with (#) Solid line Mandatory “must be”
Crow’s foot Degree element “one or more”
Single line “one and only one”
12/8/21 12/8/21 9 Copyright © Argam, 2006. All rights reserved.
SQL

Relational Database Terminology


Primary Key Column Non-key value Foreign Key

ENO ENAME SALARY COMM_PCT DNO


100 King 24000 90

Row / Record 101 Kochhar 17000 90


102 Rey 6000 null 60
103 DeCarl 3500 50
104 Abel 11000 .3 80
105 Grant 7000 .15 80
106 Reyarndo 8300 110

field

12/8/21 12/8/21 10 Copyright © Argam, 2006. All rights reserved.


SQL

Data Models

Model of system
in client’s mind

Entity model of
client’s model

Table model of
Oracle Server
entity model

Tables on disk

12/8/21 12/8/21 11 Copyright © Argam, 2006. All rights reserved.


SQL

Architecture Oracle 8i
Database

Data Dictionary Components

Oracle Product Non-Oracle Product


SQL, PL/SQL, Developer, Forms ... Java, XML, HTML ...
12/8/21 12/8/21 13 Copyright © Argam, 2006. All rights reserved.
SQL

Architecture Oracle 9i

Two Tier Three Tier


Database

Application Server

Oracle Product Non-Oracle Product


SQL, PL/SQL, Developer, Forms ... Java, XML, HTML ...
12/8/21 12/8/21 14 Copyright © Argam, 2006. All rights reserved.
SQL

Server Architecture

Dedicated Server Shared Server

Database Database

X A B C
12/8/21 12/8/21 15 Copyright © Argam, 2006. All rights reserved.
SQL

Communicating with a RDBMS using SQL

SQL Statement SELECT last_name


is entered FROM employees;

Statement is sent
LAST_NAME
to Oracle Server
King

Kochhar Oracle Server

Reynardo
DeCarl

Abel
Grant
12/8/21 12/8/21 16 Copyright © Argam, 2006. All rights reserved.
SQL

SQL Statements
Data Retrieval
SELECT

Data Manipulation Language (DML)


CALL DELETE EXPLAIN PLAN
INSERT LOCK TABLE MERGE
UPDATE

Data Definition Language (DDL)


CREATE ALTER DROP RENAME TRUNCATE

Transaction Control Language (TCL)


COMMIT ROLLBACK SAVEPOINT SET TRANSACTION

Data Control Language (DCL)


GRANT REVOKE

Session Control Statements System Control Statements


ALTER SESSION ALTER SYSTEM

12/8/21 12/8/21 17 Copyright © Argam, 2006. All rights reserved.


SQL

Summary

 Relational databases are composed of relations, managed by


relational operations, and governed by data integrity constraints.
 The Oracle is the database for Internet Computing and
based on the ORDBMS.
 Oracle Server supports ANSI standard SQL and contains
extensions.
 SQL is the language used to communicate with the server to
access, manipulate, and control data.

12/8/21 12/8/21 19 Copyright © Argam, 2006. All rights reserved.


SQL

Writing Basic SQL


SELECT Statements

12/8/21 12/8/21 20 Copyright © Argam, 2006. All rights reserved.


SQL

Capabilities of SQL SELECT Statements


Table A Projection Table B Selection

Joins

Table A Table B

12/8/21 12/8/21 21 Copyright © Argam, 2006. All rights reserved.


SQL

Basic SELECT Statement

SELECT *|{[DISTINCT] column|expression [ alias],…}


FROM table;

SELECT identifies what column(s)


FROM identifies which table

Selecting All Columns

SELECT *
FROM departments;

12/8/21 12/8/21 22 Copyright © Argam, 2006. All rights reserved.


SQL

Selecting Specific Columns


SELECT department_id, location_id
FROM departments;

Writing SQL Statements

 SQL Statements are not case sensitive.


 SQL statements can be on one or more lines.
 Key words cannot be abbreviated or split across lines.
 Clauses are usually placed on separate lines.

12/8/21 12/8/21 23 Copyright © Argam, 2006. All rights reserved.


SQL

Arithmetic Expressions
Create expressions with number and date data by using arithmetic
operators.

SELECT last_name, salary, salary+300


FROM employees;

Operator Precedence

SELECT last_name,salary,12*salary+300,12+salary*300

FROM employees;
Override the rule by using
Parentheses 12*(salary+300)

12/8/21 12/8/21 24 Copyright © Argam, 2006. All rights reserved.


SQL

Defining a Null Value


 A NULL is a value that is unavailable, unassigned, unknown,
or inapplicable.
 A null is not the same as zero or a blank space.
 Arithmetic expressions containing a null value evaluate to null.

ENO ENAME SALARY COMM COMM+1 DNO


100 King 24000 .3 1.3 90
101 Kochhar 17000 90
102 Ernst 6000 60
103 Rajs 3500 50
104 Abel 11000 .5 1.5 80
105 Grant 7000 .15 1.15 40
106 Gietz 8300 110
12/8/21 12/8/21 25 Copyright © Argam, 2006. All rights reserved.
SQL

Defining a Column Alias


 Renames a column heading.
 Is useful with calculations.
 Immediately follows the column name, AS keyword can be
optional between the column name and alias.
 Requires double quotation marks if it contains spaces or
special characters or is case sensitive.

SELECT last_name AS name, commission_pct comm


FROM employees;

SELECT last_name AS “Name”, salary*12 “Annual Salary”


FROM employees;

12/8/21 12/8/21 26 Copyright © Argam, 2006. All rights reserved.


SQL

Concatenation Operator
 Concatenates columns or character strings to other columns.

 Is represented by two vertical bars ||

SELECT last_name||job_id AS “Employees”


FROM employees;

 Date and character literal values must be enclosed within


single quotation marks.

 Each character string is output once for each row returned.

SELECT last_name||’ is a ‘||job_id AS “Employees”


FROM employees;

12/8/21 12/8/21 27 Copyright © Argam, 2006. All rights reserved.


SQL

Duplicate Rows
 The default display of queries is all rows, including duplicate rows

SELECT department_id
FROM employees;

 Eliminate duplicate rows by using the DISTINCT or UNIQUE


keyword in the SELECT clause. You cannot specify
SELECT DISTINCT department_id DISTINCT if the
select_list contains
FROM employees;
LOB columns.

Display Table Structure


DESC[RIBE] tablename;

DESCRIBE employees; DESC employees;

12/8/21 12/8/21 28 Copyright © Argam, 2006. All rights reserved.


SQL

Summary
SELECT statement
- Returns all rows and columns from a table
- Returns specified columns from a table
- Uses column aliases to give descriptive column headings

To write, save, execute the SQL statements


use the i*SQLPlus environment, SQL WorkSheet.
SELECT *|{[DISTINCT] column|expression [ alias],…}
FROM table;

12/8/21 12/8/21 29 Copyright © Argam, 2006. All rights reserved.


SQL

Restricting and Sorting Data

12/8/21 12/8/21 30 Copyright © Argam, 2006. All rights reserved.


SQL

Limiting Rows using a Selection

The WHERE clause follows the FROM clause

SELECT *|{[DISTINCT] column|expression [ alias],…}


FROM table
[ WHERE condition(s) ];

 “… retrieve all employees in department 90 .”

SELECT employee_id, last_name, department_id


FROM employees
WHERE department_id = 90;

12/8/21 12/8/21 31 Copyright © Argam, 2006. All rights reserved.


SQL

Character Strings and Dates


 Character strings and date values are enclosed in single
quotation marks.
 Character values are case sensitive, and
Date values are format sensitive.
 The default date format is DD-MON-RR.

SELECT employee_id, last_name, department_id


FROM employees
WHERE last_name = ‘Adam’;

12/8/21 12/8/21 32 Copyright © Argam, 2006. All rights reserved.


SQL

Comparison Conditions
 Used in conditions that compare one expression to another
value or expression.

SELECT employee_id, last_name, department_id


FROM employees
WHERE last_name = ‘Adam’;

WHERE hire_date = ’01-Jan-95’ ;


WHERE salary >= 6000 ;
WHERE department_id <> 80 ; != ^=

12/8/21 12/8/21 33 Copyright © Argam, 2006. All rights reserved.


SQL

BETWEEN Condition
 Use the BETWEEN condition to display rows based on a
range of values.
SELECT employee_id, last_name, salary
FROM employees
WHERE salary BETWEEN 2500 AND 3500 ;

Lower limit Upper limit

IN Condition
 Use the IN membership condition to test for values in a list.

SELECT employee_id, last_name, salary, manager_id


FROM employees
WHERE manager_id IN (100, 101, 201) ;

12/8/21 12/8/21 34 Copyright © Argam, 2006. All rights reserved.


SQL

LIKE Condition
 LIKE condition to perform wildcard searches of valid search
string values.
 Can contain either literal character or numbers
% denotes zero or many characters.
_ denotes any single character.

SELECT employee_id, last_name


FROM employees
WHERE last_name LIKE ‘S%’;

 Use the ESCAPE identifier to search for the


actual % and _ symbols
SELECT employee_id, last_name, job_id
FROM employees
WHERE job_id LIKE ‘SA\_%’ ESCAPE ‘\’;

12/8/21 12/8/21 35 Copyright © Argam, 2006. All rights reserved.


SQL

Using the NULL Conditions


 Test for nulls with the IS NULL operator.

SELECT employee_id, last_name, manager_id

FROM employees
WHERE manager_id IS NULL;

Logical Conditions
AND Returns TRUE if both component conditions are true

OR Returns TRUE if either component condition are true

NOT Returns TRUE if the following condition is false

12/8/21 12/8/21 36 Copyright © Argam, 2006. All rights reserved.


SQL

Using the AND Operator


 AND requires both conditions to be true.

SELECT employee_id, last_name, job_id, salary


FROM employees
WHERE salary >= 10000
AND job_id LIKE ‘%MAN%’;

Using the OR Operator


 OR requires either condition to be true.

SELECT employee_id, last_name, job_id, salary


FROM employees
WHERE salary >= 10000
OR job_id LIKE ‘%MAN%’;

12/8/21 12/8/21 37 Copyright © Argam, 2006. All rights reserved.


SQL

Using the NOT Operator


SELECT employee_id, last_name, job_id
FROM employees
WHERE job_id NOT IN (‘IT_PROG’, ‘ST_CLERK’);

Rules of Precedence
1 Arithmetic operators
2 Concatenation operators
3 Comparison Conditions
4 IS [NOT] NULL, LIKE, [NOT] IN
5 [NOT] BETWEEN
6 NOT logical condition
7 AND logical condition
8 OR logical condition
Override rules of precedence by using parentheses
12/8/21 12/8/21 38 Copyright © Argam, 2006. All rights reserved.
SQL

Rule of Precedence

SELECT last_name, job_id, salary


FROM employees
WHERE job_id = ‘SA_REP’
OR job_id = ‘AD_PRES’
AND salary > 15000;

Select the row if an employee is AD_PRES and earns more than 15000,
or if the employee is a SA_REP

SELECT last_name, job_id, salary


FROM employees
WHERE (job_id = ‘SA_REP’
OR job_id = ‘AD_PRES’)
AND salary > 15000;

Select the row if an employee is AD_PRES or SA_REP , and if the


employee earns more than 15000.
12/8/21 12/8/21 39 Copyright © Argam, 2006. All rights reserved.
SQL

ORDER BY Clause
 Sort rows with the ORDER BY clause

- ASC ascending order, default


- DESC descending order
 The ORDER BY clause comes last in the SELECT statement

SELECT employee_id, last_name, job_id, salary


FROM employees
ORDER BY hire_date;

ORDER BY salary DESC ;

12/8/21 12/8/21 40 Copyright © Argam, 2006. All rights reserved.


SQL

Sorting by Column Alias


SELECT employee_id, last_name, salary*12 annsal
FROM employees
ORDER BY annsal ;

Sorting by Column position


SELECT employee_id, last_name, salary*12 annsal
FROM employees
ORDER BY 3 ;

Sorting by Multiple Columns


SELECT last_name, department_id, salary
FROM employees
ORDER BY department_id, salary DESC ;

 You can sort by a column that is not in the SELECT list

12/8/21 12/8/21 41 Copyright © Argam, 2006. All rights reserved.


SQL

Summary
 Use WHERE clause to restrict rows of output
- Use the comparison conditions
- Use the BETWEEN, IN, LIKE, and NULL conditions
- Apply the logical AND, OR, and NOT operators

 Use the ORDER BY clause to sort rows of output

SELECT *|{[DISTINCT] column|expression [ alias],…}


FROM table
[ WHERE condition(s) ]
[ORDER BY {column, expr, alias} [ASC|DESC]];

12/8/21 12/8/21 42 Copyright © Argam, 2006. All rights reserved.


SQL

Single-Row Functions

12/8/21 12/8/21 43 Copyright © Argam, 2006. All rights reserved.


SQL

SQL Functions
Input

Function Output

Function returns
arg 1 a value
arg 2
arg n Result value

Function

Single-row Multiple-row
functions functions
Input Output Input Output

12/8/21 12/8/21 44 Copyright © Argam, 2006. All rights reserved.


SQL

Single-Row Functions
 Manipulate data items
 Accepts arguments and returns one value
 Act on each row returned
 Return one result per row
 Displays the input/output requested data format
 Can be nested
 Accept arguments which can be a column or an expression

function_name [(arg1, arg2,…)];

12/8/21 12/8/21 45 Copyright © Argam, 2006. All rights reserved.


SQL

Character Functions

 Case-manipulation functions

LOWER(‘Hello Bangalore’) hello bangalore


UPPER(‘Hello Bangalore’) HELLO BANGALORE
INITCAP(‘HeLlo BangAlore’) Hello Bangalore

SELECT employee_id, last_name, department_id


FROM employees
WHERE lower(last_name) = ‘abel’;

12/8/21 12/8/21 46 Copyright © Argam, 2006. All rights reserved.


SQL

Character Functions
 Character - manipulation functions
CONCAT(‘Hello’, ’World’) HelloWorld
SUBSTR(‘HelloWorld,1,5) Hello
LENGTH(‘HelloWorld’) 10
INSTR(‘HelloWorld’,’o’) 5
LPAD(salary,10,’*’) *****24000
RPAD(salary,8,’#’) 9900####
WHERE SOUNDEX(city) = SOUNDEX(‘Sidny’)
RTRIM(’AMERICA’, ‘A’) AMERIC
LTRIM(’AMERICA’, ‘A’) MERICA

TRIM(‘H’ FROM ’HelloWorld’) elloWorld


TRIM(‘A’ FROM ’AMERICA’) MERIC
12/8/21 12/8/21 47 Copyright © Argam, 2006. All rights reserved.
SQL

Number Functions
ABS(-6) 6
ABS(6) 6
CEIL(1.4) 2
FLOOR(1.6) 1
SIGN(-25) -1
SIGN(25) 1
SQRT(36) 6
VSIZE(city) – The storage size in bytes

For any datatype :


GREATEST(10,45,100,1) 100
LEAST(10,45,100,1) 1

12/8/21 12/8/21 48 Copyright © Argam, 2006. All rights reserved.


SQL

Number Functions
 ROUND : Rounds value to specified decimal
SELECT ROUND(45.923,2),ROUND(45.923,0),ROUND(45.923,-1)
FROM DUAL;
45.92 46 50

DUAL is a dummy table you can use to view results from functions and calculations

 TRUNC : Truncates value to specified decimal


SELECT TRUNC(45.923,2),TRUNC(45.923),TRUNC(45.923,-2)
FROM DUAL;
45.92 45 0
 MOD : Returns remainder of division
SELECT MOD(10,3), MOD(10,7)
1 3
FROM DUAL;

12/8/21 12/8/21 49 Copyright © Argam, 2006. All rights reserved.


SQL

Working with Dates


 Oracle database stores Dates in an internal numeric format :
Century, Year, Month, Day, Hours, Minutes, Seconds
Eg. 15-Jan-2005 2:00 PM
C Y M D H M S
20 05 01 15 14 00 15

 Default Display format DD-MON-RR.

 Valid Oracle Dates between


January 1, 4712 BC and December 31, 9999 AD

 SYSDATE function returns current database server


Date and Time
SELECT SYSDATE
FROM DUAL;

12/8/21 12/8/21 50 Copyright © Argam, 2006. All rights reserved.


SQL

Arithmetic with Dates

 Date + Number Date Adds a number of days


 Date – Number Date Subtracts a number of days
 Date – Date no. of days Subtracts one date from
another
 Date + Number/24 Date Adds a number of hours to
a date

SELECT last_name, (SYSDATE-hire_date)/7 as WEEKS

FROM employees
WHERE department-id = 90;

12/8/21 12/8/21 51 Copyright © Argam, 2006. All rights reserved.


SQL

 Date functions
MONTHS_BETWEEN(’15-NOV-05’,’01-SEP-05’) -> 1.5
ADD_MONTHS(’11-JAN-95’,6) -> ’11-JUL-95’
NEXT_DAY(’01-JUN-05’,’FRIDAY’) -> ’03-JUN-05’
LAST_DAY(’18-FEB-08’) -> ’29-FEB-08’

 Assume SYSDATE = ’25-JUL- 05’;


ROUND(SYSDATE, ‘MONTH’) -> 01-Aug-05
ROUND(SYSDATE, ‘YEAR’) -> 01-Jan-06
TRUNC(SYSDATE, ‘MONTH’) -> 01-Jul-05
TRUNC(SYSDATE, ‘YEAR’) -> 01-Jan-05

12/8/21 12/8/21 52 Copyright © Argam, 2006. All rights reserved.


SQL

Conversion Function
 Implicit Data Type Conversion

 Explicit Data Type Conversion

TO_NUMBER TO_DATE

NUMBER CHARACTER DATE

TO_CHAR TO_CHAR

SELECT employee_id, TO_CHAR (hire_date,’MM/YY’)


FROM employees;

12/8/21 12/8/21 53 Copyright © Argam, 2006. All rights reserved.


SQL

Elements of the Date Format Model


YYYY Full year in number

YEAR Year spelled out

MM Two-digit value of month

MONTH Full name of the month

MON Three-letter abbreviation of the month

DY Three-letter abbreviation of the day of the week

DAY Full name of the day of the week

DD Numeric day of the month

WW W Week of year or month

RM Roman Number

J Julian day; the number of days since 31 Dec 4713 BC


12/8/21 12/8/21 54 Copyright © Argam, 2006. All rights reserved.
SQL

Elements of the Date Format Model


SELECT to_char(sysdate,’DD-Mon-YYYY HH24:MI:SS AM’)
FROM dual;

DD “of” MONTH 4 of October


DDth 4th
DDsp FOUR
Ddspth Fourth

SELECT last_name,
to_char(hire_date,’fmDD Mon YYYY’) Hiredate
FROM employees;

12/8/21 12/8/21 55 Copyright © Argam, 2006. All rights reserved.


SQL

Using TO_CHAR function with numbers

SELECT last_name,
TO_CHAR(salary,’L9,999,999.99’) Sal
FROM employees;

9 Represents a number
0 forces a zero to be displayed
$ places a floating dollar sign
L Uses the floating local currency symbol
. Prints a decimal point
, Prints a thousand indicator

12/8/21 12/8/21 56 Copyright © Argam, 2006. All rights reserved.


SQL

General Functions
 These function work with any data type and pertain to using nulls.
NVL function
 Converts a null to an actual value
- Data type must match
NVL(commission_pct,0)
NVL(hire_date,’01-Jan-05’)
NVL(job_id,’No Job Yet’)

NVL2 function
 NVL2(expr1, expr2, expr3)
- examine the expr1, if expr1 is null returns expr3,
if expr1 is not null returns expr2

NVL2(commission_pct,’SAL+COMM’, ‘SAL’)
12/8/21 12/8/21 57 Copyright © Argam, 2006. All rights reserved.
SQL

NULLIF function
 NULLIF(expr1, expr2)
- expr1 compares to expr2, if both are equal returns null
if both are not equal expr1 is returned

NULLIF(length(first_name), length(last_name))

NVL(first_name, (NVL(last_name,’No Name’)))

COALESCE function
 COALESCE(expr1, expr2, expr3, .. exprn)
- returns the first non null expression

COALESCE(first_name, last_name, ’No Name’)


12/8/21 12/8/21 58 Copyright © Argam, 2006. All rights reserved.
SQL
DECODE Function
SELECT last_name, job_id, salary,
DECODE (job_id, ‘IT_PROG’, 1.10*salary,
‘ST_CLERK’, 1.15*salary,
‘SA_REP’, 1.20*salary,
salary) “Revised Salary”
FROM employees;
CASE Expression
 Facilitates conditional inquiries by doing the work of an
IF-THEN-ELSE statement
SELECT last_name, job_id, salary,
CASE job_id WHEN ‘IT_PROG’ THEN 1.10*salary
WHEN ‘ST_CLERK’ THEN 1.15*salary
ELSE salary END “Revised Salary”
FROM employees;
If the WHEN clause that matches, the subsequent
WHEN clauses are not evaluated.
SELECT course_name,
CASE WHEN period >= 1 AND period <=3 THEN ‘Morning’
WHEN period >= 4 AND period <=6 THEN ‘Afternoon’
ELSE ‘After School’ END FROM course;
12/8/21 12/8/21 59 Copyright © Argam, 2006. All rights reserved.
SQL

RR Date Format
If the specified two-digit year is
0-49 50-99

If two digits 0-49 the return date is The return date is in the
of the in the current century century before the
current year current one
are
50-99 the return date is The return date is in the
in the century after current century
the current one

Current Year Specified date RR Format YY Format


. 1995 27-Oct-95 1995 1995
. 1995 27-Oct-17 2017 1917
. 2001 27-Oct-17 2017 2017
. 2001 27-Oct-95 1995 2095

12/8/21 12/8/21 60 Copyright © Argam, 2006. All rights reserved.


SQL

Example of RR Date Format


The following command results in no rows being selected
because the YY format interprets the year portion of the date in
the current century (2090).
SELECT last_name, TO_CHAR(hire_date, 'DD-Mon-yyyy')
FROM employees
WHERE TO_DATE(hire_date, 'DD-Mon-yy') < '01-Jan-90';
no rows selected
To find employees hired prior to 1990, use the RR
format, which produces the same results whether the
command is run in 1999 or now:

SELECT last_name, TO_CHAR(hire_date, 'DD-Mon-YYYY')


FROM employees
WHERE hire_date < TO_DATE('01-Jan-90', 'DD-Mon-RR');

12/8/21 12/8/21 61 Copyright © Argam, 2006. All rights reserved.


SQL

Summary
 Perform calculations on data using functions
 Modify individual data items using functions
 Manipulate output for groups of rows using functions
 Alter date format for display using functions
 Use NVL, NVL2, NULLIF, COALESCE
 Use IF-THEN-ELSE logic DECODE - CASE

12/8/21 12/8/21 62 Copyright © Argam, 2006. All rights reserved.


SQL

Displaying data from Multiple Tables

12/8/21 12/8/21 63 Copyright © Argam, 2006. All rights reserved.


SQL

Cartesian Products / Cross Joins


 A join condition is omitted
 A join is invalid
 All rows in the first table are joined to all rows in the second table
 To avoid, always include a valid join condition in a WHERE clause

SELECT last_name, department_name Dname


FROM employees, departments;

 This is the same as a Cartesian Product between two tables

SELECT last_name, department_name


FROM employees CROSS JOIN departments;
12/8/21 12/8/21 64 Copyright © Argam, 2006. All rights reserved.
SQL
USING Clause
 Matches only one column when more than one column matches.
 Do not use a table name or alias in the referenced columns

SELECT e.employee_id, e.last_name, d.location_id


FROM employees e JOIN departments d
USING (department_id);

SELECT e.employee_id, e.last_name, d.location_id


FROM employees e, departments d
WHERE e.department_id = d.department_id;

(Non-equi Join)
SELECT e.eno, e.ename, s.grade
FROM emp e, salgrade s
WHERE e.sal BETWEEN s.losal AND s.hisal;

12/8/21 12/8/21 66 Copyright © Argam, 2006. All rights reserved.


SQL

ON Clause (Self join)


 The join condition for the natural join is equi-join,
Use this clause to specify a join condition.

 Find the name of the Manager for each employee.

SELECT e.employee_id, e.last_name, e.manager_id,


m.last_name
FROM employees e JOIN employees m
ON (e.manager_id = m.employee_id);

SELECT e.employee_id, e.last_name, e.manager_id,


m.last_name
FROM employees e , employees m
WHERE e.manager_id = m.employee_id ;

12/8/21 12/8/21 67 Copyright © Argam, 2006. All rights reserved.


SQL

Creating Three-way joins with the ON Clause


SELECT employee_id, city, department_name
FROM employees e
JOIN departments d
ON d.department_id = e.department_id
JOIN locations l
ON d.location_id = l.location_id;

SELECT employee_id, city, department_name


FROM employees e, departments d, locations l
WHERE e.department_id = d.department_id
AND d.location_id = l.location_id;

 To join N tables, minimum N-1 join condition required


12/8/21 12/8/21 68 Copyright © Argam, 2006. All rights reserved.
SQL

LEFT OUTER JOIN


 This retrieves all rows in the Employees, which is the left table
even if there is no match in the departments table.

SELECT e.last_name,e.department_id, d.department_name


FROM employees e
LEFT OUTER JOIN departments d
ON (e.department_id = d.department_id);

SELECT e.last_name,e.department_id, d.department_name


FROM employees e, departments d
WHERE e.department_id = d.department_id(+) ;

12/8/21 12/8/21 69 Copyright © Argam, 2006. All rights reserved.


SQL

RIGHT OUTER JOIN


 This retrieves all rows in the Departments, which is the right
table even if there is no match in the Employees table.

SELECT e.last_name,e.department_id, d.department_name


FROM employees e
RIGHT OUTER JOIN departments d
ON (e.department_id = d.department_id);

SELECT e.last_name,e.department_id, d.department_name


FROM employees e, departments d
WHERE e.department_id(+) = d.department_id;

12/8/21 12/8/21 70 Copyright © Argam, 2006. All rights reserved.


SQL

FULL OUTER JOIN


 This retrieves all rows in the Employees , even if there is no
match in the Departments table.
 It also retrieves all rows in the Departments table, even if there
is no match in the Employees table.

SELECT e.last_name,e.department_id, d.department_name


FROM employees e
FULL OUTER JOIN departments d
ON (e.department_id = d.department_id);

12/8/21 12/8/21 71 Copyright © Argam, 2006. All rights reserved.


SQL

Summary
CROSS JOIN
NATURAL JOIN
USING
ON
LEFT OUTER JOIN
RIGHT OUTER JOIN
FULL OUTER JOIN

12/8/21 12/8/21 72 Copyright © Argam, 2006. All rights reserved.


SQL

Aggregating Data
Using Group Functions

12/8/21 12/8/21 73 Copyright © Argam, 2006. All rights reserved.


SQL

What are Group Functions ?


 Group functions operates on set of rows to give
one result per group. Multiple-row
Input Output
functions

“The maximum salary in the Employees table”

SELECT AVG(salary), SUM(salary),


MIN(salary), MAX(salary)
FROM employees;

SELECT MIN(hire_date), MAX(hire_date),


MIN(last_name), MAX(last_name)
FROM employees;
12/8/21 12/8/21 74 Copyright © Argam, 2006. All rights reserved.
SQL

Using the COUNT Function


 COUNT(*) returns the number of rows in a table

SELECT COUNT(*)
FROM employees;

COUNT(expr) returns the number of rows with non-null values


for the expr

SELECT COUNT(commission_pct)
FROM employees
WHERE department_id = 80;

12/8/21 12/8/21 75 Copyright © Argam, 2006. All rights reserved.


SQL

Using the DISTINCT Keyword


 COUNT(DISTINCT expr)
returns the number of distinct non-null values of the expr

SELECT COUNT(DISTINCT department_id)


FROM employees;

Group Functions and Null Values


 Group functions ignore null values in the column

SELECT AVG(commission_pct)
FROM employees;

12/8/21 12/8/21 76 Copyright © Argam, 2006. All rights reserved.


SQL

Using NVL Function with Group Functions

 The NVL function forces group functions to include null values

SELECT AVG(NVL(commission_pct,0))
FROM employees;

12/8/21 12/8/21 77 Copyright © Argam, 2006. All rights reserved.


SQL

Creating Groups of Data


“The average salary in the Employees table for each department”

 Divide rows in table into smaller groups by using


GROUP BY Clause

SELECT *|{[DISTINCT] column|expression [ alias],…}


FROM table
[ WHERE condition(s) ]
[ GROUP BY group_by_expression ]
[ORDER BY {column, expr, alias} [ASC|DESC]];

12/8/21 12/8/21 78 Copyright © Argam, 2006. All rights reserved.


SQL

Using GROUP BY Clause


 All column(s) in the SELECT list that are not group functions
must be in the GROUP BY clause.

SELECT department_id, AVG(salary)


FROM employees
GROUP BY department_id;

 The GROUP BY column(s) does not have to be in the SELECT list

SELECT AVG(salary)
FROM employees
GROUP BY department_id;
12/8/21 12/8/21 79 Copyright © Argam, 2006. All rights reserved.
SQL

Using the GROUP BY Clause on Multiple Columns

SELECT department_id dept_id, job_id, SUM(salary)


FROM employees
GROUP BY department_id, job_id;

Excluding Group Results


“The maximum salary per department where it is greater than 10000”

SELECT department_id, MAX(salary)


FROM employees
GROUP BY department_id
HAVING MAX(salary) > 10000;

12/8/21 12/8/21 80 Copyright © Argam, 2006. All rights reserved.


SQL

Nested Group Functions


“Display the maximum average salary”

SELECT MAX(AVG(SALARY))
FROM employees
GROUP BY department_id;

Group Function can be nested to a depth of Two

12/8/21 12/8/21 81 Copyright © Argam, 2006. All rights reserved.


SQL

Summary
 Use the group functions
 Write queries that use the GROUP BY clause
 Write queries that use the HAVING clause

SELECT *|{[DISTINCT] column|expression [ alias],…}


FROM table
[ WHERE condition(s) ]
[ GROUP BY group_by_expression ]
[ HAVING group_condition ]
[ORDER BY {column, expr, alias} [ASC|DESC]];

12/8/21 12/8/21 82 Copyright © Argam, 2006. All rights reserved.


SQL

Sub-Queries

12/8/21 12/8/21 83 Copyright © Argam, 2006. All rights reserved.


SQL

Using a Subquery to Solve a Problem


Which employees have salaries greater than Abel’s salary ?

You need two queries :


First, find what Abel earns, and
Second, find who earns more than that amount.

What is the Abel’s Salary 1

Combine two queries, placing one query inside the other query.
i.e. “Query within a query.”
12/8/21 12/8/21 84 Copyright © Argam, 2006. All rights reserved.
SQL

Sub-query
SELECT select_list
FROM table
WHERE expr operator ( SELECT select_list
FROM table );

The subquery (inner query) executes once before the main query.
The result of the subquery is used by the main query(outer query).

SELECT last_name
FROM employees
WHERE salary > ( SELECT salary FROM employees
WHERE last_name =‘Abel’ );

12/8/21 12/8/21 85 Copyright © Argam, 2006. All rights reserved.


SQL

Types of Subqueries

SELECT select_list
FROM table
WHERE expr operator ( SELECT select_list
FROM table );

 Single-row subquery
ST_CLERK

 Multiple-row subquery
ST_CLERK
SA_MAN

12/8/21 12/8/21 86 Copyright © Argam, 2006. All rights reserved.


SQL

Single Row Subqueries


 Returns only one value
 Use single-row comparison operators
= < <= > >= <>
SELECT last_name, job_id
FROM employees
WHERE job_id = ( SELECT job_id FROM employees
WHERE employee_id = 141 );

SELECT last_name, job_id, salary


FROM employees
WHERE job_id = ( SELECT job_id FROM employees
WHERE employee_id = 141 )
AND salary > ( SELECT salary FROM employees
WHERE employee_id = 143 );

12/8/21 12/8/21 87 Copyright © Argam, 2006. All rights reserved.


SQL

Using Group Functions in a Subquery

SELECT last_name, job_id, salary


FROM employees
WHERE salary = ( SELECT MIN(salary) FROM employees);

The HAVING clause with Subqueries


SELECT department_id, MIN(salary)
FROM employees
GROUP BY department_id
HAVING MIN(salary) > ( SELECT MIN(salary)
FROM employees
WHERE department_id = 50);

12/8/21 12/8/21 88 Copyright © Argam, 2006. All rights reserved.


SQL

Will this statement Return Rows ?


SELECT last_name, job_id
FROM employees
WHERE job_id = ( SELECT job_id FROM employees
WHERE last_name = ‘Xyz’);

 If subquery returns no rows, main query returns null result

Null values in the Subquery


SELECT last_name, job_id
FROM employees
WHERE job_id = ( SELECT job_id FROM employees
WHERE last_name = ‘Haas’);

 If subquery returns null values, main query returns null result

12/8/21 12/8/21 89 Copyright © Argam, 2006. All rights reserved.


SQL

What is Wrong in this Statement


SELECT last_name, job_id
FROM employees
WHERE salary = ( SELECT MIN(salary) FROM employees
GROUP BY department_id);

 Single row operator with multiple-row subquery

Using the IN Operator


 Equal to any member in the list

SELECT last_name, salary, department_id


FROM employees
WHERE salary IN ( SELECT MIN(salary) FROM employees
GROUP BY department_id);

12/8/21 12/8/21 90 Copyright © Argam, 2006. All rights reserved.


SQL

Using the ANY Operator


 Compare value to each values returned by the subquery

SELECT last_name, salary, department_id


FROM employees
WHERE salary < ANY ( SELECT salary FROM employees
WHERE job_id = ‘IT_PROG’);

Using the ALL Operator


 Compare value to every values returned by the subquery

SELECT last_name, salary, department_id


FROM employees
WHERE salary < ALL ( SELECT salary FROM employees
WHERE job_id = ‘IT_PROG’);

12/8/21 12/8/21 91 Copyright © Argam, 2006. All rights reserved.


SQL

Summary
 Write subqueries when a query is based on unknown values

SELECT select_list
FROM table
WHERE expr operator ( SELECT select_list
FROM table );

12/8/21 12/8/21 92 Copyright © Argam, 2006. All rights reserved.


SQL

SQL*Plus Formating Elements

12/8/21 12/8/21 93 Copyright © Argam, 2006. All rights reserved.


SQL

Column Headings
COLUMN employee_name HEADING “Employee Name”
Employee Name
-------------

COLUMN employee_name HEADING “Employee | Name”


Employee
Name SET UNDERLINE @
--------

COLUMN employee_name HEADING “Employee | Name” JUSTIFY RIGHT


COLUMN employee_name HEADING “Employee | Name” JUSTIFY CENTER

Page Width SET LINESIZE 60 Page Length SET PAGESIZE 50

12/8/21 12/8/21 94 Copyright © Argam, 2006. All rights reserved.


SQL

COLUMN department_name FORMAT A15 Heading DNAME


COLUMN department_id FORMAT 9999 Heading JOB

SELECT department_name,department_id
FROM departments d;

12/8/21 12/8/21 95 Copyright © Argam, 2006. All rights reserved.


SQL

Value Format Result


123 9999 123
1234.01 9,999.99 1,234.01
23456 $999,999.99 $23,456.00
1 0999 0001
1 99099 001
-1000.01 9,999.9mi 1,000.01-
1001 S9,999 +1,001
-1001 9,999PR <1,001>
1001 9,999PR 1,001

12/8/21 12/8/21 96 Copyright © Argam, 2006. All rights reserved.


SQL

Defining a Title
BTITLE
TTITLE LEFT “My Company”
CENTER “Current”
RIGHT “Page” FORMAT 999 SQL.PNO SKIP 1
CENTER “Employee Listing” SKIP 4

My Company Current Page 1 SQL.RELEASE


Employee Listing SQL.USER

Getting the Date into a title

COLUMN curdate NEW_VALUE report_date


SELECT to_char(sysdate,’dd’mon-yyyy’) curdate
FROM dual;

BTITLE LEFT “Report Date : “ report_date

12/8/21 12/8/21 97 Copyright © Argam, 2006. All rights reserved.


SQL
Report Breaks
BREAK ON owner
The below above example causes a
SELECT owner, table_name page break to occur whenever an
FROM all_tables owner changes, and a blank line to be
ORDER BY owner,table_name; printed whenever an owner changes,
and a blank line to be printed whenever
OWNER TABLE_NAME the object type changes :
---------------------- --------------------------
CTYSYS DR$CLASS BREAK ON owner SKIP PAGE
DR$DELETE ON object_type SKIP 1
DR$INDEX
SELECT owner, object_type,
SCOTT CUSTOMER
object_name
DEPARTMENT
EMPLOYEE
FROM dba_objects
ORDER BY owner,
object_type, object_name;
BREAK ON owner SKIP 1
BREAK ON owner SKIP PAGE

12/8/21 12/8/21 98 Copyright © Argam, 2006. All rights reserved.


SQL

Creating and Managing Tables

12/8/21 12/8/21 99 Copyright © Argam, 2006. All rights reserved.


SQL

Table
Basic unit of storage ; composed of rows and columns

CREATE TABLE [schema.]table


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

TABLE name and COLUMN name


 Must begin with a letter
 Must between 1-30 characters long
 Must contain only A-Z, a-z, 0-9, _ , $ , #
 Must not be an Oracle server reserved word

12/8/21 12/8/21 100 Copyright © Argam, 2006. All rights reserved.


SQL

Creating Table
CREATE TABLE student

(sno number(2),
sname varchar2(15),
dob date,
age number(2),
tno number(2));
CREATE TABLE teacher
(tno number(2),
tname varchar2(15),
dept varchar2(15) DEFAULT ‘no dept’);
Creating a table by using a Subquery
CREATE TABLE dept80
AS SELECT employee_id, last_name, hire_date,
department_id
FROM employees
WHERE department_id = 80;
12/8/21 12/8/21 101 Copyright © Argam, 2006. All rights reserved.
SQL

The ALTER TABLE statement


Use ALTER TABLE statement to add, modify or drop columns

ALTER TABLE dept80


ADD (job_id varchar2(9));

ALTER TABLE dept80


MODIFY (last_name varchar2(30));

ALTER TABLE dept80 ALTER TABLE dept80


DROP COLUMN job_id; SET UNUSED (last_name);

ALTER TABLE dept80 ALTER TABLE dept80


SET UNUSED COLUMN job_id; DROP UNUSED COLUMNS ;

12/8/21 12/8/21 102 Copyright © Argam, 2006. All rights reserved.


SQL
Dropping a Table
DROP TABLE dept80;

Changing the Name of an Object / Column


RENAME dept TO detail_dept;

ALTER TABLE emp RENAME COLUMN dept TO depart;

Truncating a table
TRUNCATE TABLE detail_dept;

 Removes all the rows from a Table


 Releases storage space used by that table HWM
12/8/21 12/8/21 103 Copyright © Argam, 2006. All rights reserved.
SQL

Adding Comments to a Table & Column


COMMENT ON TABLE employees
IS ‘Employee Information’;

Removing Comments from a Table


COMMENT ON TABLE employees
IS ‘ ’;

COMMENT ON COLUMN employees.last_name


IS ‘Last Name of the Employee’;

ALL_COL_COMMENTS USER_COL_COMMENTS
ALL_TAB_COMMENTS USER_TAB_COMMENTS

12/8/21 12/8/21 104 Copyright © Argam, 2006. All rights reserved.


SQL

Constraints
Constraints enforce rules at the Table level

NOT NULL value must exist


UNIQUE no duplicates
PRIMARY KEY NOT NULL & UNIQUE
FOREIGN KEY relationship between two

columns
CHECK condition must be true

12/8/21 12/8/21 105 Copyright © Argam, 2006. All rights reserved.


SQL

Defining Constraint
CREATE TABLE student1
(sno number(2) CONSTRAINT s_sno_pk PRIMARY KEY,
sname varchar2(15) NOT NULL,
dob date UNIQUE, SYS_Cnnnnnn
age number(2) CHECK (age < 25),
tno number(2),
CONSTRAINT st_te_fk FOREIGN KEY (tno)
REFERENCES teach(tno) ON DELETE CASCADE
);

ON DELETE CASCADE Deletes the dependent rows in the child


table when a row in parent table is deleted

ON DELETE SET NULL


Converts dependent foreign key values to null
12/8/21 12/8/21 106 Copyright © Argam, 2006. All rights reserved.
SQL

Constraints

ALTER TABLE teach


ADD CONSTRAINT emp_mgr_uk UNIQUE (tname);

ALTER TABLE teach


DROP CONSTRAINT emp_mgr_uk;

ALTER TABLE teach


DISABLE CONSTRAINT emp_mgr_uk;

ALTER TABLE teach user_constraints


ENABLE CONSTRAINT emp_mgr_uk; user_cons_columns

12/8/21 12/8/21 107 Copyright © Argam, 2006. All rights reserved.


SQL

Manipulating Data

12/8/21 12/8/21 108 Copyright © Argam, 2006. All rights reserved.


SQL

SQL Statements
SELECT Data retrieval
INSERT DML Data Manipulation Language
UPDATE
DELETE
MERGE
CREATE DDL Data Definition Language
ALTER
DROP
RENAME
TRUNCATE
COMMIT Transaction Control
ROLLBACK
SAVEPOINT
GRANT DCL Data Control Language
REVOKE
12/8/21 12/8/21 109 Copyright © Argam, 2006. All rights reserved.
SQL

Data Manipulation Language


A DML statement is executed when
 Add new rows to a table.
 Modify existing rows in a table.
 Remove existing rows from a table.

The INSERT statement


Add new rows to a table by using the INSERT statement

INSERT INTO table [(column [, column…])]


VALUES (value [, value…]);

 Only one row is inserted at a time with this syntax

12/8/21 12/8/21 110 Copyright © Argam, 2006. All rights reserved.


SQL

Inserting New Rows


INSERT INTO departments(department_id,
department_name, manager_id, location_id)

VALUES (9, ‘Database Admin’, 100, 1700);


INSERT INTO departments
VALUES (9, ‘Database Admin’,100,1700);

INSERT INTO departments(department_id,


location_id)
VALUES (9, 1700);

INSERT INTO departments(department_id,


department_name, manager_id, location_id)

VALUES (9, USER , null ,’’);

12/8/21 12/8/21 111 Copyright © Argam, 2006. All rights reserved.


SQL

Inserting New Rows


INSERT INTO employees
VALUES (18,’Reyarndo’,’DeCarl’,’RDECARL’, ‘515.17.61’,
TO_DATE(‘FEB 3, 2005’,’MON DD, YYYY’), ‘DBA’, 11000,
NULL, 100, 30);

Copying Rows from Another Table


INSERT INTO empp
SELECT * FROM employees WHERE deptno = 30;

Inserting using & && (Substitution variables)


INSERT INTO departments
VALUES (&c1, &c2 , &&c3);

12/8/21 12/8/21 112 Copyright © Argam, 2006. All rights reserved.


SQL

The UPDATE statement


Modify existing rows with the UPDATE statement

UPDATE table
SET column = value [, column = value,…]
[WHERE condition];

 Update more than one row at a time, if required

UPDATE employees
SET department_id = 70
WHERE employee_id = 113;

 Updates all rows, if WHERE clause is omitted

UPDATE empp
SET department_id = 70;

12/8/21 12/8/21 113 Copyright © Argam, 2006. All rights reserved.


SQL

The UPDATE statement

UPDATE employees
SET job_id = (SELECT job_id FROM employees
WHERE employee_id = 205),

salary = (SELECT sal FROM emp


WHERE eid = 200)

WHERE employee_id = 114;

12/8/21 12/8/21 114 Copyright © Argam, 2006. All rights reserved.


SQL

The DELETE statement


Remove existing rows with the DELETE statement
DELETE [FROM] table
[WHERE condition];

 Delete more than one row at a time, if required

DELETE FROM departments


WHERE department_name = ‘Finance’;

DELETE FROM empp;

DELETE employees
WHERE department_id = (SELECT department_id
FROM departments
WHERE
department_name
LIKE ‘%Public%’);
12/8/21 12/8/21 115 Copyright © Argam, 2006. All rights reserved.
SQL

The MERGE statement


Insert or Update rows in the COPY_EMP table to match the
EMPLOYEES table.

MERGE INTO copy_emp c


USING employees e
ON (c.employee_id = e.employee_id)
WHEN MATCHED THEN
UPDATE SET
c.first_name = e.first_name,
... ...
c.department_id = e.department_id
WHEN NOT MATCHED THEN
INSERT VALUES (e.employee_id, e.first_name, ...
e.department_id);

12/8/21 12/8/21 116 Copyright © Argam, 2006. All rights reserved.


SQL
Multi-table INSERT
 Unconditional INSERT ALL
 Select the EMPLOYEE_ID, HIRE_DATE, SALARY, and
MANAGER_ID values from the EMPLOYEES table for those
employees whose EMPLOYEE_ID is greater than 200.
 Insert these values into the SAL_HISTORY and
MGR_HISTORY tables using a multi-table INSERT
 All the table must be valid, otherwise rollback.
INSERT ALL
INTO sal_history VALUES(empid, hiredate, sal)
INTO mgr_history VALUES(empid, mgr, sal)
SELECT employee_id EMPID, hire_date HIREDATE,
salary SAL, manager_id MGR
FROM employees
WHERE employee_id > 200;

12/8/21 12/8/21 117 Copyright © Argam, 2006. All rights reserved.


SQL

Multi-table INSERT
 Conditional INSERT ALL
 Select the EMPLOYEE_ID, HIRE_DATE, SALARY, and MANAGER_ID
values from the EMPLOYEES table for those employees whose
EMPLOYEE_ID is greater than 200.
-- If the SALARY is greater than $10,000, insert these values into the
SAL_HISTORY table
-- If the MANAGER_ID is greater than 200, insert these values into the
MGR_HISTORY table.
INSERT ALL
WHEN sal > 10000 THEN
INTO sal_history VALUES(empid, hiredate, sal)
WHEN mgr > 200 THEN
INTO mgr_history VALUES(empid, mgr, sal)
SELECT employee_id EMPID, hire_date HIREDATE,
salary SAL, manager_id MGR
FROM employees
WHERE employee_id > 200;
12/8/21 12/8/21 118 Copyright © Argam, 2006. All rights reserved.
SQL
Multi-table INSERT
 Conditional FIRST INSERT
 Select the DEPARTMENT_ID, SUM(salary) and MAX(hire_date)
from the EMPLOYEES table
-- If the SUM(salary)is greater than $18,000, then insert these values into the
SPECIAL_SAL.
-- If the first WHEN clause evaluates to true, the subsequent WHEN clauses for
this rows should be skipped.
-- For the rows that do not satisfy the first WHEN condition, insert into the
HIREDATE_HISTORY_00, or HIREDATE_HISTORY_99 or HIREDATE_HISTORY tables,
based on the value in the HIRE_DATE column

INSERT FIRST
WHEN sal > 18000 THEN
INTO special_sal VALUES(deptid, sal)
WHEN hiredate like (‘%00%’) THEN
INTO hiredate_history_00 VALUES(deptid, hiredate)
WHEN hiredate like (‘%99%’) THEN
INTO hiredate_history_99 VALUES(deptid,hiredate)
ELSE INTO hiredate_history VALUES(deptid, hiredate)
SELECT department_id DEPTID, SUM(salary) SAL,
MAX(hire_date) HIREDATE FROM employees
GROUP BY department_id;

12/8/21 12/8/21 119 Copyright © Argam, 2006. All rights reserved.


SQL

Transaction
Transaction consists of the collection of DML statements that form a
logical unit of work

 DML statements which constitute one consistent change to the data.


 One DDL statement
 One DCL statement

 Begin when the first DML statement is executed


 End with one of the following events :
- A COMMIT or ROLLBACK statement is issued
- A DDL or DCL statement executed
- The user exits SQL*Plus / Worksheet

12/8/21 12/8/21 120 Copyright © Argam, 2006. All rights reserved.


SQL

Controlling Transactions

COMMIT
Transaction
DELETE
SAVEPOINT A
INSERT

UPDATE
SAVEPOINT B
INSERT
ROLLBACK TO ROLLBACK TO
SAVEPOINT B SAVEPOINT A
ROLLBACK
12/8/21 12/8/21 121 Copyright © Argam, 2006. All rights reserved.
SQL

Index
 Used by the Server to speed up the retrieval rows by using pointer
 Automatically - PRIMARY KEY or UNIQUE constraint
Manually - create non-unique index on column
CREATE INDEX emp_lname_idx
ON employees(last_name);

 A Function-based index is an index based on expressions

CREATE INDEX upper_emp_job_idx


ON employees( UPPER (job_id));

user_indexes
DROP INDEX emp_lname_idx;
user_ind_columns

12/8/21 12/8/21 122 Copyright © Argam, 2006. All rights reserved.


SQL

Sequence
 Generates unique numbers sequentially
 Used to create a primary key value
CREATE SEQUENCE d_did_seq
START WITH 120
INCREMENT BY 10
MAXVALUE 9999 | NOMAXVALUE
CYCLE | NOCYCLE
CACHE 10 | NOCACHE;
ORDER | NOORDER;

INSERT INTO departments


VALUES (d_did_seq.NEXTVAL , ‘Support’, 2500);

SELECT d_did_seq.CURRVAL FROM dual;

NEXTVAL returns the next available sequence


CURRVAL obtains the current sequence value
12/8/21 12/8/21 123 Copyright © Argam, 2006. All rights reserved.
SQL

Sequence
 ALTER SEQUENCE is used to modify

ALTER SEQUENCE d_did_seq


INCREMENT BY 10
MAXVALUE 8888
NOCYCLE;

START WITH cannot be modified always

DROP SEQUENCE d_did_seq;

user_sequences
12/8/21 12/8/21 124 Copyright © Argam, 2006. All rights reserved.
SQL

Synonyms
 Shorten lengthy objects names

CREATE SYNONYM d_sum


FOR department_sum_vu;

DROP SYNONYM d_sum;

12/8/21 12/8/21 125 Copyright © Argam, 2006. All rights reserved.


SQL

Summary
INSERT DML Data Manipulation Language
UPDATE
DELETE
MERGE
COMMIT Transaction Control
ROLLBACK
SAVEPOINT
Multi-table INSERT

Unconditional INSERT ALL


Conditional INSERT ALL
Conditional FIRST INSERT

INDEX – SEQUENCE - SYNONYM

12/8/21 12/8/21 126 Copyright © Argam, 2006. All rights reserved.


SQL

Controlling User Access

12/8/21 12/8/21 127 Copyright © Argam, 2006. All rights reserved.


SQL

Privileges
 Privileges are the right to execute particular SQL statements
 System Privileges : Gaining access to the database
– CREATE TABLE, CREATE USER ..
Object Privileges : Manipulating the content of the db objects
– SELECT, UPDATE, REFERENCES...

GRANT create user, create table, create view


TO hr;

CREATE USER reynardo


IDENTIFIED BY carl;

ALTER USER reynardo


IDENTIFIED BY rey;

12/8/21 12/8/21 128 Copyright © Argam, 2006. All rights reserved.


SQL

Role
 Role is a named group of related privileges that can be granted
to the user
 A User can have several roles, and several users can be
assigned the same role
 Create a Role
CREATE ROLE manager;

 Grant privileges to a Role


GRANT create table, create user
TO manager;
 Grant a role to users SET ROLE gardener IDENTIFIED BY

GRANT manager marigolds;


TO dehann, kochhar; SET ROLE ALL;
SET ROLE ALL EXCEPT dw_manager;
SET ROLE NONE; -- includes DEFAULT role
12/8/21 12/8/21 129 Copyright © Argam, 2006. All rights reserved.
SQL

Privileges
* Object privileges is access to on object i.e. table, view…
* An owner has all privileges on the object which has been created
* An owner can give specific privileges on his object to other user
Connect to SCOTT to retrieve from HR
GRANT select, update
ON employees SELECT *
TO scott; FROM hr.employees;

GRANT update (department_id, location_id)


ON employees
TO scott, rey ; references

GRANT select, update GRANT select


ON employees ON rey.student
TO scott TO PUBLIC;
WITH GRANT OPTION ;

12/8/21 12/8/21 130 Copyright © Argam, 2006. All rights reserved.


SQL

Revoke
 REVOKE statement used to revoke privileges granted to other users
 Privileges granted to others through WITH GRANT OPTION also revoked

REVOKE select, update


ON employees
FROM scott;

WITH GRANT OPTION REVOKE the PRIVILEGE


Grant on X object Grant on X object

X Y Z X Y Z

Z can access from X Y and Z cannot access from X

12/8/21 12/8/21 131 Copyright © Argam, 2006. All rights reserved.


SQL

Summary
 Privilege - rights to execute particular SQL statements
System – CREATE TABLE, CREATE USER ..
Object – SELECT, UPDATE ..

 Role is a named group of related privileges

 Grant
Revoke

12/8/21 12/8/21 132 Copyright © Argam, 2006. All rights reserved.


SQL

Views

12/8/21 12/8/21 133 Copyright © Argam, 2006. All rights reserved.


SQL

Creating View
 Logically represents subsets of data from one or more tables.
 Logical table based on a table or another view.
 A View contains no data of its own but is like a window
through which data from tables can be view or changed.
 View is stored as a SELECT statement in the data dictionary.

CREATE [OR REPLACE] [FORCE|NO FORCE] VIEW viewname

[(alias[, alias] ..)]


AS subquery
[WITH CHECK OPTION [constraint cname]]
[WITH READ ONLY [constraint cname]] ;

12/8/21 12/8/21 134 Copyright © Argam, 2006. All rights reserved.


SQL

Creating View
 Create a view EMPVU80, that contains details of the employees
in department 80
CREATE OR REPLACE VIEW empvu80
AS SELECT employee_id, last_name, salary
FROM employees WHERE department_id = 80;

CREATE OR REPLACE VIEW empvu50


AS SELECT employee_id EID, last_name NAME,
salary*12 ANN_SAL
FROM employees WHERE department_id = 50;

CREATE OR REPLACE VIEW empvu50 (EID,NAME,ANN_SAL)


AS SELECT employee_id, last_name, salary
FROM employees WHERE department_id = 50
WITH READ ONLY ;

12/8/21 12/8/21 135 Copyright © Argam, 2006. All rights reserved.


SQL

Complex View
 Create a Complex view that contains group functions to display
values from two tables

CREATE OR REPLACE VIEW dept_sum_vu


( name, minsal, maxsal, avgsal)
AS SELECT d.department_name, min(e.salary),
max(salary), avg(salary)
FROM employees e, departments d
WHERE e.department_id = d.department_id
GROUP BY d.department_name;

12/8/21 12/8/21 136 Copyright © Argam, 2006. All rights reserved.


SQL

WITH CHECK OPTION


 Any attempt to change the department number for a row
in the view fails, because it violates WITH CHECK OPTION
CREATE OR REPLACE VIEW empvu20
AS SELECT employee_id, last_name, salary,
department_id FROM employees
WHERE department_id = 20
WITH CHECK OPTION ;

WITH CHECK OPTION CONSTRAINT empvu20_ck;

DROP VIEW view_name;

12/8/21 12/8/21 137 Copyright © Argam, 2006. All rights reserved.


SQL

Inline View / TOP-N


 A named subquery in the FROM clause of the main query.
Who are the top TEN earners ?
Who are the least FIVE earners ?

SELECT ROWNUM as RANK, last_name, salary


FROM ( SELECT last_name, salary FROM employees
ORDER BY salary DESC )
WHERE ROWNUM < = 10 ;

WHERE must use < or <= operator

12/8/21 12/8/21 138 Copyright © Argam, 2006. All rights reserved.


SQL

Why use Views ?


 To restrict data access
 To make complex queries easy
 To present different view of the same data table.

Simple View vs Complex View


Feature Simple View Complex View
No of tables One One or More
Contains group functions No Yes
DML operations Yes Not always
through a view

12/8/21 12/8/21 139 Copyright © Argam, 2006. All rights reserved.


SQL

Summary

 Create View – Simple / Complex

 WITH CHECK OPTION

 INLINE / TOP-N

12/8/21 12/8/21 140 Copyright © Argam, 2006. All rights reserved.


SQL

12/8/21 12/8/21 141 Copyright © Argam, 2006. All rights reserved.

You might also like