SQL Basics: SELECT Statements Guide
SQL Basics: SELECT Statements Guide
1
Objectives
2
Basic SELECT Statement
3
Writing SQL Statements
4
Selecting All Columns
SQL> SELECT *
2 FROM departments;
5
Selecting Specific Columns
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
9
Operator Precedence
_
* / +
• Parentheses can force precedence
10
Operator Precedence
SQL> SELECT ename, sal, 12*sal+100
2 FROM employees;
11
Using Parentheses
SQL> SELECT ename, sal, 12*(sal+100)
2 FROM employees;
12
Defining a Null Value
• NULL is UNASSIGNED Value.
13
Null Values in Arithmetic Expr
NAME 12*SAL+COMM
---------- -----------
KING
14
Defining Column Alias
15
Using Column Aliases
SQL> SELECT ename AS name, sal salary
2 FROM employees;
NAME SALARY
------------- ---------
...
17
Using Concatenation Operator
Employees
-------------------
KINGPRESIDENT
BLAKEMANAGER
CLARKMANAGER
JONESMANAGER
MARTINSALESMAN
ALLENSALESMAN
...
14 rows selected.
18
Literal Character Strings
19
Using ‘DISTINCT’ Clause
• Eliminate duplicate rows by using the
DISTINCT keyword
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
22
Using 'Where' and 'Order By'
Clauses
23
Objectives
24
Using ‘WHERE’ Clause
• Specify the Selection of rows retrieved by
the WHERE Clause.
SELECT [DISTINCT] {*, column [alias], ...}
FROM table
[WHERE condition(s)];
25
Using WHERE Clause
26
Character Strings and Dates
• Character / Dates are Represented by the
Single Quotation Marks.
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
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
32
Using LIKE Operator
33
Using LIKE Operator
• ESCAPE identifier to search for "%" or "_".
ENAME
----------
JAMES
WARD
34
Using IS NULL Operator
ENAME MGR
---------- ---------
KING
35
Logical Operators
Operator Meaning
36
Using AND Operator
• AND requires both conditions to be TRUE.
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';
ENAME JOB
---------- ---------
KING PRESIDENT
MARTIN SALESMAN
ALLEN SALESMAN
TURNER SALESMAN
WARD SALESMAN
39
Rules of Precedence
40
‘ORDER BY’ Clause
• Sort rows specified by the order: ASC/DESC
41
Sorting in Descending Order
SQL> SELECT ename, job, deptno, hiredate
2 FROM emp
3 ORDER BY hiredate DESC;
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;
43
Summary
44
SQL Functions
45
Objectives
46
Types of SQL Functions
Functions
Multiple-row Single-row
functions functions
47
Single-Row Functions
48
Single-Row Functions
Character
General Number
Single-row
functions
Conversion Date
49
Character Functions
Character
functions
CONCAT LOWER
SUBSTR UPPER
LENGTH INITCAP
INSTR
LPAD
50
Case Conversion Functions
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
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
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
57
Arithmetic with Dates
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
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
61
Implicit Data type Conversion
•For assignments, Oracle can
automatically convert
From To
VARCHAR2 or CHAR NUMBER
NUMBER VARCHAR2
DATE VARCHAR2
62
‘TO_CHAR’ with Dates
TO_CHAR(date, 'fmt')
63
Date Format
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')
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
TO_NUMBER(char)
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
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
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
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
75
Cartesian Product
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
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];
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
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 (+).
86
Using Outer Joins
SQL> SELECT [Link], [Link], [Link]
2 FROM emp e, dept d
3 WHERE [Link](+) = [Link]
4 ORDER BY [Link];
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
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
95
Using the COUNT Function
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
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
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
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
DEPTNO MAX(SAL)
--------- ---------
10 5000
20 3000
107
Using HAVING Clause
JOB PAYROLL
--------- ---------
ANALYST 6000
MANAGER 8275
108
Nesting Group Functions
•Display the maximum average salary.
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];
110
Subqueries
111
Objectives
112
Subquery to Solve a Problem
Subquery
?
“What is Jones’s salary?”
113
Subqueries
SELECT select_list
FROM table
WHERE expr operator
(SELECT select_list
FROM table);
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
ENAME JOB
---------- ---------
MILLER CLERK
119
Group Functions in Subquery
120
HAVING with Subqueries
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?
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
124
ANY: Multiple-Row Subqueries
125
ALL: Multiple-Row Subqueries
126
Multiple-Column Subqueries
Main query
MANAGER 10
Subquery
SALESMAN 30
MANAGER 10
CLERK 20
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.
129
DML Statements
130
Objectives
131
Data Manipulation Language
132
INSERT Statement
133
Inserting New Rows
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.
137
Copying from Another Table
138
UPDATE Statement
139
Updating Rows in a Table
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
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.
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
145
Database Transactions
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
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
SQL> UPDATE...
SQL> SAVEPOINT update_done;
Savepoint created.
SQL> INSERT...
SQL> ROLLBACK TO update_done;
Rollback complete.
151
Statement-Level Rollback
152
Read Consistency
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
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
158
CREATE TABLE Statement
• You specify:
• Table name
• Column name, column data type, and column
size
159
Reference other User’s Tables
160
The DEFAULT Option
• Specify a default value for a column during an
insert.
… hiredate DATE DEFAULT SYSDATE, …
162
Querying the Data Dictionary
• Describe tables owned by the user.
SQL> SELECT *
2 FROM user_tables;
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;
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.
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]...);
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.
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
172
Rename an 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.
174
Adding Comments to a Table
• You can add comments to a table or column
by using the COMMENT statement.
176
Objectives
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
179
Defining Constraints
CREATE TABLE [schema.]table
(column data type [DEFAULT expr]
[column_constraint],
…
[table_constraint]);
180
Defining Constraints
181
The NOT NULL Constraint
•Ensures that null values are not
permitted for the column
EMP
EMPNO ENAME JOB ... COMM DEPTNO
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
184
The UNIQUE Key Constraint
•Defined at either the table level or the
column level
185
PRIMARY KEY Constraint
PRIMARY KEY
DEPARTMENT
DEPTNO DNAME LOC
------ ---------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
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
191
Adding a Constraint
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.
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.
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?
202
Simple & Complex Views
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]
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.
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.
206
Retrieving Data from a View
SQL> SELECT *
2 FROM salvu30;
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.
209
Creating a Complex View
•Create a complex view that contains group
functions to display values from two tables.
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.
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.
215
Summary
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
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
221
Creating Users
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...];
223
Granting System Privileges
224
What Is a Role?
Users
Manager
Privileges
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.
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.
229
Granting Object Privileges
• Grant query privileges on the EMP table.
SQL> GRANT select
2 ON employee
3 TO sue, rich;
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.
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.
233
Revoking Object Privileges
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
236