SQL
Structured Query Language
1
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.
2
2
Agenda
SQL
Database Basics
Different types of commands(DDL,DML,TCL and DCL)
Functions and Aggregations
Joins and Set Operators
Object types – Constraints, Index, Views, M Views ,Synonyms, DB Links and Sequences
Oracle Architecture
PL SQL
Basics of PLSQL
Anonymous Blocks
Cursors
Procedures, Function, Package and Trigger
Ref Cursor, Nested Cursor, Parametric cursor, IOT, PLSQL Tables
TOAD Overview
3
Entity Relationship Model
Entity / Table : A thing of significance about which information needs to be known.
e.g. emp, dept, Students, and Orders.
Attribute / Column : Something that qualifies an entity. eg. eno, ename, ordno.,
Relationship : Association between entities showing cardinality / degree.
emp dept
number number
name name
job title location
Scenario:
- “ … assign one or more emp to a department…”
- “ … some dept do not yet have assigned emp…”
4
4
Architecture Oracle
Two Tier Three Tier
Client Client
Application Server
Server
Database Server
[Link]
C:\Oracle\ORA10_2\NETWORK\ADMIN
Oracle Product Non-Oracle Product
SQL, PL/SQL, Developer, Forms ... Java, XML, HTML,JSON ..
5
5
Communicating with a RDBMS using SQL
SQL Statement SELECT last_name
is entered FROM emp;
Statement is sent
LAST_NAME
to Oracle Server
King
Kochhar Oracle Server
Reynardo
DeCarl
Abel
Grant
6
SQL Statements
Data Retrieval
SELECT
Data Manipulation Language (DML)
DELETE INSERT MERGE
UPDATE
Data Definition Language (DDL)
CREATE ALTER DROP RENAME TRUNCATE
Transaction Control Language (TCL)
COMMIT ROLLBACK SAVEPOINT
Data Control Language (DCL)
GRANT REVOKE
Session Control Statements System Control Statements
ALTER SESSION ALTER SYSTEM
7
Creating and Managing Tables
8
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
9
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 dept
AS SELECT employee_id, last_name, hire_date,
deptno
FROM emp
WHERE deptno = 80;
10
The ALTER TABLE statement
Use ALTER TABLE statement to add, modify or drop columns
ALTER TABLE dept
ADD (job_id varchar2(9);
ALTER TABLE dept
MODIFY (last_name varchar2(30);
ALTER TABLE dept ALTER TABLE dept
DROP COLUMN job_id; SET UNUSED (last_name);
ALTER TABLE dept ALTER TABLE dept
SET UNUSED COLUMN job_id; DROP UNUSED COLUMNS ;
11
Dropping a Table
DROP TABLE dept;
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
Adding Comments to a Table & Column
COMMENT ON TABLE emp
IS ‘Employee Information’;
Removing Comments from a Table
COMMENT ON TABLE emp
IS ‘ ’;
COMMENT ON COLUMN emp.last_name
IS ‘Last Name of the Employee’;
ALL_COL_COMMENTS USER_COL_COMMENTS
ALL_TAB_COMMENTS USER_TAB_COMMENTS
13
Summary
CREATE TABLE
ALTER TABLE
DROP TABLE
RENAME
TRUNCATE
COMMENT
14
Oracle SQL Data Type
Datatype Description Max/Min Size:
VARCHAR2(size) Variable length character string having 4000 bytes. Minimum is 1.
max length size bytes. You must
specify size
CHAR(size) Fixed length character data of length 2000 [Link] and minimum
size bytes. This should be used for size is 1 byte.
fixed length data. Such as codes A100,
B102…
NUMBER(p,s) Number having precision p and scale s. The precision p can range from 1 to
38. The scale s can range from -84 to
127.
LONG Character data of variable length (A 2 Gigabytes
bigger version the VARCHAR2
datatype)
DATE Valid date range from January 1, 4712 BC to
December 31, 9999 AD.
TIMESTAMP the number of digits in the fractional Accepted values of
(fractional_seconds_precision) part of the SECOND datetime field. fractional_seconds_precision are 0
to 9. (default = 6)
CLOB Character Large object 4 Gigabytes
BLOB Binary Large Object 4 Gigabytes
BFILE pointer to binary file on disk 4 Gigabytes
11/08/2022 15
15
Constraints
16
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
17
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
18
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
19
Manipulating Data
20
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
21
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
22
Inserting New Rows
INSERT INTO dept(deptno,
department_name, manager_id, locid)
VALUES (9, ‘Database Admin’, 100, 1700);
INSERT INTO dept
VALUES (9, ‘Database Admin’,100,1700);
INSERT INTO dept(deptno,
locid)
VALUES (9, 1700);
INSERT INTO dept(deptno,
department_name, manager_id, locid)
VALUES (9, USER , null ,’’);
23
Inserting New Rows
INSERT INTO emp
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 emp WHERE job_id LIKE ‘%REP%’;
24
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 emp
SET deptno = 70
WHERE employee_id = 113;
Updates all rows, if WHERE clause is omitted
UPDATE empp
SET deptno = 70;
25
The UPDATE statement
UPDATE emp
SET job_id = (SELECT job_id FROM emp
WHERE employee_id = 205),
salary = (SELECT sal FROM emp
WHERE eid = 200)
WHERE employee_id = 114;
26
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 dept
WHERE department_name = ‘Finance’;
DELETE FROM empp;
DELETE emp
WHERE deptno = (SELECT deptno
FROM dept
WHERE department_name
LIKE ‘%Public%’);
27
The MERGE statement
Insert or Update rows in the COPY_EMP table to match the emp
table.
MERGE INTO copy_emp c
USING emp e
ON (c.employee_id = e.employee_id)
WHEN MATCHED THEN
UPDATE SET
c.first_name = e.first_name,
... ...
[Link] = [Link]
WHEN NOT MATCHED THEN
INSERT VALUES (e.employee_id, e.first_name, ...
[Link]);
28
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
29
Controlling Transactions
COMMIT
Transaction
DELETE
SAVEPOINT A
INSERT
UPDATE
SAVEPOINT B
INSERT
ROLLBACK TO ROLLBACK TO ROLLBACK
SAVEPOINT B SAVEPOINT A
30
Summary
INSERT DML Data Manipulation Language
UPDATE
DELETE
MERGE
COMMIT Transaction Control
ROLLBACK
SAVEPOINT
31
Writing Basic SQL
SELECT Statements
32
Basic SELECT Statement
SELECT *|{[DISTINCT] column_name|expression
[ alias],…}
FROM table_name;
SELECT identifies what column(s)
FROM identifies which table
Selecting All Columns
SELECT *
FROM dept;
33
Selecting Specific Columns
SELECT deptno, locid
FROM dept;
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.
34
Arithmetic Expressions
Create expressions with number and date data by using arithmetic
operators.
SELECT last_name, salary, salary+300
FROM emp;
Operator Precedence
SELECT last_name,salary,12*salary+300,12+salary*300
FROM emp;
Override the rule by using
Parentheses 12*(salary+300)
35
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
36
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 emp;
SELECT last_name AS “Name”, salary*12 “Annual Salary”
FROM emp;
37
Concatenation Operator
Concatenates columns or character strings to other columns.
Is represented by two vertical bars ||
SELECT last_name||job_id AS “emp”
FROM emp;
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 “emp”
FROM emp;
38
Duplicate Rows
The default display of queries is all rows, including duplicate rows
SELECT deptno
FROM emp;
Eliminate duplicate rows by using the DISTINCT or UNIQUE
keyword in the SELECT clause. You cannot specify
SELECT DISTINCT deptno DISTINCT if the
select_list contains
FROM emp;
LOB columns.
Display Table Structure
DESC[RIBE] tablename;
DESCRIBE emp; DESC emp;
39
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;
40
Restricting and Sorting Data
41
Limiting Rows using a Selection
The WHERE clause follows the FROM clause
SELECT *|{[DISTINCT] column|expression [ alias],…}
FROM table
[ WHERE condition(s) ];
“… retrieve all emp in department 90 .”
SELECT employee_id, last_name, deptno
FROM emp
WHERE deptno = 90;
42
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-YY / DD-MON-YYYY.
SELECT employee_id, last_name, deptno
FROM emp
WHERE last_name = ‘Adam’;
43
Comparison Conditions
Used in conditions that compare one expression to another
value or expression.
SELECT employee_id, last_name, deptno
FROM emp
WHERE last_name = ‘Adam’;
WHERE hire_date = ’01-Jan-95’ ;
WHERE salary >= 6000 ;
WHERE deptno <> 80 ; != ^=
44
BETWEEN Condition
Use the BETWEEN condition to display rows based on a
range of values.
SELECT employee_id, last_name, salary
FROM emp
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 emp
WHERE manager_id IN (100, 101, 201) ;
45
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 emp
WHERE last_name LIKE ‘S%’;
Use the ESCAPE identifier to search for the
actual % and _ symbols
SELECT employee_id, last_name, job_id
FROM emp
WHERE job_id LIKE ‘SA\_%’ ESCAPE ‘\’;
46
Using the NULL Conditions
Test for nulls with the IS NULL operator.
SELECT employee_id, last_name, manager_id
FROM emp
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
47
Using the AND Operator
AND requires both conditions to be true.
SELECT employee_id, last_name, job_id, salary
FROM emp
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 emp
WHERE salary >= 10000
OR job_id LIKE ‘%MAN%’;
48
Using the NOT Operator
SELECT employee_id, last_name, job_id
FROM emp
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
49
Rule of Precedence
SELECT last_name, job_id, salary
FROM emp
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 emp
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.
50
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 emp
ORDER BY hire_date;
ORDER BY salary DESC ;
51
Sorting by Column Alias
SELECT employee_id, last_name, salary*12 annsal
FROM emp
ORDER BY annsal ;
Sorting by Column position
SELECT employee_id, last_name, salary*12 annsal
FROM emp
ORDER BY 3 ;
Sorting by Multiple Columns
SELECT last_name, deptno, salary
FROM emp
ORDER BY deptno, salary DESC ;
You can sort by a column that is not in the SELECT list
52
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]];
53
Single-Row Functions
54
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,…)];
55
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, deptno
FROM emp
WHERE lower(last_name) = ‘abel’;
56
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
TRANSLATE
REPLACE
57
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
58
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;
59