Professional Documents
Culture Documents
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
Introduction
Database
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.
Scenario:
- “ … assign one or more employees to a
department…”
- “ … some departments do not yet have assigned
employees…”
10/16/08 10/16/08 8 Copyright © Argam, 2006. All rights reserved.
SQL
Data Models
Model of
system in
client’s
mind
Entity model
of client’s
model
Table model
Oracle
of entity
Server
model
Tables on
disk
10/16/08 10/16/08 11 Copyright © Argam, 2006. All rights reserved.
SQL
Architecture Oracle 8i
Database
Architecture Oracle 9i
Application Server
Server Architecture
Database Database
X A B C
10/16/08 10/16/08 15 Copyright © Argam, 2006. All rights reserved.
SQL
Kochhar Oracle
Server
Reynard
o
DeCarl
SQL Statements
Data Retrieval
SELECT
Summary
Joins
Table A Table B
SELECT *
FROM departments;
Arithmetic Expressions
Create expressions with number and date data by using arithmetic
operators.
Operator Precedence
SELECT last_name,salary,12*salary+300,12+salary*300
FROM employees;
Override the rule by using
Parentheses 12*(salary+300)
10/16/08 10/16/08 25
5 Abel 11000Copyright © Argam, .5
2006. All rights reserved.
SQL
Concatenation Operator
Concatenates columns or character strings to other columns.
Duplicate Rows
The default display of queries is all rows, including duplicate rows
SELECT department_id
FROM employees;
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
Comparison Conditions
Used in conditions that compare one expression to another
value or expression.
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 ;
IN Condition
Use the IN membership condition to test for values in a list.
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.
FROM employees
WHERE manager_id IS NULL;
Logical Conditions
Rules of Precedence
• Arithmetic operators
• Concatenation operators
• Comparison Conditions
• IS [NOT] NULL, LIKE, [NOT] IN
• [NOT] BETWEEN
• NOT logical condition
• AND logical condition
• OR logical condition
Override rules of precedence by using
parentheses
10/16/08 10/16/08 38 Copyright © Argam, 2006. All rights reserved.
SQL
Rule of Precedence
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
Summary
Use WHERE clause to restrict rows of output
Single-Row Functions
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
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
Character Functions
Case-manipulation functions
LOWER(‘Hello Bangalore’) hello bangalore
UPPER(‘Hello Bangalore’) HELLO BANGALORE
INITCAP(‘HeLlo BangAlore’) Hello Bangalore
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
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
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
FROM employees
WHERE department-id = 90;
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’
Conversion Function
Implicit Data Type Conversion
TO_NUMBER TO_DATE
TO_CHAR TO_CHAR
RM Roman Number
SELECT last_name,
to_char(hire_date,’fmDD Mon YYYY’) Hiredate
FROM employees;
SELECT last_name,
TO_CHAR(salary,’L9,999,999.99’) Sal
FROM employees;
1 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
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
10/16/08 10/16/08 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
RR Date Format
If the specified two-digit year is
0-49 50-
99
If two 0-49 the return date is The return
digits date is in the in the current century
of the century before the
current current one
year are
50-99 the return date is The return
date is in the
in the century after current
Current century
Year Specified dateRR Format YY Format
. 1995 the current one
27-Oct-95 1995 1995
. 1995 27-Oct-17 2017 1917
. 2001 27-Oct-17 2017 2017
. 2001 27-Oct-95 1995 2095
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
(Non-equi Join)
SELECT e.eno, e.ename, s.grade
FROM emp e, salgrade s
WHERE e.sal BETWEEN s.losal AND s.hisal;
Summary
CROSS JOIN
NATURAL JOIN
USING
ON
LEFT OUTER JOIN
RIGHT OUTER JOIN
FULL OUTER JOIN
Aggregating Data
Using Group Functions
SELECT COUNT(*)
FROM employees;
SELECT COUNT(commission_pct)
FROM employees
WHERE department_id = 80;
SELECT AVG(commission_pct)
FROM employees;
SELECT AVG(NVL(commission_pct,0))
FROM employees;
SELECT AVG(salary)
FROM employees
GROUP BY department_id;
10/16/08 10/16/08 79 Copyright © Argam, 2006. All rights reserved.
SQL
SELECT MAX(AVG(SALARY))
FROM employees
GROUP BY department_id;
Summary
Use the group functions
Write queries that use the GROUP BY clause
Write queries that use the HAVING clause
Sub-Queries
Sub-query
SELECT select_list
FROM table
WHERE expr operator ( SELECT select_list
FROM table );
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
Summary
Write subqueries when a query is based on
unknown values
SELECT select_list
FROM table
WHERE expr operator ( SELECT select_list
FROM table );
SQL*Plus Formating
Elements
Column Headings
COLUMN employee_name HEADING “Employee
Name”
Employee Name
-------------
COLUMN employee_name HEADING “Employee |
Name”
Employee SET
Name UNDERLINE @
--------
COLUMN employee_name HEADING “Employee |
Name” JUSTIFY RIGHT
COLUMN employee_name HEADING “Employee |
Name” JUSTIFY CENTER
Page SET Page SET
Width LINESIZE 60 Length PAGESIZE 50
SELECT department_name,department_id
FROM departments d;
Defining a Title
BTITLE
TTITLE LEFT “My Company”
CENTER “Current”
RIGHT “Page” FORMAT 999 SQL.PNO SKIP 1
CENTER “Employee Listing” SKIP 4
Table
Basic unit of storage ; composed of rows and
columns
CREATE TABLE [schema.]table
(column datatype [DEFAULT expr] [,..]);
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;
10/16/08 10/16/08 101 Copyright © Argam, 2006. All rights reserved.
SQL
Truncating a table
TRUNCATE TABLE detail_dept;
ALL_COL_COMMENTS USER_COL_COMMENTS
ALL_TAB_COMMENTS USER_TAB_COMMENTS
Constraints
Constraints enforce rules at the Table level
columns
CHECK condition must be true
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
);
Constraints
Manipulating Data
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
UPDATE table
SET column = value [, column = value,…]
[WHERE condition];
UPDATE employees
SET job_id = (SELECT job_id FROM employees
WHERE employee_id = 205),
DELETE employees
WHERE department_id = (SELECT department_id
FROM departments
WHERE
department_name
LIKE ‘%Public%’);
10/16/08 10/16/08 115 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
INSERT
-- If theALL
MANAGER_ID is greater than 200, insert these
WHEN
values sal
into the> 10000 THEN
INTO sal_history
MGR_HISTORY table. 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;
10/16/08 10/16/08 118 Copyright © Argam, 2006. All rights reserved.
SQL
Multi-table INSERT
Conditional FIRST INSERT
Select the DEPARTMENT_ID, SUM(salary) and MAX(hire_date)
Transaction
Transaction consists of the collection of DML
statements that form a logical unit of work
Controlling Transactions
COMMIT
Transaction
DELETE
SAVEPOINT A
INSERT
UPDATE
SAVEPOINT B
INSERT
ROLLBACK TO ROLLBACK TO
SAVEPOINT B SAVEPOINT A
ROLLBACK
10/16/08 10/16/08 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);
user_indexes
DROP INDEX emp_lname_idx;
user_ind_columns
Sequence
Generates unique numbers sequentially
Used to create a primary key value
Sequence
ALTER SEQUENCE is used to modify
user_sequences
10/16/08 10/16/08 124 Copyright © Argam, 2006. All rights reserved.
SQL
Synonyms
Shorten lengthy objects names
Summary
INSERT DML Data Manipulation Language
UPDATE
DELETE
MERGE
COMMIT Transaction Control
ROLLBACK
SAVEPOINT
Multi-table INSERT
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
GRANT
the create user, create table, create view
db objects
TO hr;
– SELECT, UPDATE, REFERENCES...
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 a Role
Create
assigned the same role
CREATE ROLE manager;
Grant privileges to
aGRANT
Role create table, create user
TO manager;
Grant a role to users SET ROLE gardener IDENTIFIED BY
Privileges
* Object privileges is access to on object i.e. table,
view…
* An owner has all privileges on the object which
has been created
Connect to SCOTT to retrieve from H
* An owner can give specific privileges on his
GRANT select, update
ON
object employees
to other user SELECT *
TO scott; FROM hr.employees;
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;
X Y Z X Y Z
Summary
Privilege - rights to execute particular SQL
statements System – CREATE TABLE, CREATE
USER ..
Object – SELECT, UPDATE ..
Grant
Revoke
Views
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.
CREATE [OR REPLACE] [FORCE|NO FORCE] VIEW viewname
View is stored as a SELECT statement in the data
dictionary.
[(alias[, alias] ..)]
AS subquery
[WITH CHECK OPTION [constraint cname]]
[WITH READ ONLY [constraint cname]] ;
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;
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;
Summary
INLINE / TOP-N