Professional Documents
Culture Documents
Oracle SQL Basic
Oracle SQL Basic
Data entry
Query processing
ORACLE SQL FUNDAMENTALS
Sorting
2
What is Database?
Database management
system
ORACLE SQL FUNDAMENTALS
Amounts of Data
Supports concurrent access to Very Large
Amounts of Data
Supports secure, atomic access to Very
Large Amounts of Data
Database system
architecture
It is common to describe databases in two
ways
The logical level:
What
tuples
Relational Schema
A relational schema specifies:
name of the relation: Students
names of fields: (sid, name, login, age, and gpa)
domain of each field: it is type of possible values
sid
53666
53688
53650
name
login
Jones jones@cs
Smith smith@eecs
Smith smith@math
ORACLE SQL FUNDAMENTALS
age gpa
18 3.4
18 3.2
19 3.8
8
Relational Instance
A relation instance contains a set of tuples
A relation instance is referred to as a relation.
A tuple can also be called a record or a row.
A relation instance is a set, and it has no
duplicate tuples.
Order
important.age
sidof tuples
name is notlogin
18
18
19
gpa
3.4
3.2
3.8
9
Example
database
10
Tables as Themes
Employees
empno
ename
sal
comm
7499
ALLEN
1600
300
7654
MARTIN
1250
1400
7698
BLAKE
2850
7839
KING
5000
7844
TURNER
1500
7986
STERN
1500
A row represents a
single Employee
11
Columns as Attributes
Employees
empno
Primary Key is
underlined
Uniquely
identifies an
employee
ename
sal
comm
7499
ALLEN
1600
300
7654
MARTIN
1250
1400
7698
BLAKE
2850
7839
KING
5000
7844
TURNER
1500
7986
STERN
1500
12
Rows as Objects/Entities
Employees
empno
ename
sal
an Employee Object
comm
7499
ALLEN
1600
300
7654
MARTIN
1250
1400
7698
BLAKE
2850
7839
KING
5000
7844
TURNER
1500
7986
STERN
1500
empno: 7654
ename: MARTIN
sal: 1250
comm: 1400
ItItcan
canbe
beuseful
usefulto
tothink
thinkof
ofeach
eachrow
rowas
asan
anobject
object
or
orentity
entityand
andthe
thetable
tableas
asaacollection
collectionof
ofthese
these
entities.
entities.
The
Thecolumns
columnsof
ofthe
thetable
tablecorrespond
correspondto
tothe
the
instance
instancevariables
variablesfor
foreach
eachobject
object
13
Entity Classes
In conceptual modeling, we focus on the
entity class
which represents the class of entities with
the same theme.
In general (but as we will see, not
14
Relationships
and ER Diagrams
15
ER (Entity-Relationship)
Diagrams
(Crow Magnum style)
Depicts a relationship
between Employees and
Depts
Employee
relationship
characterization
works for
empno
ename
sal
comm
Dept
deptno
dname
Crows Foot
16
Employee
ER Diagram
Relationship
Entity Class
Dept
Entity Class
Instance Diagram
7499
ALLEN
1600
300
7654
MARTIN
1250
1400
7844
TURNER
1500
10
SALES
Entity Instances
7698
7986
BLAKE
STERN
2850
30
1500
Entity Instances
ORACLE SQL FUNDAMENTALS
ACCOUNTING
Links
17
SQL History
It is a query language for relational databases.
Developed by IBM (system R) in the 1970s
Two standard organizations
ANSI (American National Standard Institutes)
ISO (International Organization for
Standardization)
Standards:
SQL-86, SQL-89, SQL-92, SQL-99 (current
standard)
ORACLE SQL FUNDAMENTALS
18
Data Types
19
SQL Statements
SELECT
Data retrieval
INSERT
UPDATE
DELETE
MERGE
Data manipulation
language (DML)
CREATE
ALTER
DROP
TRUNCATE
RENAME
COMMIT
ROLLBACK
SAVEPOINT
Transaction control
language (TCL)
GRANT
REVOKE
20
Data Definition
Language
(DDL)
Data Definition is used to create database
objects.
The statements are
1.CREATE
2.ALTER
3.DROP
4.TRUNCATE
21
Creating Tables
Naming Rules
Table names and column names:
Must begin with a letter
Must be 130 characters long
Must contain only AZ, az, 09, _, $, and #
Must not duplicate the name of another object
owned by the same user
Must not be an Oracle server reserved word
22
Creating Tables
Create the table
CREATE TABLE dept
(deptno NUMBER(2),
dname VARCHAR2(14),
loc
VARCHAR2(13));
Null?
---------
Type
--------NUMBER(2)
VARCHAR2(14)
VARCHAR2(13)
23
24
25
26
Column Name
Table Name
27
28
29
dropped at a time.
The table must have at least one column remaining in it after it is
altered.
Once a column is dropped, it cannot be recovered.
30
31
32
33
34
35
36
37
38
39
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.
SQL>SELECT last_name, job_id, department_id, hire_date
FROM employees
ORDER BY hire_date DESC ;
ORACLE SQL FUNDAMENTALS
40
41
42
43
44
45
WHERE clause.
46
Including Constraints
What are Constraints?
Constraints enforce rules at the table level.
Constraints prevent the deletion of a table
if there are dependencies.
The following constraint types are valid:
NOT NULL
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK
47
Including Constraints
Constraint Guidelines
Create a constraint either:
At the same time as the table is created,
or
After the table has been created
Define a constraint at the column or
table level.
View a constraint in the data dictionary.
48
49
50
51
52
satisfy
SQL>CREATE TABLE employees(employee_id NUMBER(6),last_name
VARCHAR2(25) NOT NULL,email VARCHAR2(25),salary
NUMBER(8,2) CONSTRAINT emp_salary_min CHECK (salary >
0));
SQL> ALTER TABLE EMPLOYEES ADD CONSTRAINT CK
CHECK(SALARY>0);
53
Adding a Constraint
Syntax
Use the ALTER TABLE statement to:
Add or drop a constraint, but not modify its structure
Enable or disable constraints
Add a NOT NULL constraint by using the MODIFY clause
SQL>ALTER TABLE employees ADD CONSTRAINT emp_manager_fk
FOREIGN KEY(manager_id)REFERENCES employees(employee_id);
Table altered.
SQL> alter table st modify sno number not null;
Table altered.
SQL> alter table st modify sno number unique;
Table altered.
SQL> alter table abcd modify ename constraint nn not null;
Table altered.
SQL> alter table abcd modify ename constraint uq unique;
Table altered.
54
55
Dropping a Constraint
Remove the manager constraint from the
EMPLOYEES table.
The constraint name in the drop clause is case
sensitive.
SQL>ALTER TABLE employees DROP CONSTRAINT emp_manager_fk;
Table altered.
56
Operators
Operators are the elements you use inside an
expression to articulate how you want specified
conditions to retrieve data.
Operators fall into six groups:
1.Arithmetic Operator
2.Comparison Operator
3.Character Operator
4.Logical Operator
5.Set Operator
6.Miscellaneous Operator
ORACLE SQL FUNDAMENTALS
57
Arithmetic Operator
The arithmetic operators are
Plus (+)
Minus (-)
Divide (/)
Multiply (*)
Modulo (%)
58
Comparison Operator
For
...
...
...
Example
WHERE hire_date='01-JAN-95'
WHERE salary>=6000
WHERE last_name='Smith'
59
60
range of values .
The range that you specify contains a lower limit and an
upper limit.
You must specify the lower limit first .
61
62
63
64
65
66
Logical Operators
67
68
69
WHERE
WHERE
WHERE
WHERE
2008 InnoMind
70
Rules of Precedence
71
Set Operators
72
Guidelines
The number of columns and the data types of the columns being
selected must be identical in all the SELECT statements used in the
query. The names of the columns need not be identical.
UNION operates over all of the columns being selected.
NULL values are not ignored during duplicate checking.
The IN operator has a higher precedence than the UNION operator.
By default, the output is sorted in ascending order of the first column of
the SELECT clause.
ORACLE SQL FUNDAMENTALS
73
74
75
76
77
78
79
The expressions in the select lists of the queries must match in number
and datatype. Queries that use UNION, UNION ALL, INTERSECT, and
MINUS SET operators in their WHERE clause must have the same
number and type of columns in their SELECT list. For example:
SQL>SELECT employee_id, department_id
FROM employees
WHERE (employee_id, department_id)
IN (SELECT employee_id, department_id
FROM employees
UNION
SELECT employee_id, department_id
FROM job_history);
The ORDER BY clause:
Can appear only at the very end of the statement
Will accept the column name, an alias, or the positional notation
The column name or alias, if used in an ORDER BY clause, must be from
the first SELECT list.
SET operators can be used in subqueries
.
80
SQL Functions
Functions are a very powerful feature of SQL
and can be used to do the following:
Perform calculations on data
Modify individual data items
Manipulate output for groups of rows
Format dates and numbers for display
Convert column data types
SQL functions sometimes take arguments and
always return a value.
ORACLE SQL FUNDAMENTALS
81
SQL Functions
Types of SQL Functions
There are two distinct types of functions:
Single-row functions
Multiple-row functions
Single-Row Functions
These functions operate on single rows only and return one result per row.
There are different types of single-row functions.
Character
Number
Date
Conversion
Multiple-Row Functions
Functions can manipulate groups of rows to give one result per group of rows.
These functions are known as group functions.
ORACLE SQL FUNDAMENTALS
82
Aggregate Functions
These functions are also referred to as group
AVG
COUNT
MAX
MIN
SUM
83
SUM
SQL> SELECT SUM(SAL) AS TOTAL FROM EMP;
TOTAL
---------29025
ORACLE SQL FUNDAMENTALS
84
You can use MIN and MAX for any data type.
MIN
SQL> SELECT MIN(SAL) FROM EMP;
MIN(SAL)
---------800
MAX
SQL> SELECT MAX(SAL) FROM EMP;
MAX(SAL)
---------5000
ORACLE SQL FUNDAMENTALS
85
86
87
88
89
two.
SQL>SELECT MAX(AVG(salary))
FROM employees
GROUP BY department_id;
90
91
92
93
01-AUG-95
ROUND(SYSDATE ,'YEAR')
01-JAN-96
TRUNC(SYSDATE ,'MONTH')
01-JUL-95
TRUNC(SYSDATE ,'YEAR')
01-JAN-95
94
95
Arithmetic Functions
ABS
Returns the absolute value of a numeric value.
SQL>SELECT ABS(-15) FROM DUAL;
Absolute
---------15
CEIL
Returns the smallest integer greater than or equal
to the numeric value passed to this function
SQL>SELECT order_total, CEIL(order_total) FROM orders
WHERE order_id = 2434;
ORDER_TOTAL
CEIL(ORDER_TOTAL)
--------------------------268651.8
268652
96
Arithmetic Functions
FLOOR
Returns the largest integer less than or equal to the
numeric value you pass to this function
SQL>SELECT FLOOR(15.7) FROM DUAL;
Floor
---------15
COS
Returns the cosine of a numeric value (expressed in
radians).
SQL>SELECT COS(180 * 3.14159265359/180)FROM DUAL;
Cosine of 180 degrees
---------------------1
COSH
Returns the hyperbolic cosine of a numeric value
(expressed in radians).
SQL>SELECT COSH(0) FROM DUAL;
Hyperbolic cosine of 0
---------------------ORACLE SQL FUNDAMENTALS
1
97
Arithmetic Functions
SIN
Returns the sine of a numeric value (expressed in radians).
SQL>SELECT SINH(1) FROM DUAL;
Hyperbolic sine of 1
-------------------1.17520119
SINH
Returns the hyperbolic sine of the numeric value.
SQL>SELECT SINH(1) FROM DUAL;
Hyperbolic sine of 1
-------------------1.17520119
TAN
Returns the tangent of a numeric value (expressed in
radians).
SQL>SELECT TAN(135 * 3.14159265359/180)FROM DUAL;
Tangent of 135 degrees
---------------------- 1
98
Arithmetic Functions
TANH
EXP
Returns e raised to the specified power (exponent), where
e=2.71828183
SQL>SELECT EXP(4) FROM DUAL;
e to the 4th power
-----------------54.59815
LN
Returns the natural logarithm of a numeric value. For example,
LN(3)returns 1.098612.
SQL>SELECT LN(95)FROM DUAL;
Natural log of 95
----------------4.55387689
99
Arithmetic
Functions
MOD
Returns the remainder of a division calculation
SQL>SELECT MOD(11,4) "Modulus" FROM DUAL;
Modulus
---------3
POWER
Returns a value raised to the exponent you pass to the
function
SQL>SELECT POWER(3,2) "Raised" FROM DUAL;
Raised
---------9
SIGN
Returns whether a numeric value is positive, negative, or 0
SQL>SELECT SIGN(-15) "Sign" FROM DUAL;
Sign
----------1
100
Arithmetic Functions
SQRT
Returns the square root of a non-negative
numeric value.
SQL>SELECT SQRT(26) "Square root" FROM DUAL;
Square root
----------5.09901951
101
Character Functions
102
Character Functions
Case Manipulation Functions
These functions convert case for
character strings.
103
Character Functions
Character-Manipulation Functions
These functions manipulate character
strings:
104
Conversion Functions
Data-Type Conversion
105
Conversion Functions
Using the TO_CHAR Function with Dates
The format model must be enclosed in single
quotation marks and is case sensitive.
The format model can include any valid date
format element. Be sure to separate the date
value from the format model by a comma.
The names of days and months in the output
are automatically padded with blanks.
106
Conversion Functions
Using the TO_CHAR Function with Numbers
SQL> SELECT TO_CHAR(sal,'9,999.00') from t1;
TO_CHAR(S
--------2,450.00
5,000.00
1,300.00
5,000.00
4,500.00
107
Conversion Functions
Using the TO_Number Function with Char
CHAR to NUMBER conversions succeed only if
the character string represents a valid number.
SQL> SELECT TO_NUMBER('12345') FROM DUAL;
TO_NUMBER('12345')
-----------------12345
108
Miscellaneous Functions
GREATEST
GREATEST returns the greatest of the list of one
or more expressions.
SQL>SELECT GREATEST ('HARRY', 'HARRIOT', 'HAROLD') "Greatest" FROM DUAL;
Greatest
-------HARRY
LEAST
LEAST returns the least of the list of expressions.
SQL>SELECT LEAST('HARRY','HARRIOT','HAROLD') "LEAST FROM DUAL;
LEAST
-----HAROLD
109
Joining Tables
One of the most powerful features of SQL is its capability
110
Cartesian Products
A Cartesian product is formed when:
A join condition is omitted
A join condition is invalid
All rows in the first table are joined to all rows in the second table
To avoid a Cartesian product, always include a valid join condition in a
WHERE clause.
SQL> select * from t1;
ENAME
---------CLARK
KING
MILLER
JOB
SAL
DEPTNO
--------- ---------- ---------MANAGER
2450
10
PRESIDENT
5000
10
CLERK
1300
10
DNAME
-------------ACCOUNTING
RESEARCH
LOC
--------NEW YORK
DALLAS
111
Equi
Join
112
Non Equi-Join
ENAME
SAL
GRADE
-------------------- ---------- ---------SMITH
800
1
ADAMS
1100
1
JAMES
950
1
WARD
1250
2
MARTIN
1250
2
MILLER
1300
2
ALLEN
1600
3
TURNER
1500
3
JONES
2975
4
BLAKE
2850
4
CLARK
2450
4
SCOTT
3000
4
FORD
3000
4
KING
5000
5
113
SQL>
ENAME
---------CLARK
KING
MILLER
RAJ
VARUN
DEPTNO
---------10
20
30
SQL>
JOB
SAL
DEPTNO
--------- ---------- ---------MANAGER
2450
10
PRESIDENT
5000
10
CLERK
1300
10
CLERK
5000
50
MANAGER
4500
60
LOC
-----------NEW YORK
DALLAS
CALIFORNIA
ENAME
---------MILLER
KING
CLARK
RAJ
VARUN
JOB
SAL
DEPTNO
DEPTNO DNAME
--------- ---------- ---------- ---------- -------------CLERK
1300
10
10 ACCOUNTING
PRESIDENT
5000
10
10 ACCOUNTING
MANAGER
2450
10
10 ACCOUNTING
CLERK
5000
50
NULL NULL
MANAGER
4500
60
NULL NULL
LOC
------------NEW YORK
NEW YORK
NEW YORK
NULL
NULL
114
SQL>
ENAME
---------CLARK
KING
MILLER
RAJ
VARUN
DEPTNO
---------10
20
30
JOB
SAL
DEPTNO
--------- ---------- ---------MANAGER
2450
10
PRESIDENT
5000
10
CLERK
1300
10
CLERK
5000
50
MANAGER
4500
60
LOC
-----------NEW YORK
DALLAS
CALIFORNIA
JOB
SAL
DEPTNO
DEPTNO
--------- ---------- ---------- ---------MANAGER
2450
10
10
PRESIDENT
5000
10
10
CLERK
1300
10
10
NULL
NULL
NULL
30
NULL
NULL
NULL
20
DNAME
-------------ACCOUNTING
ACCOUNTING
ACCOUNTING
PRODUCTION
RESEARCH
LOC
-----------NEW YORK
NEW YORK
NEW YORK
CALIFORNIA
DALLAS
115
SQL>
ENAME
---------CLARK
KING
MILLER
RAJ
VARUN
DEPTNO
---------10
20
30
JOB
SAL
DEPTNO
--------- ---------- ---------MANAGER
2450
10
PRESIDENT
5000
10
CLERK
1300
10
CLERK
5000
50
MANAGER
4500
60
LOC
-----------NEW YORK
DALLAS
CALIFORNIA
JOB
SAL
DEPTNO
DEPTNO
--------- ---------- ---------- ---------CLERK
1300
10
10
PRESIDENT
5000
10
10
MANAGER
2450
10
10
CLERK
5000
50
NULL
MANAGER
4500
60
NULL
NULL
NULL
NULL
30
NULL
NULL
NULL
20
DNAME
-------------ACCOUNTING
ACCOUNTING
ACCOUNTING
NULL
NULL
PRODUCTION
RESEARCH
LOC
----------NEW YORK
NEW YORK
NEW YORK
NULL
NULL
CALIFORNIA
DALLAS
7 rows selected.
116
Subqueries
A subquery is a SELECT statement that is embedded in a clause of
117
Subqueries
Subquery Syntax
118
Subqueries
Types of Subqueries
Single-row subqueries: Queries that return
119
Subqueries
Single-Row Subqueries
A single-row subquery is one that returns one
row from the inner SELECT statement.
This type of subquery uses a single-row
operator.
120
Subqueries
Using Aggregate Functions in a Subquery
You can display data from a main query by using a group function
121
Subqueries
Multiple-Row Subqueries
Subqueries that return more than one row are called multiple-row subqueries.
You use a multiple-row operator, instead of a single-row operator, with a
multiple-row subquery.
Nested Subqueries
Nesting is the act of embedding a subquery within
another subquery.
SQL>SELECT ALL C.NAME, C.ADDRESS, C.STATE,C.ZIP
FROM CUSTOMER C
WHERE C.NAME IN
(SELECT O.NAME FROM ORDERS O, PART P
WHERE O.PARTNUM = P.PARTNUM AND O.QUANTITY * P.PRICE >
(SELECT AVG(O.QUANTITY * P.PRICE) FROM ORDERS O, PART P
WHERE O.PARTNUM = P.PARTNUM))
122
Subqueries
Correlated Subqueries
Correlated subqueries enable you to use an
outside reference from outside the subquery
SQL>SELECT * FROM ORDERS O
WHERE 'ROAD BIKE' = (SELECT DESCRIPTION
FROM PART P WHERE P.PARTNUM = O.PARTNUM)
123
VIEWS
124
VIEWS
Advantages of Views
Views restrict access to the data because the view can
125
VIEWS
Simple Views and Complex Views
126
The subquery that defines a view can contain complex SELECT syntax,
127
128
129
Indexes
An index:
Is a schema object
Is used by the Oracle Server to speed up
the retrieval of rows by using a pointer
Can reduce disk I/O by using a rapid path
access method to locate data quickly
Is independent of the table it indexes
Is used and maintained automatically by
the Oracle Server
ORACLE SQL FUNDAMENTALS
130
Indexes
Creating an Index
Create an index on one or more columns by issuing the
131
Indexes
It is usually not worth creating an index if:
The table is small
The columns are not often used as a
condition in the query
Most queries are expected to retrieve more
than 2 to 4% of the rows in the table
The table is updated frequently
The indexed columns are referenced as
part of an
expression
ORACLE SQL FUNDAMENTALS
132
Indexes
Removing an Index
You cannot modify indexes.
To change an index, you must drop it and then
re-create it.
Remove an index definition from the data
dictionary by issuing the DROP INDEX
statement.
SQL>DROP INDEX upper_last_name_idx;
Index dropped.
133
Creating Sequence
134
Creating a Sequence
SQL>CREATE SEQUENCE dept_deptid_seq
INCREMENT BY 10
START WITH 120
MAXVALUE 9999
NOCACHE
NOCYCLE;
Sequence created.
135
Using a Sequence
Modifying a Sequence
If you reach the MAXVALUE limit for your sequence, no additional values
from the sequence are allocated and you will receive an error indicating
that the sequence exceeds the MAXVALUE.
To continue to use the sequence, you can modify it by using the ALTER
SEQUENCE statement.
SQL>ALTER SEQUENCE dept_deptid_seq
INCREMENT BY 20
MAXVALUE 999999
NOCACHE
NOCYCLE;
Sequence altered.
136
Removing a Sequence
Remove a sequence from the data
137
Transactions Control
Language commands
138
Controlling Transactions
139
Controlling Transactions
140
141
Committing Changes
State of the data before COMMIT or ROLLBACK
statements are issued:
Data manipulation operations primarily affect the database buffer; therefore, the
previous state of the data can be recovered.
The current user can review the results of the data manipulation operations by querying
the tables.
Other users cannot view the results of the data manipulation operations made by the
current user.
The affected rows are locked; other users cannot change the data in the affected rows.
142
Committing Data
Make the changes. Commit the changes.
DELETE FROM employees
WHERE employee_id = 99999;
1 row deleted.
INSERT INTO departments
VALUES (290, 'Corporate Tax', NULL, 1700);
1 row inserted.
143
144
145
146
Granting Object
Privileges
Grant query privileges on the EMPLOYEES
table.
SQL>GRANT select ON employees TO scott;
Grant succeeded.
147
Revoking Object
Privileges
As user Alice, revoke the SELECT and
INSERT privileges given to user Scott on
the DEPARTMENTS table.
SQL>REVOKE select, insert ON departments FROM scott;
Revoke succeeded.
148