0% found this document useful (0 votes)
39 views236 pages

SQL Basics: SELECT Statements Guide

The document provides an overview of SQL statements, focusing on the SELECT statement, its clauses, and various operators. It explains how to write SQL queries, use arithmetic expressions, define null values, and apply comparison and logical operators. Additionally, it covers the use of the WHERE and ORDER BY clauses to filter and sort data, as well as the types of SQL functions available.

Uploaded by

Ram
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views236 pages

SQL Basics: SELECT Statements Guide

The document provides an overview of SQL statements, focusing on the SELECT statement, its clauses, and various operators. It explains how to write SQL queries, use arithmetic expressions, define null values, and apply comparison and logical operators. Additionally, it covers the use of the WHERE and ORDER BY clauses to filter and sort data, as well as the types of SQL functions available.

Uploaded by

Ram
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

SQL Statements

1
Objectives

• SQL SELECT statements

• A basic SELECT statement

• SQL statements and SQL*Plus commands

2
Basic SELECT Statement

SELECT [DISTINCT] {*, column [alias],...}


FROM table;

• Select Clause determines what columns

• The From Clause determines which table.

3
Writing SQL Statements

• SQL is not Case Sensitive.


• Tabs and Indentations will promote
readability.
• Keywords cannot be split or abbreviated.
• SQL Statements can be split across
lines.
• Clauses are placed in different lines, to
promote readability.

4
Selecting All Columns

SQL> SELECT *
2 FROM departments;

DEPTNO DNAME LOC


--------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

5
Selecting Specific Columns

SQL> SELECT deptno, loc


2 FROM departments;

DEPTNO LOC
--------- -------------
10 NEW YORK
20 DALLAS
30 CHICAGO
40 BOSTON

6
Default Column Headings
• Default justification
• Date and Character Data is Left Justified
• Numeric Data is Right Justified
• Display Headings in UPPER CASE.
• Character / Date Columns headings will be
Truncated.
• Numerical Columns headings are not truncated.
• Alias name can be replaced by the column name.

7
Arithmetic Expressions
•Basic Arithmetic operators

Operator Description
+ Add
- Subtract
* Multiply
/ Divide

8
Using Arithmetic Operators

SQL> SELECT ename, sal, sal+300


2 FROM employees;

ENAME SAL SAL+300


---------- --------- ---------
KING 5000 5300
BLAKE 2850 3150
CLARK 2450 2750
JONES 2975 3275
MARTIN 1250 1550
ALLEN 1600 1900
...
14 rows selected.

9
Operator Precedence
_
* / +
• Parentheses can force precedence

• Multiplication and Division followed by


Addition and subtraction.

10
Operator Precedence
SQL> SELECT ename, sal, 12*sal+100
2 FROM employees;

ENAME SAL 12*SAL+100


---------- --------- ----------
KING 5000 60100
BLAKE 2850 34300
CLARK 2450 29500
JONES 2975 35800
MARTIN 1250 15100
ALLEN 1600 19300
...
14 rows selected.

11
Using Parentheses
SQL> SELECT ename, sal, 12*(sal+100)
2 FROM employees;

ENAME SAL 12*(SAL+100)


---------- --------- -----------
KING 5000 61200
BLAKE 2850 35400
CLARK 2450 30600
JONES 2975 36900
MARTIN 1250 16200
...
14 rows selected.

12
Defining a Null Value
• NULL is UNASSIGNED Value.

SQL> SELECT ename, job, comm


2 FROM emp;

ENAME JOB COMM


---------- --------- ---------
KING PRESIDENT
BLAKE MANAGER
...
TURNER SALESMAN 0
...
14 rows selected.

13
Null Values in Arithmetic Expr

• NULL as an operand will result NULL

SQL> select ename NAME, 12*sal+comm


2 from emp
3 WHERE ename='KING';

NAME 12*SAL+COMM
---------- -----------
KING

14
Defining Column Alias

• The Heading name is replaced for the current


SELECT Statement.

• AS Keyword [ Optional ] between the column


name and the actual alias name

• Double Quotation Marks.

15
Using Column Aliases
SQL> SELECT ename AS name, sal salary
2 FROM employees;

NAME SALARY
------------- ---------
...

SQL> SELECT ename "Name",


2 sal*12 "Annual Salary"
3 FROM employees;

Name Annual Salary


------------- -------------
...
16
Concatenation Operator (||)

• Concatenates the Columns of any data


type.

• A Resultant column will be a Single


column.

17
Using Concatenation Operator

SQL> SELECT ename||job AS "Employees"


2 FROM employees;

Employees
-------------------
KINGPRESIDENT
BLAKEMANAGER
CLARKMANAGER
JONESMANAGER
MARTINSALESMAN
ALLENSALESMAN
...
14 rows selected.

18
Literal Character Strings

• Date and character literal values must be


enclosed within single quotation marks.

19
Using ‘DISTINCT’ Clause
• Eliminate duplicate rows by using the
DISTINCT keyword

SQL> SELECT DISTINCT deptno


2 FROM employees;

DEPTNO
---------
10
20
30

20
SQL Vs SQL*Plus
SQL SQL*Plus

• A language • An environment
• ANSI standard • Oracle proprietary
• Keyword cannot be • Keywords can be
abbreviated abbreviated
• Statements manipulate • Commands do not
data and table allow manipulation of
definitions in the values in the database
database • SQL*PLUS statements
• SQL statements are are not stored in Buffer
stored in buffer

21
Summary

SELECT [DISTINCT] {*,column[alias],...}


FROM table;

•Use SQL*Plus as an environment to:


– Execute SQL statements
– Edit SQL statements

22
Using 'Where' and 'Order By'
Clauses

23
Objectives

• Limit the rows required

• Arrange the rows in a particular order.

24
Using ‘WHERE’ Clause
• Specify the Selection of rows retrieved by
the WHERE Clause.
SELECT [DISTINCT] {*, column [alias], ...}
FROM table
[WHERE condition(s)];

• The WHERE clause follows the FROM


clause.

25
Using WHERE Clause

SQL> SELECT ename, job, deptno


2 FROM employees
3 WHERE job='CLERK';

ENAME JOB DEPTNO


---------- --------- ---------
JAMES CLERK 30
SMITH CLERK 20
ADAMS CLERK 20
MILLER CLERK 10

26
Character Strings and Dates
• Character / Dates are Represented by the
Single Quotation Marks.

• Default date format is 'DD-MON-YY'

SQL> SELECT ename, job, deptno


2 FROM emp
3 WHERE ename = 'JAMES';

27
Comparison Operators

Operator Meaning
= Equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
<> Not equal to

28
Using Comparison Operators

SQL> SELECT ename, sal, comm


2 FROM employees
3 WHERE sal<=comm;

ENAME SAL COMM


---------- --------- ---------
MARTIN 1250 1400

29
More Comparison Operators

Operator Meaning
BETWEEN Between two values (inclusive)
...AND...
IN(list) Match any of a list of values
LIKE Match a character pattern
IS NULL Is a null value

30
Using BETWEEN Operator
SQL> SELECT ename, sal
2 FROM employees
3 WHERE sal BETWEEN 1000 AND 1500;

ENAME SAL
---------- --------- Lower Higher
MARTIN 1250 limit limit
TURNER 1500
WARD 1250
ADAMS 1100
MILLER 1300

•Used to compare between range of


values. Values Specified are inclusive.
31
Using IN Operator
•IN Operator to check with a List of
Values.
SQL> SELECT empno, ename, sal, mgr
2 FROM emp
3 WHERE mgr IN (7902, 7566, 7788);

EMPNO ENAME SAL MGR


--------- ---------- --------- ---------
7902 FORD 3000 7566
7369 SMITH 800 7902
7788 SCOTT 3000 7566
7876 ADAMS 1100 7788

32
Using LIKE Operator

• Like Keyword Does Wildcard Searches in


Valid String Values..

% ---------- zero or many characters


_ ----------- one character

SQL> SELECT ename


2 FROM emp
3 WHERE ename LIKE 'S%';

33
Using LIKE Operator
• ESCAPE identifier to search for "%" or "_".

SQL> SELECT ename


2 FROM emp
3 WHERE ename LIKE ‘_A%‘;

ENAME
----------
JAMES
WARD

34
Using IS NULL Operator

•To Check for Null Values , IS NULL is


used.
SQL> SELECT ename, mgr
2 FROM emp
3 WHERE mgr IS NULL;

ENAME MGR
---------- ---------
KING

35
Logical Operators

Operator Meaning

AND Returns TRUE if both component


conditions are TRUE
OR Returns TRUE if either component
condition is TRUE

NOT Returns TRUE if the following


condition is FALSE

36
Using AND Operator
• AND requires both conditions to be TRUE.

SQL> SELECT empno, ename, job, sal


2 FROM emp
3 WHERE sal>=1100
4 AND job='CLERK';

EMPNO ENAME JOB SAL


--------- ---------- --------- ---------
7876 ADAMS CLERK 1100
7934 MILLER CLERK 1300

37
Using OR Operator
• OR requires either condition to be TRUE.
SQL> SELECT empno, ename, job, sal
2 FROM emp
3 WHERE sal>=1100
4 OR job='CLERK';

EMPNO ENAME JOB SAL


--------- ---------- --------- ---------

7839 KING PRESIDENT 5000


7698 BLAKE MANAGER 2850
7782 CLARK MANAGER 2450
7566 JONES MANAGER 2975
7654 MARTIN SALESMAN 1250
...
14 rows selected.
38
Using NOT Operator
SQL> SELECT ename, job
2 FROM emp
3 WHERE job NOT IN ('CLERK','MANAGER','ANALYST');

ENAME JOB
---------- ---------
KING PRESIDENT
MARTIN SALESMAN
ALLEN SALESMAN
TURNER SALESMAN
WARD SALESMAN

39
Rules of Precedence

Order Evaluated Operator


1 All comparison
operators
2 NOT
3 AND
4 OR

40
‘ORDER BY’ Clause
• Sort rows specified by the order: ASC/DESC

SQL> SELECT ename, job, deptno, hiredate


2 FROM emp
3 ORDER BY hiredate;

ENAME JOB DEPTNO HIREDATE


---------- --------- --------- ---------
SMITH CLERK 20 17-DEC-80
ALLEN SALESMAN 30 20-FEB-81
...
14 rows selected.

41
Sorting in Descending Order
SQL> SELECT ename, job, deptno, hiredate
2 FROM emp
3 ORDER BY hiredate DESC;

ENAME JOB DEPTNO HIREDATE


---------- --------- --------- ---------
ADAMS CLERK 20 12-JAN-83
SCOTT ANALYST 20 09-DEC-82
MILLER CLERK 10 23-JAN-82
JAMES CLERK 30 03-DEC-81
FORD ANALYST 20 03-DEC-81
KING PRESIDENT 10 17-NOV-81
MARTIN SALESMAN 30 28-SEP-81
...
14 rows selected.

42
Sorting by Multiple Columns
• The order of ORDER BY list is the order of
sort.
SQL> SELECT ename, deptno, sal
2 FROM emp
3 ORDER BY deptno, sal DESC;

ENAME DEPTNO SAL


---------- --------- ---------
KING 10 5000
CLARK 10 2450
MILLER 10 1300
FORD 20 3000
...
14 rows selected.

43
Summary

SELECT [DISTINCT] {*, column [alias], ...}


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

44
SQL Functions

45
Objectives

• Get an awareness of the Various SQL


Functions available.
• Types of Functions in the SELECT
Statement.
• Conversion functions

46
Types of SQL Functions

Functions

Multiple-row Single-row
functions functions

47
Single-Row Functions

• Act on every row as a result of every row.


• Invoke Nested Levels.

function_name (column|expression, [arg1, arg2,...])

48
Single-Row Functions

Character

General Number
Single-row
functions

Conversion Date

49
Character Functions
Character
functions

Character manipulation Case conversion


functions functions

CONCAT LOWER
SUBSTR UPPER
LENGTH INITCAP
INSTR
LPAD
50
Case Conversion Functions

•Convert case for character strings


Function Result
LOWER('SQL Course') sql course
UPPER('SQL Course') SQL COURSE
INITCAP('SQLCourse') Sql Course

51
Case Conversion Functions
•Display the employee number, name,
and department number for employee
Blake.
SQL> SELECT empno, ename, deptno
2 FROM emp
3 WHERE ename = 'blake';
no rows selected

SQL> SELECT empno, ename, deptno


2 FROM emp
3 WHERE LOWER(ename) = 'blake';

EMPNO ENAME DEPTNO


--------- ---------- ---------
7698 BLAKE 30

52
Character Functions

Function Result
CONCAT('Good', 'String') GoodString
SUBSTR('String',1,3) Str
LENGTH('String') 6
INSTR('String', 'r') 3
LPAD(sal,10,'*') ******5000

53
Using Character Functions

SQL> SELECT ename, CONCAT (ename, job), LENGTH(ename),


2 INSTR(ename, 'A')
3 FROM emp
4 WHERE SUBSTR(job,1,5) = 'SALES';

ENAME CONCAT(ENAME,JOB) LENGTH(ENAME) INSTR(ENAME,'A')


---------- ------------------- ------------- ----------------
MARTIN MARTINSALESMAN 6 2
ALLEN ALLENSALESMAN 5 1
TURNER TURNERSALESMAN 6 0
WARD WARDSALESMAN 4 2

54
Number Functions
– ROUND: Rounds value to specified
decimal
• ROUND(45.926, 2)
45.93
– TRUNC: Truncates value to
specified
decimal
• TRUNC(45.926, 2)
45.92

– MOD: Returns
remainder of division 55
Working with Dates
• Stores date with Century.
• Default date format is DD-MON-YY.
• SYSDATE is a Function which returns the
System date and time.
• DUAL is a dummy table used to view
SYSDATE.

56
Arithmetic with Dates

• Add/Subtract a Number to the Date.

• Add/Subtract hours to a date by dividing


the number of hours by 24.

57
Arithmetic with Dates

SQL> SELECT ename, (SYSDATE-hiredate)/7 WEEKS


2 FROM emp
3 WHERE deptno = 10;

ENAME WEEKS
---------- ---------
KING 830.93709
CLARK 853.93709
MILLER 821.36566

58
Working with Date Functions
FUNCTION DESCRIPTION

Number of months
MONTHS_BETWEEN between two dates
Add calendar months to
ADD_MONTHS date
Next day of the date
NEXT_DAY specified

LAST_DAY Last day of the month

ROUND Round date

TRUNC Truncate date

59
Using Date Functions

• ROUND('25-JUL-95','MONTH') 01-AUG-95

• ROUND('25-JUL-95','YEAR') 01-JAN-96
• TRUNC('25-JUL-95','MONTH') 01-JUL-95
• TRUNC('25-JUL-95','YEAR') 01-JAN-
95

60
Conversion Functions

Conversion
Functions

Explicit data type Implicit data type


conversion conversion

61
Implicit Data type Conversion
•For assignments, Oracle can
automatically convert
From To
VARCHAR2 or CHAR NUMBER

VARCHAR2 or CHAR DATE

NUMBER VARCHAR2

DATE VARCHAR2

62
‘TO_CHAR’ with Dates
TO_CHAR(date, 'fmt')

•The format model:


• Enclosed in Single Quote Marks.
• Include any Valid date format.

63
Date Format

YYYY Full year in numbers

YEAR Year spelled out

MM 2-digit value for month

MONTH Full name of the month


3-letter abbreviation of the day
DY
of the week
DAY Full name of the day

64
Date Format Elements
• Time elements format the time portion of
the date.
HH24:MI:SS AM [Link] PM
• Add character strings by enclosing them in
double quotation marks.
DD "of" MONTH 12 of OCTOBER
• Number suffixes spell out numbers.
ddspth fourteenth

65
‘TO_CHAR’ with Numbers
TO_CHAR(number, 'fmt')

•To display a number value as a character.

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
66
TO_NUMBER & TO_DATE

• A character string to a number format using


the TO_NUMBER function

TO_NUMBER(char)

• A character string to a date format using


the TO_DATE function

TO_DATE(char[, 'fmt'])

67
‘RR’ Date Format
• Windowing Technique using the ‘RR’ Date Format
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

If the specified two-digit year is

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

SQL> SELECT ename, sal, comm, (sal*12)+NVL(comm,0)


2 FROM emp;

ENAME SAL COMM (SAL*12)+NVL(COMM,0)


---------- --------- --------- --------------------
KING 5000 60000
BLAKE 2850 34200
CLARK 2450 29400
JONES 2975 35700
MARTIN 1250 1400 16400
ALLEN 1600 300 19500
...
14 rows selected.

69
Nesting Functions
• Single-row functions can be nested to any
number of levels.
• ‘Function of Function’ rule

F3(F2(F1(col,arg1),arg2),arg3)

Step 1 = Result 1
Step 2 = Result 2
Step 3 = Result 3

70
Summary

• Perform calculations on data


• Modify individual data items
• Alter date formats for display
• Convert column data types

71
Using ‘Joins’

72
Objectives

• Cartesian Join
• To access data from more than one Table
using Equality and Non-Equality Condition
• Outer and Inner Join
• Join a table to itself

73
Data from Multiple Tables
EMP DEPT
EMPNO ENAME ... DEPTNO DEPTNO DNAME LOC
------ ----- ... ------ ------ ---------- --------
7839 KING ... 10 10 ACCOUNTING NEW YORK
7698 BLAKE ... 30 20 RESEARCH DALLAS
... 30 SALES CHICAGO
7934 MILLER ... 10 40 OPERATIONS BOSTON

EMPNO DEPTNO LOC


----- ------- --------
7839 10 NEW YORK
7698 30 CHICAGO
7782 10 NEW YORK
7566 20 DALLAS
7654 30 CHICAGO
7499 30 CHICAGO
...
14 rows selected.
74
What Is a Join?
•A JOIN Basically involves more than
one Table to interact with.
SELECT [Link], [Link]
FROM table1, table2
WHERE table1.column1 = table2.column2;

• Where clause specifies the JOIN


Condition.
• Ambiguous Column names are identified
by the Table name.

75
Cartesian Product

• A Cartesian product is formed when:


• A Join Condition is completely omitted
• All rows in the first table are joined to all
rows in the second table

76
Cartesian Product
EMP (14 rows) DEPT (4 rows)
EMPNO ENAME ... DEPTNO DEPTNO DNAME LOC
------ ----- ... ------ ------ ---------- --------
7839 KING ... 10 10 ACCOUNTING NEW YORK
7698 BLAKE ... 30 20 RESEARCH DALLAS
... 30 SALES CHICAGO
7934 MILLER ... 10 40 OPERATIONS BOSTON

ENAME DNAME
------ ----------
KING ACCOUNTING
“Cartesian BLAKE ACCOUNTING
product: ...
KING RESEARCH
14*4=56 rows” BLAKE RESEARCH
...
56 rows selected.
77
Types of Joins

• Inner Join
• Equi Join
• Non Equi Join
• Self Join
• Outer join

78
What Is an Equijoin?
EMP DEPT
EMPNO ENAME DEPTNO DEPTNO DNAME LOC
------ ------- ------- ------- ---------- --------
7839 KING 10 10 ACCOUNTING NEW YORK
7698 BLAKE 30 30 SALES CHICAGO
7782 CLARK 10 10 ACCOUNTING NEW YORK
7566 JONES 20 20 RESEARCH DALLAS
7654 MARTIN 30 30 SALES CHICAGO
7499 ALLEN 30 30 SALES CHICAGO
7844 TURNER 30 30 SALES CHICAGO
7900 JAMES 30 30 SALES CHICAGO
7521 WARD 30 30 SALES CHICAGO
7902 FORD 20 20 RESEARCH DALLAS
7369 SMITH 20 20 RESEARCH DALLAS
... ...
14 rows selected. 14 rows selected.

79
Retrieving Rows: Equijoin

SQL> SELECT [Link], [Link], [Link],


2 [Link], [Link]
3 FROM emp, dept
4 WHERE [Link]=[Link];

EMPNO ENAME DEPTNO DEPTNO LOC


----- ------ ------ ------ ---------
7839 KING 10 10 NEW YORK
7698 BLAKE 30 30 CHICAGO
7782 CLARK 10 10 NEW YORK
7566 JONES 20 20 DALLAS
...
14 rows selected.

80
Using Table Aliases
•Simplify queries by using table aliases.
SQL> SELECT [Link], [Link], [Link],
2 [Link], [Link]
3 FROM emp, dept
4 WHERE [Link]=[Link];

SQL> SELECT [Link], [Link], [Link],


2 [Link], [Link]
3 FROM emp e, dept d
4 WHERE [Link]=[Link];

81
Joining More Than Two Tables
CUSTOMER ORD
NAME CUSTID CUSTID ORDID
----------- ------ ------- -------
JOCKSPORTS 100 101 610
TKB SPORT SHOP 101 102 611
VOLLYRITE 102 104 612
JUST TENNIS 103 106 601
K+T SPORTS 105 102 602
SHAPE UP 106 106 604
WOMENS SPORTS 107 106 605 ITEM
... ... ... ORDID ITEMID
9 rows selected. 21 rows selected.
------ -------
610 3
611 1
612 1
601 1
602 1
...
64 rows selected. 82
Non-Equijoins
EMP SALGRADE
EMPNO ENAME SAL GRADE LOSAL HISAL
------ ------- ------ ----- ----- ------
7839 KING 5000 1 700 1200
7698 BLAKE 2850 2 1201 1400
7782 CLARK 2450 3 1401 2000
7566 JONES 2975 4 2001 3000
7654 MARTIN 1250 5 3001 9999
7499 ALLEN 1600
7844 TURNER 1500
7900 JAMES 950
... “salary in the EMP
14 rows selected. table is between
low salary and high
salary in the SALGRADE
table”

83
Retrieving Rows:Non-Equijoin

SQL> SELECT [Link], [Link], [Link]


2 FROM emp e, salgrade s
3 WHERE [Link]
4 BETWEEN [Link] AND [Link];

ENAME SAL GRADE


---------- --------- ---------
JAMES 950 1
SMITH 800 1
ADAMS 1100 1
...
14 rows selected.

84
Outer Joins
EMP DEPT
ENAME DEPTNO DEPTNO DNAME
----- ------ ------ ----------
KING 10 10 ACCOUNTING
BLAKE 30 30 SALES
CLARK 10 10 ACCOUNTING
JONES 20 20 RESEARCH
... ...
40 OPERATIONS

No employee in the
OPERATIONS department

85
Outer Joins
• To see also the rows that do not usually
meet the join condition.
• Outer join operator is the plus sign (+).

SELECT [Link], [Link]


FROM table1, table2
WHERE [Link](+) = [Link];

SELECT [Link], [Link]


FROM table1, table2
WHERE [Link] = [Link](+);

86
Using Outer Joins
SQL> SELECT [Link], [Link], [Link]
2 FROM emp e, dept d
3 WHERE [Link](+) = [Link]
4 ORDER BY [Link];

ENAME DEPTNO DNAME


---------- --------- -------------
KING 10 ACCOUNTING
CLARK 10 ACCOUNTING
...
40 OPERATIONS
15 rows selected.

87
Self Joins
EMP (WORKER) EMP (MANAGER)
EMPNO ENAME MGR EMPNO ENAME
----- ------ ---- ----- --------
7839 KING
7698 BLAKE 7839 7839 KING
7782 CLARK 7839 7839 KING
7566 JONES 7839 7839 KING
7654 MARTIN 7698 7698 BLAKE
7499 ALLEN 7698 7698 BLAKE

"MGR in the WORKER table is equal to EMPNO in the


MANAGER table"

88
Joining a Table to Itself
SQL> SELECT [Link]||' works for '||[Link]
2 FROM emp worker, emp manager
3 WHERE [Link] = [Link];

[Link]||'WORKSFOR'||MANAG
-------------------------------
BLAKE works for KING
CLARK works for KING
JONES works for KING
MARTIN works for BLAKE
...
13 rows selected.

89
Summary
SELECT [Link], [Link]
FROM table1, table2
WHERE table1.column1 = table2.column2;

Types of Joins
• Equijoins
• Non- Equijoins
• Outer Joins
• Self Joins

90
Using Group Functions

91
Objectives

• Group Functions
• GROUP BY clause
• HAVING Clause.

92
What Are Group Functions?
•Operate on sets of rows to give one result per group.
EMP
DEPTNO SAL
--------- ---------
10 2450
10 5000
10 1300
20 800
20 1100
20 3000 “maximum MAX(SAL)
20 3000 salary in ---------
20 2975 the EMP table” 5000
30 1600
30 2850
30 1250
30 950
30 1500
30 1250
93
Common Group Functions

– AVG
– COUNT
– MAX
– MIN
– STDDEV
– SUM
– VARIANCE

94
Using Group Functions

SELECT column, group_function(column)


FROM table
[WHERE condition]
[ORDER BY column];

95
Using the COUNT Function

SQL> SELECT COUNT(*)


2 FROM emp
3 WHERE deptno = 30;

COUNT(*)
---------
6

96
Using the COUNT Function
•COUNT(expr) returns the number of
nonnull values in the given column.
SQL> SELECT COUNT(comm)
2 FROM emp
3 WHERE deptno = 30;

COUNT(COMM)
-----------
4

97
Group Functions & Null Values
•Group functions ignore null values in
the column.
SQL> SELECT AVG(comm)
2 FROM emp;

AVG(COMM)
---------
550

98
NVL with Group Functions

•The NVL function forces group functions


to include null values.
SQL> SELECT AVG(NVL(comm,0))
2 FROM emp;

AVG(NVL(COMM,0))
----------------
157.14286

99
Creating Groups of Data
EMP
DEPTNO SAL
--------- ---------
10 2450
10 5000 2916.6667
10 1300
20 800 “average DEPTNO AVG(SAL)
20 1100 salary
------- ---------
20 3000 2175 in EMP
20 3000 table 10 2916.6667
20 2975 for each 20 2175
30 1600 department” 30 1566.6667
30 2850
30 1250 1566.6667
30 950
30 1500
30 1250

100
Using ‘GROUP BY’ Clause

SELECT column, group_function(column)


FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[ORDER BY column];

•Modularize rows in a table into smaller


groups by using the GROUP BY clause.

101
Using GROUP BY Clause
•Columns that are not a part of the
Group Functions should be included in
the Group by clause.
SQL> SELECT deptno, AVG(sal)
2 FROM emp
3 GROUP BY deptno;

DEPTNO AVG(SAL)
--------- ---------
10 2916.6667
20 2175
30 1566.6667

102
Grouping by Multiple Columns
EMP
DEPTNO JOB SAL
--------- --------- ---------
10 MANAGER 2450
DEPTNO JOB SUM(SAL)
10 PRESIDENT 5000
-------- --------- ---------
10 CLERK 1300
10 CLERK 1300
20 CLERK 800 “sum salaries in 10 MANAGER 2450
20 CLERK 1100 the EMP table
10 PRESIDENT 5000
20 ANALYST 3000 for each job,
20 ANALYST 6000
20 ANALYST 3000 grouped by
20 CLERK 1900
20 MANAGER 2975 department”
20 MANAGER 2975
30 SALESMAN 1600
30 CLERK 950
30 MANAGER 2850
30 MANAGER 2850
30 SALESMAN 1250
30 SALESMAN 5600
30 CLERK 950
30 SALESMAN 1500
30 SALESMAN 1250

103
GROUP BY: Multiple Columns

SQL> SELECT deptno, job, sum(sal)


2 FROM emp
3 GROUP BY deptno, job;

DEPTNO JOB SUM(SAL)


--------- --------- ---------
10 CLERK 1300
10 MANAGER 2450
10 PRESIDENT 5000
20 ANALYST 6000
20 CLERK 1900
...
9 rows selected.

104
Segregating Group Results
EMP
DEPTNO SAL
--------- ---------
10 2450
10 5000 5000
10 1300
20 800
20 1100 “maximum DEPTNO MAX(SAL)
20 3000 salary --------- ---------
3000 per department
20 3000 10 5000
20 2975 greater than 20 3000
30 1600 $2900”
30 2850
30 1250
30 950
2850
30 1500
30 1250

105
Using the ‘HAVING’ Clause

•HAVING clause is to restrict groups


Groups satisfying the HAVING condition
are displayed.

SELECT column, group_function


FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[HAVING group_condition]
[ORDER BY column];
106
Using HAVING Clause

SQL> SELECT deptno, max(sal)


2 FROM emp
3 GROUP BY deptno
4 HAVING max(sal)>2900;

DEPTNO MAX(SAL)
--------- ---------
10 5000
20 3000

107
Using HAVING Clause

SQL> SELECT job, SUM(sal) PAYROLL


2 FROM emp
3 WHERE job NOT LIKE 'SALES%'
4 GROUP BY job
5 HAVING SUM(sal)>5000
6 ORDER BY SUM(sal);

JOB PAYROLL
--------- ---------
ANALYST 6000
MANAGER 8275

108
Nesting Group Functions
•Display the maximum average salary.

SQL> SELECT max(avg(sal))


2 FROM emp
3 GROUP BY deptno;

MAX(AVG(SAL))
-------------
2916.6667

109
Summary
SELECT column, group_function (column)
FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[HAVING group_condition]
[ORDER BY column];

•Order of evaluation of the clauses:


• WHERE clause
• GROUP BY clause
• HAVING clause

110
Subqueries

111
Objectives

• Describe the types of problems that


subqueries can solve
• Define subqueries
• List the types of subqueries
• Write Single-row , Multiple-row ,Inline
views and Multiple column subqueries

112
Subquery to Solve a Problem

•“Who has a salary greater than Jones’s?”


Main Query

“Which employees have a salary greater


? than Jones’s salary?”

Subquery

?
“What is Jones’s salary?”

113
Subqueries
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).

114
Using a Subquery
SQL> SELECT ename
2 FROM employee2975
3 WHERE sal >
4 (SELECT sal
5 FROM employee
6 WHERE empno=7566);

ENAME
----------
KING
FORD
SCOTT

115
Guidelines for Subqueries
• Enclose subqueries in parentheses.
• Place subqueries on the right side of the
comparison operator.
• Do not add an ORDER BY clause to a
subquery.
• Use single-row operators with single-row
subqueries.
• Use multiple-row operators with multiple-
row subqueries.

116
Types of Subqueries
• Single-row subquery
Main query
returns CLERK
Subquery

• Multiple-row subquery
Main query
returns CLERK
Subquery
MANAGER
• Inline Views
From Clause of Main Query
returns
Single-row
Subquery Multiple-row
• Multiple-column subquery Multiple-column
Main query
returns CLERK 7900
Subquery 117
MANAGER 7698
Single-Row Subqueries
• Return only one row
• Use single-row comparison operators

Operator Meaning
= Equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
<> Not equal to

118
Single-Row Subqueries

SQL> SELECT ename, job


2 FROM employee
3 WHERE job = CLERK
4 (SELECT job
5 FROM employee
6 WHERE empno = 7369)
7 AND sal > 1100
8 (SELECT sal
9 FROM employee
10 WHERE empno = 7876);

ENAME JOB
---------- ---------
MILLER CLERK

119
Group Functions in Subquery

SQL> SELECT ename, job, sal


800
2 FROM employee
3 WHERE sal =
4 (SELECT MIN(sal)
5 FROM employee);

ENAME JOB SAL


---------- --------- ---------
SMITH CLERK 800

120
HAVING with Subqueries

• The Oracle Server executes subqueries first.

SQL> SELECT deptno, MIN(sal)


2 FROM employee
3 GROUP BY deptno
800
4 HAVING MIN(sal) >
5 (SELECT MIN(sal)
6 FROM employee
7 WHERE deptno = 20);

121
What Is Wrong ?
r y
ue
SQL> SELECT empno, ename bq
2 FROM employee su
3 WHERE sal = ow
4 (SELECT -
MIN(sal)r
p le
5 FROM
l t i
employee
6 GROUP BYu deptno);
m
i th
r w
ERROR:
t o
ORA-01427: single-row rasubquery returns more than
one row pe o
ow
no rows selected
e-r
g l
i n
S
122
Will This Statement Work?

SQL> SELECT ename, job


2 FROM employee
3 WHERE job =
4 (SELECT job es
u
5 FROM employee al
v
6 WHERE o
ename='SMYTHE');
n
ns
ur
no rows selected et
r
r y
u e
bq
Su

123
Multiple-Row Subqueries
• Return more than one row
• Use multiple-row comparison operators

Operator Meaning
IN Equal to any member in the list
ANY Compare value to each value returned by
the subquery

ALL Compare value to every value returned by


the subquery

124
ANY: Multiple-Row Subqueries

SQL> SELECT empno, ename, job 1300


2 FROM employee 1100
800
3 WHERE sal < ANY 950
4 (SELECT sal
5 FROM employee
6 WHERE job = 'CLERK')
7 AND job <> 'CLERK';

EMPNO ENAME JOB


--------- ---------- ---------
7654 MARTIN SALESMAN
7521 WARD SALESMAN

125
ALL: Multiple-Row Subqueries

SQL> SELECT empno, ename, job 1566.6667


2 FROM employee 2175
2916.6667
3 WHERE sal > ALL
4 (SELECT avg(sal)
5 FROM employee
6 GROUP BY deptno);

EMPNO ENAME JOB


--------- ---------- ---------
7839 KING PRESIDENT
7566 JONES MANAGER
7902 FORD ANALYST
7788 SCOTT ANALYST

126
Multiple-Column Subqueries
Main query
MANAGER 10

Subquery
SALESMAN 30
MANAGER 10
CLERK 20

Main query Values from a multiple-row and


compares to
multiple-column subquery

MANAGER 10 SALESMAN 30
MANAGER 10
CLERK 20
127
Multiple-Column Subqueries
•Display the name, dept. no, salary, and
commission of any employee whose salary
and commission matches both the
commission and salary of any employee in
department 30.

SQL> SELECT ename, deptno, sal, comm


2 FROM employee
3 WHERE (sal, NVL(comm,-1)) IN
4 (SELECT sal, NVL(comm,-1)
5 FROM employee
6 WHERE deptno = 30);
128
Summary

• Single row subqueries

• A multiple-column subquery returns more


than one column.

• A multiple-column subquery can also be


used in the FROM clause of a SELECT
statement.

129
DML Statements

130
Objectives

• Insert rows into a table


• Update rows in a table
• Delete rows from a table
• Controlling the Transactions

131
Data Manipulation Language

• A DML statement is executed when you:


• Add new rows to a table
• Modify existing rows in a table
• Remove existing rows from a table
• A transaction consists of a collection of
DML statements that form a logical unit of
work.

132
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.

133
Inserting New Rows

• Insert a new row containing values for each


column.
• List values in the default order of the
columns in the table.
• Optionally list the columns in the INSERT
clause.
SQL> INSERT INTO department (deptno, dname, loc)
2 VALUES (50, 'DEVELOPMENT', 'DETROIT');
1 row created.
• Enclose character and date values within
single quotation marks.
134
Insert Rows with Null Values
• Implicit method: Omit the column from the
column list.
SQL> INSERT INTO department (deptno, dname )
2 VALUES (60, 'MIS');
1 row created.

• Explicit method: Specify the NULL


keyword.
SQL> INSERT INTO department
2 VALUES (70, 'FINANCE', NULL);
1 row created.

135
Inserting Special Values
•The SYSDATE and USER function
records the current date and time.
SQL> INSERT INTO employee (empno, ename, job,
2 mgr, hiredate, sal, comm,
3 deptno)
4 VALUES (7196, USER, 'SALESMAN',
5 7782, SYSDATE, 2000, NULL,
6 10);
1 row created.

136
Inserting Specific Date Values
• Add a new employee.
SQL> INSERT INTO employee
2 VALUES (2296,'AROMANO','SALESMAN',7782,
3 TO_DATE('FEB 3,97', 'MON DD, YY'),
4 1300, NULL, 10);
1 row created.

• Verify your addition.


EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
----- ------- -------- ---- --------- ---- ---- ------
2296 AROMANO SALESMAN 7782 03-FEB-97 1300 10

137
Copying from Another Table

• Write your INSERT statement with a


subquery.
SQL> INSERT INTO managers(id, name, salary, hiredate)
2 SELECT empno, ename, sal, hiredate
3 FROM employee
4 WHERE job = 'MANAGER';
3 rows created.

• Do not use the VALUES clause.


• Match the number of columns in the
INSERT clause to those in the subquery.

138
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.

139
Updating Rows in a Table

• All rows in the table are modified if you


omit the WHERE clause.

SQL> UPDATE employee


2 SET deptno = 20;
14 rows updated.

140
Updating Rows:
• Integrity Constraint Error
i s t
e x
SQL> UPDATE employee
o t
2 SET deptno = 55
s n
3 WHERE deptno = 10;
o e
5 d
r 5
b e
u m
UPDATE emp
t n
*
e n
ERROR at line 1:tm
a r
e p
ORA-02291: integrity
violated - Dparent
constraint (USR.EMP_DEPTNO_FK)
• key not found

141
DELETE Statement

•You can remove existing rows from a


table by using the DELETE statement.

DELETE [FROM] table


[WHERE condition];

142
Deleting Rows from a Table
• Specific row or rows are deleted when you
specify the WHERE clause.
SQL> DELETE FROM department
2 WHERE dname = 'DEVELOPMENT';
1 row deleted.

• All rows in the table are deleted if you omit


the WHERE clause.
SQL> DELETE FROM department;
4 rows deleted.

143
Deleting Rows:
• Integrity Constraint Error
s a in
a i n ey
SQL> DELETE FROM department
n t k
2 WHERE deptno = 10; c o i g n
a t re
th fo
r o w sa
DELETE FROM dept a d a
*
e t e se
e l su
ERROR at line 1:
t t i
d constraint
o
ORA-02292: integrity
n record
t a
h found
(USR.EMP_DEPTNO_FK)
n
a ey .
violated - child
u c k b le
• Yo ar r tay
r i m e
p ot h
an 144
Database Transactions

•Consist of one of the following


statements:
• DML statements that make up one
consistent change to the data
• One DDL statement
• One DCL statement

145
Database Transactions

• Begin when the first executable SQL


statement is executed
• End with one of the following events:
• COMMIT or ROLLBACK
• DDL or DCL statement executes
(automatic commit)
• User exits
• System crashes

146
State of the Data
Before COMMIT or ROLLBACK
• The previous state of the data can be recovered.
• The current user can review the results of the
DML operations by using the SELECT
statement.
• Other users cannot view the results of the DML
statements by the current user.
• The affected rows are locked; other users
cannot change the data within the affected rows.

147
State of the Data
After COMMIT
• Data changes are made permanent in the
database.
• The previous state of the data is permanently lost.
• All users can view the results.
• Locks on the affected rows are released; those
rows are available for other users to manipulate.
• All savepoints are erased.

148
Committing Data

• Make the changes.


SQL> UPDATE employee
2 SET deptno = 10
3 WHERE empno = 7782;
1 row updated.

• Commit the changes.


SQL> COMMIT;
Commit complete.

149
State of the Data
After ROLLBACK
•Discard all pending changes by using the
ROLLBACK statement.
• Data changes are undone.
• Previous state of the data is restored.
• Locks on the affected rows are released.
SQL> DELETE FROM employee;
14 rows deleted.
SQL> ROLLBACK;
Rollback complete.

150
Rolling Back to a Marker

• Create a marker within a current transaction by


using the SAVEPOINT statement.
• Roll back to that marker by using the
ROLLBACK TO SAVEPOINT statement.

SQL> UPDATE...
SQL> SAVEPOINT update_done;
Savepoint created.
SQL> INSERT...
SQL> ROLLBACK TO update_done;
Rollback complete.

151
Statement-Level Rollback

• If a single DML statement fails during execution,


only that statement is rolled back.
• Oracle Server implements an implicit savepoint.
• All other changes are retained.
• The user should terminate transactions explicitly
by executing a COMMIT or ROLLBACK
statement.

152
Read Consistency

• Read consistency guarantees a consistent


view of the data at all times.
• Changes made by one user do not conflict
with changes made by another user.
• Ensures that on the same data:
• Readers do not wait for writers
• Writers do not wait for readers

153
Summary

Statement Description
INSERT Adds a new row to the table
UPDATE Modifies existing rows in the table
DELETE Removes existing rows from the table
COMMIT Makes all pending changes permanent
SAVEPOINT Allows a rollback to the savepoint marker
ROLLBACK Discards all pending data changes

154
DDL Statements

155
Objectives

• Describe the main database objects


• Create tables
• Describe the data types that can be used
when specifying column definition
• Alter table definitions
• Drop, rename, and truncate tables

156
Database Objects

Object Description
Table Basic unit of storage; composed of rows
and columns
View Logically represents subsets of data from
one or more tables
Sequence Generates primary key values
Index Improves the performance of some queries
Synonym Gives alternative names to objects

157
Naming Conventions

• Must begin with a letter


• Can be 1–30 characters long
• Must contain only A–Z, a–z, 0–9, _, $, and #
• Must not duplicate the name of another
object owned by the same user
• Must not be an Oracle Server reserved word

158
CREATE TABLE Statement

• You must have :


• CREATE TABLE privilege
• A storage area
CREATE TABLE [schema.]table
(column data type [DEFAULT expr];

• You specify:
• Table name
• Column name, column data type, and column
size
159
Reference other User’s Tables

• Tables belonging to other users are not in


the user’s schema.
• You should use the owner’s name as a
prefix to the table.

160
The DEFAULT Option
• Specify a default value for a column during an
insert.
… hiredate DATE DEFAULT SYSDATE, …

• Legal values are literal value, expression, or


SQL function.
• Illegal values are another column’s name or
pseudo column.
• The default data type must match the column
data type.
161
Creating Tables
• Create the table.
SQL> CREATE TABLE department
2 (deptno NUMBER(2),
3 dname VARCHAR2(14),
4 loc VARCHAR2(13));
Table created.

• Confirm table creation.


SQL> DESCRIBE department

Name Null? Type


--------------------------- -------- ---------
DEPTNO NOT NULL NUMBER(2)
DNAME VARCHAR2(14)
LOC VARCHAR2(13)

162
Querying the Data Dictionary
• Describe tables owned by the user.
SQL> SELECT *
2 FROM user_tables;

• View distinct object types owned by the user.

SQL> SELECT DISTINCT object_type


2 FROM user_objects;

• View tables, views, synonyms, and sequences


owned by the user.
SQL> SELECT *
2 FROM user_catalog;

163
Data types
Data type Description
VARCHAR2(size) Variable-length character data
CHAR(size) Fixed-length character data
NUMBER(p,s) Variable-length numeric data
DATE Date and time values
LONG Variable-length character data
up to 2 gigabytes
CLOB Single-byte character data up to 4
gigabytes
RAW and LONG RAW Raw binary data
BLOB Binary data up to 4 gigabytes
BFILE Binary data stored in an external
file; up to 4 gigabytes

164
Create Table Using Subquery
• Create a table and insert rows by combining
the CREATE TABLE statement and AS
subquery option.
CREATE TABLE table
[column(, column...)]
AS subquery;

• Match the number of specified columns to


the number of subquery columns.
• Define columns with column names and
default values.

165
Create Table Using Subquery
SQL> CREATE TABLE dept30
2 AS
3 SELECT empno, ename, sal*12 ANNSAL, hiredate
4 FROM employee
5 WHERE deptno = 30;
Table created.

SQL> DESCRIBE dept30

Name
Name Null?
Null? Type
Type
----------------------------
---------------------------- --------
-------- -----
-----
EMPNO
EMPNO NOT
NOT NULL
NULL NUMBER(4)
NUMBER(4)
ENAME
ENAME VARCHAR2(10)
VARCHAR2(10)
ANNSAL
ANNSAL NUMBER
NUMBER
HIREDATE
HIREDATE DATE
DATE

166
ALTER TABLE Statement
• Add a new column
• Modify an existing column
• Drop an existing column,
• Define a default value for the new column
ALTER TABLE table
ADD (column data type [DEFAULT expr]
[, column data type]...);
ALTER TABLE table
MODIFY (column data type [DEFAULT expr]
[, column data type]...);

ALTER TABLE table


DROP column column_name;
167
Adding a Column
“…add a
DEPT30 New column
new
EMPNO ENAME ANNSAL HIREDATE JOB column
------ ---------- -------- into
7698 BLAKE 34200 01-MAY-81 DEPT30
7654 MARTIN 15000 28-SEP-81 table…”
7499 ALLEN 19200 20-FEB-81
7844 TURNER 18000 08-SEP-81
...
DEPT30
EMPNO ENAME ANNSAL HIREDATE JOB

------ ---------- --------


7698 BLAKE 34200 01-MAY-81
7654 MARTIN 15000 28-SEP-81
7499 ALLEN 19200 20-FEB-81
7844 TURNER 18000 08-SEP-81
...
168
Adding a Column
• You use the ADD clause to add columns.
SQL> ALTER TABLE dept30
2 ADD (job VARCHAR2(9));
Table altered.

• The new column becomes the last column.


EMPNO ENAME ANNSAL HIREDATE JOB
--------- ---------- --------- --------- ----
7698 BLAKE 34200 01-MAY-81
7654 MARTIN 15000 28-SEP-81
7499 ALLEN 19200 20-FEB-81
7844 TURNER 18000 08-SEP-81
...
6 rows selected.

169
Modifying a Column
• You can change a column's data type, size,
and default value.
ALTER TABLE dept30
MODIFY (ename VARCHAR2(15));
Table altered.

• A change to the default value affects only


subsequent insertions to the table.

170
Dropping a Column
• You can remove a column and its contents
entirely from the table.
ALTER TABLE dept30
DROP COLUMN ename;
Table altered.
• You can ignore the column by set unused
column
SQL>ALTER TABLE dept30 set unused column ename;
Table altered.
SQL> ALTER TABLE dept30 drop unused columns;
Table altered.

171
Dropping a Table

• All data and structure in the table is


deleted.
• Any pending transactions are committed.
• All indexes are dropped.
• You cannot roll back this statement.

SQL> DROP TABLE dept30;


Table dropped.

172
Rename an Object

• To change the name of a table, view,


sequence, or synonym, you execute the
RENAME statement.
SQL> RENAME dept TO department;
Table renamed.

• You must be the owner of the object.

173
Truncating a Table
• The TRUNCATE TABLE statement:
• Removes all rows from a table
• Releases the storage space used by that table
SQL> TRUNCATE TABLE department;
Table truncated.

• Cannot roll back row removal when using


TRUNCATE
• Alternatively, remove rows by using the DELETE
statement

174
Adding Comments to a Table
• You can add comments to a table or column
by using the COMMENT statement.

SQL> COMMENT ON TABLE employee


2 IS 'Employee Information';
Comment created.

• Comments can be viewed through the data


dictionary views.
• ALL_COL_COMMENTS
• USER_COL_COMMENTS
• ALL_TAB_COMMENTS
• USER_TAB_COMMENTS
175
Constraints

176
Objectives

• Create the following types of constraints:


• NOT NULL
• UNIQUE key
• PRIMARY KEY
• FOREIGN KEY
• CHECK
• Query the USER_CONSTRAINTS table to
view all constraint definitions and names.

177
What Are Constraints?
• Constraints enforce rules at the table
[Link] prevent the deletion of a
table if there are dependencies.
• The following constraint types are valid in
Oracle:
• NOT NULL
• UNIQUE Key
• PRIMARY KEY
• FOREIGN KEY
• CHECK
178
Constraint Guidelines

• Name a constraint or the Oracle Server will


generate a name by using the SYS_Cn format.
• Create a constraint:
• At the same time as the table is created
• After the table has been created
• Define a constraint at the column or table level.
• View a constraint in the data dictionary.

179
Defining Constraints
CREATE TABLE [schema.]table
(column data type [DEFAULT expr]
[column_constraint],

[table_constraint]);

CREATE TABLE employee(


empno NUMBER(4),
ename VARCHAR2(10),

deptno NUMBER(7,2) NOT NULL,
CONSTRAINT emp_empno_pk
PRIMARY KEY (EMPNO));

180
Defining Constraints

• Column constraint level


column [CONSTRAINT constraint_name] constraint_type,

• Table constraint level


column,...
[CONSTRAINT constraint_name] constraint_type
(column, ...),

181
The NOT NULL Constraint
•Ensures that null values are not
permitted for the column
EMP
EMPNO ENAME JOB ... COMM DEPTNO

7839 KING PRESIDENT 10


7698 BLAKE MANAGER 30
7782 CLARK MANAGER 10
7566 JONES MANAGER 20
...

NOT NULL constraint Absence of NOT NULL NOT NULL constraint


(no row may contain constraint
a null value for (any row can contain
this column) null for this column)

182
The NOT NULL Constraint
•Defined at the column level
SQL> CREATE TABLE employee(
2 empno NUMBER(4),
3 ename VARCHAR2(10) NOT NULL,
4 job VARCHAR2(9),
5 mgr NUMBER(4),
6 hiredate DATE,
7 sal NUMBER(7,2),
8 comm NUMBER(7,2),
9 deptno NUMBER(7,2) NOT NULL);

183
The UNIQUE Key Constraint
UNIQUE key constraint
DEPARTMENT
DEPTNO DNAME LOC
------ ---------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

Insert into Not allowed


50 SALES DETROIT (DNAME-SALES
already exists)
60 BOSTON Allowed

184
The UNIQUE Key Constraint
•Defined at either the table level or the
column level

SQL> CREATE TABLE department(


2 deptno NUMBER(2),
3 dname VARCHAR2(14),
4 loc VARCHAR2(13),
5 CONSTRAINT dept_dname_uk UNIQUE(dname));

185
PRIMARY KEY Constraint
PRIMARY KEY
DEPARTMENT
DEPTNO DNAME LOC
------ ---------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

Insert into Not allowed


20 MARKETING DALLAS (DEPTNO-20 already
exists)
FINANCE NEW YORK Not allowed
(DEPTNO is null)

186
PRIMARY KEY Constraint
•Defined at either the table level or the
column level
SQL> CREATE TABLE department(
2 deptno NUMBER(2),
3 dname VARCHAR2(14),
4 loc VARCHAR2(13),
5 CONSTRAINT dept_dname_uk UNIQUE (dname),
6 CONSTRAINT dept_deptno_pk PRIMARY KEY(deptno));

187
FOREIGN KEY Constraint
DEPARTMENT
PRIMARY DEPTNO DNAME LOC
KEY ------ ---------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
...
EMPLOYEE
EMPNO ENAME JOB ... COMM DEPTNO FOREIGN
KEY
7839 KING PRESIDENT 10
7698 BLAKE MANAGER 30
... Not allowed
(DEPTNO-9
Insert into does not exist
in the DEPT
7571 FORD MANAGER ... 200 9 table
7571 FORD MANAGER ... 200 Allowed

188
FOREIGN KEY Constraint
•Defined at either the table level or the
column level
SQL> CREATE TABLE employee(
2 empno NUMBER(4),
3 ename VARCHAR2(10) NOT NULL,
4 job VARCHAR2(9),
5 mgr NUMBER(4),
6 hiredate DATE,
7 sal NUMBER(7,2),
8 comm NUMBER(7,2),
9 deptno NUMBER(7,2) NOT NULL,
10 CONSTRAINT emp_deptno_fk FOREIGN KEY (deptno)
11 REFERENCES dept (deptno));

189
FOREIGN KEY Constraint
Keywords :
• FOREIGN KEY
• Defines the column in the child table at
the table constraint level
• REFERENCES
• Identifies the table and column in the parent table
• ON DELETE CASCADE
• Allows deletion in the parent table and deletion of
the dependent rows in the child table

190
The CHECK Constraint
• Defines a condition that each row must satisfy
• Expressions that are not allowed:
• References to pseudo columns CURRVAL,
NEXTVAL, LEVEL, and ROWNUM
• Calls to SYSDATE, UID, USER, and
USERENV functions
• Queries that refer to other values in other
rows

..., deptno NUMBER(2),


CONSTRAINT emp_deptno_ck
CHECK (DEPTNO BETWEEN 10 AND 99),...

191
Adding a Constraint

ALTER TABLE table


ADD [CONSTRAINT constraint] type (column);

• Add or drop, but not modify, a constraint


• Enable or disable constraints
• Add a NOT NULL constraint by using the
MODIFY clause

192
Adding a Constraint
•Add a FOREIGN KEY constraint to the
EMP table indicating that a manager
must already exist as a valid employee
in the EMP table.
SQL> ALTER TABLE employee
2 ADD CONSTRAINT emp_mgr_fk
3 FOREIGN KEY(mgr) REFERENCES emp(empno);
Table altered.

193
Dropping a Constraint
• Remove the manager constraint from the
EMP table.
SQL> ALTER TABLE employee
2 DROP CONSTRAINT emp_mgr_fk;
Table altered.

• Remove the PRIMARY KEY constraint on


the DEPT table and drop the associated
FOREIGN KEY constraint on the
[Link] column.
SQL> ALTER TABLE department
2 DROP PRIMARY KEY CASCADE;
Table altered.

194
Disabling Constraints
• Execute the DISABLE clause of the ALTER
TABLE statement to deactivate an integrity
constraint.
• Apply the CASCADE option to disable
dependent integrity constraints.
SQL> ALTER TABLE employee
2 DISABLE CONSTRAINT emp_empno_pk CASCADE;
Table altered.

195
Enabling Constraints
• Activate an integrity constraint currently
disabled in the table definition by using the
ENABLE clause.
SQL> ALTER TABLE employee
2 ENABLE CONSTRAINT emp_empno_pk;
Table altered.

• A UNIQUE or PRIMARY KEY index is


automatically created if you enable a
UNIQUE key or PRIMARY KEY constraint.

196
Viewing Constraints
•Query the USER_CONSTRAINTS table to
view all constraint definitions and names.
SQL> SELECT constraint_name, constraint_type,
2 search_condition
3 FROM user_constraints
4 WHERE table_name = 'EMPLOYEE';

CONSTRAINT_NAME C SEARCH_CONDITION
------------------------ - -------------------------
SYS_C00674 C EMPNO IS NOT NULL
SYS_C00675 C DEPTNO IS NOT NULL
EMP_EMPNO_PK P
...

197
Summary
• Create the following types of constraints:
• NOT NULL
• UNIQUE key
• PRIMARY KEY
• FOREIGN KEY
• CHECK
• Query the USER_CONSTRAINTS table to view
all constraint definitions and names.

198
Views

199
Objectives
• Describe a view
• Create a view
• Retrieve data through a view
• Alter the definition of a view
• Insert, update, and delete data through
a view
• Drop a view

200
Database Objects
Object Description
Table Basic unit of storage; composed of rows
and columns
View Logically represents subsets of data from
one or more tables
Sequence Generates primary key values
Index Improves the performance of some queries
Synonym Alternative name for an object

201
Why Use Views?

• To restrict database access


• To make complex queries easy
• To allow data independence
• To present different views of the same data

202
Simple & Complex Views

•Feature Simple Complex


•Number of tables One One or more
•Contain functions No Yes
•Contain groups of data No Yes
•DML through view Yes Not always

203
Creating a View
• You embed a subquery within the CREATE
VIEW statement.
CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view
[(alias[, alias]...)]
AS subquery
[WITH CHECK OPTION [CONSTRAINT constraint]]
[WITH READ ONLY]

• The subquery can contain complex


SELECT syntax.
• The subquery cannot contain an ORDER
BY clause.

204
Creating a View
• Create a view, EMPVU10, that contains
details of employees in department 10.
SQL> CREATE VIEW empvu10
2 AS SELECT empno, ename, job
3 FROM employee
4 WHERE deptno = 10;
View created.

• Describe the structure of the view by using


the SQL*Plus DESCRIBE command.

SQL> DESCRIBE empvu10

205
Creating a View
• Create a view by using column aliases in
the subquery.
SQL> CREATE VIEW salvu30
2 AS SELECT empno EMPLOYEE_NUMBER, ename NAME,
3 sal SALARY
4 FROM employee
5 WHERE deptno = 30;
View created.

• Select the columns from this view by the


given alias names.

206
Retrieving Data from a View
SQL> SELECT *
2 FROM salvu30;

EMPLOYEE_NUMBER NAME SALARY


--------------- ---------- ---------
7698 BLAKE 2850
7654 MARTIN 1250
7499 ALLEN 1600
7844 TURNER 1500
7900 JAMES 950
7521 WARD 1250

6 rows selected.

207
Querying a View

SQL*Plus
USER_VIEWS
USER_VIEWS
SELECT *
EMPVU10
EMPVU10
FROM empvu10; SELECT empno,
SELECT empno, ename,
ename, job
job
FROM
FROM employee
employee
WHERE
WHERE deptno
deptno == 10;
10;
7839 KING PRESIDENT
7782 CLARK MANAGER EMP
7934 MILLER CLERK

208
Modifying a View
• Modify the EMPVU10 view by using
CREATE OR REPLACE VIEW clause. Add
an alias for each column name.
SQL> CREATE OR REPLACE VIEW empvu10
2 (employee_number, employee_name, job_title)
3 AS SELECT empno, ename, job
4 FROM employee
5 WHERE deptno = 10;
View created.

• Column aliases in the CREATE VIEW


clause are listed in the same order as the
columns in the subquery.

209
Creating a Complex View
•Create a complex view that contains group
functions to display values from two tables.

SQL> CREATE VIEW dept_sum_vu


2 (name, minsal, maxsal, avgsal)
3 AS SELECT [Link], MIN([Link]), MAX([Link]),
4 AVG([Link])
5 FROM employee e, department d
6 WHERE [Link] = [Link]
7 GROUP BY [Link];
View created.

210
DML Operations on a View
Rules for Performing DML Operations on a View
• You can perform DML operations on simple
views.
• You cannot remove a row if the view
contains the following:
• Group functions
• A GROUP BY clause
• The DISTINCT keyword

211
DML Operations on a View
Rules for Performing DML Operations on a View
• You cannot modify data in a view if it contains:
• Any of the conditions mentioned in the previous
slide
• Columns defined by expressions
• The ROWNUM pseudo column
• You cannot add data if:
• The view contains any of the conditions
mentioned above or in the previous slide
• There are NOT NULL columns in the base
tables that are not selected by the view
212
WITH CHECK OPTION
•You can ensure that DML on the view stays
within the domain of the view by using the WITH
CHECK OPTION.
SQL> CREATE OR REPLACE VIEW empvu20
2 AS SELECT *
3 FROM employee
4 WHERE deptno = 20
5 WITH CHECK OPTION CONSTRAINT empvu20_ck;
View created.

• Any attempt to change the department number for


any row in the view will fail because it violates the
WITH CHECK OPTION constraint.

213
Denying DML Operations
•You can ensure that no DML operations occur by
adding the WITH READ ONLY option to your view
definition.
SQL> CREATE OR REPLACE VIEW empvu10
2 (employee_number, employee_name, job_title)
3 AS SELECT empno, ename, job
4 FROM employee
5 WHERE deptno = 10
6 WITH READ ONLY;
View created.

• Any attempt to perform a DML on any row in


the view will result in Oracle Server error ORA-
01752.
214
Removing a View
•Remove a view without losing data because a
view is based on underlying tables in the
database.

DROP VIEW view;

SQL> DROP VIEW empvu10;


View dropped.

215
Summary

• A view is derived from data in other tables or


other views.
• A view provides the following advantages:
• Restricts database access
• Simplifies queries
• Provides data independence
• Allows multiple views of the same data
• Can be dropped without removing the
underlying data

216
DCL Statements

217
Objectives

• Create users
• Create roles to ease setup and
maintenance of the security model
• GRANT and REVOKE object privileges

218
Controlling User Access

Database
administrator

Username and password


privileges
Users

219
Privileges
• Database security
• System security
• Data security
• System privileges: Gain access to the
database
• Object privileges: Manipulate the content of
the database objects
• Schema: Collection of objects, such as
tables, views, and sequences

220
System Privileges

• More than 80 privileges are available.


• The DBA has high-level system privileges.
• Create new users
• Remove users
• Remove tables
• Backup tables

221
Creating Users

•The DBA creates users by using the CREATE


USER statement.
CREATE USER user
IDENTIFIED BY password;

SQL> CREATE USER scott


2 IDENTIFIED BY tiger;
User created.

222
User System Privileges
• Once a user is created, the DBA can grant
specific system privileges to a user.
GRANT privilege [, privilege...]
TO user [, user...];

• An application developer may have the following


system privileges:
– CREATE SESSION
– CREATE TABLE
– CREATE SEQUENCE
– CREATE VIEW
– CREATE PROCEDURE

223
Granting System Privileges

•The DBA can grant a user specific


system privileges.

SQL> GRANT create table, create sequence, create view


2 TO scott;
Grant succeeded.

224
What Is a Role?

Users

Manager

Privileges

Allocating privileges Allocating privileges


without a role with a role

225
Creating Roles

SQL>
SQL> CREATE
CREATE ROLE
ROLE manager;
manager;
Role
Role created.
created.

SQL>
SQL> GRANT
GRANT create
create table,
table, create
create view
view
22 to
to manager;
manager;
Grant
Grant succeeded.
succeeded.

SQL>
SQL> GRANT
GRANT manager
manager to
to BLAKE,
BLAKE, CLARK;
CLARK;
Grant
Grant succeeded.
succeeded.

226
Changing Your Password
• When the user account is created, a password
is initialized.
• Users can change their password by using the
ALTER USER statement.

SQL> ALTER USER scott


2 IDENTIFIED BY lion;
User altered.

227
Object Privileges
•Object
Privilege Table View Sequence Procedure
•ALTER Ö Ö
•DELETE Ö Ö
•EXECUTE Ö
•INDEX Ö
•INSERT Ö Ö
•REFERENCES Ö
•SELECT Ö Ö Ö
•UPDATE Ö Ö

228
Object Privileges
• Object privileges vary from object to object.
• An owner has all the privileges on the object.
• An owner can give specific privileges on that
owner’s object.

GRANT object_priv [(columns)]


ON object
TO {user|role|PUBLIC}
[WITH GRANT OPTION];

229
Granting Object Privileges
• Grant query privileges on the EMP table.
SQL> GRANT select
2 ON employee
3 TO sue, rich;
Grant succeeded.

• Grant privileges to update specific columns to


users and roles.
SQL> GRANT update (dname, loc)
2 ON department
3 TO scott, manager;
Grant succeeded.

230
GRANT Keywords
WITH GRANT OPTION & PUBLIC Keywords
• Give a user authority to pass along the privileges.
SQL> GRANT select, insert
2 ON department
3 TO scott
4 WITH GRANT OPTION;
Grant succeeded.

• Allow all users on the system to query data from


Alice’s DEPARTMENT table.
SQL> GRANT select
2 ON [Link]
3 TO PUBLIC;
Grant succeeded.
231
Confirming Privileges Granted
Data Dictionary Table Description
ROLE_SYS_PRIVS System privileges granted to roles
ROLE_TAB_PRIVS Table privileges granted to roles
USER_ROLE_PRIVS Roles accessible by the user
USER_TAB_PRIVS_MADE Object privileges granted on the
user's objects
USER_TAB_PRIVS_RECD Object privileges granted to the
user
USER_COL_PRIVS_MADE Object privileges granted on the
columns of the user's objects
USER_COL_PRIVS_RECD Object privileges granted to the
user on specific columns

232
Revoke Object Privileges
• You use the REVOKE statement to revoke
privileges granted to other users.
• Privileges granted to others through the
WITH GRANT OPTION will also be
revoked.

REVOKE {privilege [, privilege...]|ALL}


ON object
FROM {user[, user...]|role|PUBLIC}
[CASCADE CONSTRAINTS];

233
Revoking Object Privileges

•As user Alice, revoke the SELECT and


INSERT privileges given to user Scott
on the DEPARTMENT table.
SQL> REVOKE select, insert
2 ON department
3 FROM scott;
Revoke succeeded.

234
Summary
•CREATE USER Allows the DBA to create a user
•GRANT Allows the user to give other users
privileges to access the user's
objects
•CREATE ROLE Allows the DBA to create a
collection of privileges
•ALTER USER Allows users to change their
password
•REVOKE Removes privileges on an object
from users
235
Bibliography

• SQL Documentation ( SQL 9i PDF )


• Oracle Reference Manual.

236

You might also like