0oracle SQL Scribe)
0oracle SQL Scribe)
0oracle SQL Scribe)
1.
Writing Basic SQL Statements 2. Restricting and Sorting Data 3. Displaying Data from Multiple Tables 4. Manipulating Data: INSERT, UPDATE, DELETE 5. Creating and Managing Tables 6. Creating Views
Table 1
Join
Table 1
Table 1
Table 2
Arithmetic Expressions
Create expressions on NUMBER and DATE data by using arithmetic operators.
Operator + Description Add Subtract
*
/
Multiply
Divide
Operator Precedence
* / +
10
Operator Precedence
SQL> SELECT ename, sal, 12*sal+100 2 FROM emp; 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 emp; ENAME SAL 12*(SAL+100) ---------- --------- ----------KING 5000 61200 BLAKE 2850 35400 CLARK 2450 30600 JONES 2975 36900 MARTIN 1250 16200 ... 14 rows selected.
12
ENAME JOB COMM ---------- --------- --------KING PRESIDENT BLAKE MANAGER ... TURNER SALESMAN 0 ... 14 rows selected.
13
14
15
...
16
Concatenation Operator
Concatenates columns or character strings to other columns Is represented by two vertical bars (||) Creates a resultant column that is a character expression
17
Employees ------------------KINGPRESIDENT BLAKEMANAGER CLARKMANAGER JONESMANAGER MARTINSALESMAN ALLENSALESMAN ... 14 rows selected.
18
19
20
Duplicate Rows
The default display of queries is all rows, including duplicate rows.
SQL> SELECT deptno 2 FROM emp;
21
DEPTNO --------10 20 30
22
Buffer
SQL Statements
Server
SQL*Plus
Query Results
23
SQL*Plus An environment Oracle proprietary Keywords can be abbreviated Commands do not allow manipulation of values in the database
SQL*Plus commands
SQL*Plus buffer
24
Overview of SQL*Plus
Log in to SQL*Plus.
25
Logging In to SQL*Plus
From Windows environment:
26
27
28
Objectives
After completing this lesson, you should be able to do the following: Limit the rows retrieved by a query Sort the rows retrieved by a query
32
EMP
EMPNO ENAME JOB ... DEPTNO 10 10 10
33
34
35
36
Comparison Operators
Operator
= > >= < <= <>
Meaning
Equal to Greater than Greater than or equal to Less than Less than or equal to Not equal to
37
38
39
ENAME SAL ---------- --------MARTIN 1250 TURNER 1500 WARD 1250 ADAMS 1100 MILLER 1300
Lower limit
Higher limit
40
ENAME SAL MGR ---------- --------- --------FORD 3000 7566 SMITH 800 7902 SCOTT 3000 7566 ADAMS 1100 7788
41
42
You can use the ESCAPE identifier to search for "%" or "_".
43
44
Logical Operators
Operator AND OR Meaning Returns TRUE if both component conditions are TRUE Returns TRUE if either component condition is TRUE Returns TRUE if the following condition is FALSE
NOT
45
46
EMPNO ENAME --------- ---------7839 KING 7698 BLAKE 7782 CLARK 7566 JONES 7654 MARTIN ... 7900 JAMES ... 14 rows selected.
47
48
Rules of Precedence
Order Evaluated 1 2 3 4 Operator All comparison operators NOT AND OR
49
Rules of Precedence
SQL> 2 3 4 5 SELECT FROM WHERE OR AND ename, job, sal emp job='SALESMAN' job='PRESIDENT' sal>1500;
JOB SAL --------- --------PRESIDENT 5000 SALESMAN 1250 SALESMAN 1600 SALESMAN 1500 SALESMAN 1250
50
Rules of Precedence
Use parentheses to force priority.
SQL> 2 3 4 5 SELECT FROM WHERE OR AND ename, job, sal emp (job='SALESMAN' job='PRESIDENT') sal>1500;
51
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 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.
52
53
54
Summary
SELECT FROM [WHERE [ORDER BY [DISTINCT] {*| column [alias], ...} table condition(s)] {column, expr, alias} [ASC|DESC]];
56
Objectives
After completing this lesson, you should be able to do the following: Write SELECT statements to access data from more than one table using equality and nonequality joins
View data that generally does not meet a join condition by using outer joins
Join a table to itself
58
DEPT
DEPTNO -----10 20 30 40 DNAME ---------ACCOUNTING RESEARCH SALES OPERATIONS LOC -------NEW YORK DALLAS CHICAGO BOSTON
MILLER ...
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.
59
What Is a Join?
Use a join to query data from more than one table.
SELECT FROM WHERE table1.column, table2.column table1, table2 table1.column1 = table2.column2;
Write the join condition in the WHERE clause. Prefix the column name with the table name when the same column name appears in more than one table.
60
Cartesian Product
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
61
DEPT (4 rows)
DEPTNO -----10 20 30 40 DNAME ---------ACCOUNTING RESEARCH SALES OPERATIONS LOC -------NEW YORK DALLAS CHICAGO BOSTON
MILLER ...
ENAME DNAME --------------KING ACCOUNTING BLAKE ACCOUNTING ... KING RESEARCH BLAKE RESEARCH ... 56 rows selected.
62
Types of Joins
Equijoin Non-equijoin Outer join Self join
63
What Is an Equijoin?
EMP
EMPNO ENAME DEPTNO ------ ------- ------7839 KING 10 7698 BLAKE 30 7782 CLARK 10 7566 JONES 20 7654 MARTIN 30 7499 ALLEN 30 7844 TURNER 30 7900 JAMES 30 7521 WARD 30 7902 FORD 20 7369 SMITH 20 ... 14 rows selected.
DEPT
DEPTNO ------10 30 10 20 30 30 30 30 30 20 20 ... 14 rows DNAME ---------ACCOUNTING SALES ACCOUNTING RESEARCH SALES SALES SALES SALES SALES RESEARCH RESEARCH selected. LOC -------NEW YORK CHICAGO NEW YORK DALLAS CHICAGO CHICAGO CHICAGO CHICAGO CHICAGO DALLAS DALLAS
Foreign key
Primary key
64
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.
65
66
DEPT
DEPTNO DNAME ------ --------10 ACCOUNTING 30 SALES 10 ACCOUNTING 20 RESEARCH 30 SALES 30 SALES 30 SALES 30 SALES 30 SALES 20 RESEARCH 20 RESEARCH ... 14 rows selected. LOC -------NEW YORK CHICAGO NEW YORK DALLAS CHICAGO CHICAGO CHICAGO CHICAGO CHICAGO DALLAS DALLAS
67
SQL> SELECT e.empno, e.ename, e.deptno, 2 d.deptno, d.loc 3 FROM emp e, dept d 4 WHERE e.deptno=d.deptno;
68
ORD
CUSTID ORDID ------- ------101 610 102 611 104 612 106 601 102 602 ITEM 106 604 ORDID ITEMID 106 605 ------ ------... 610 3 21 rows selected. 611 1 612 1 601 1 602 1 ... 64 rows selected.
69
Non-Equijoins
EMP
EMPNO ENAME SAL ------ ------- -----7839 KING 5000 7698 BLAKE 2850 7782 CLARK 2450 7566 JONES 2975 7654 MARTIN 1250 7499 ALLEN 1600 7844 TURNER 1500 7900 JAMES 950 ... 14 rows selected.
SALGRADE
GRADE LOSAL HISAL ----- ----- -----1 700 1200 2 1201 1400 3 1401 2000 4 2001 3000 5 3001 9999
salary in the EMP table is between low salary and high salary in the SALGRADE table
70
ENAME SAL GRADE ---------- --------- --------JAMES 950 1 SMITH 800 1 ADAMS 1100 1 ... 14 rows selected.
71
Outer Joins
EMP
ENAME ----KING BLAKE CLARK JONES ... DEPTNO -----10 30 10 20
DEPT
DEPTNO -----10 30 10 20 ... 40 DNAME ---------ACCOUNTING SALES ACCOUNTING RESEARCH OPERATIONS
72
Outer Joins
You use an outer join to also see rows that do not usually meet the join condition. Outer join operator is the plus sign (+).
SELECT table1.column, table2.column FROM table1, table2 WHERE table1.column(+) = table2.column; SELECT table1.column, table2.column FROM table1, table2 WHERE table1.column = table2.column(+);
73
ENAME DEPTNO DNAME ---------- --------- ------------KING 10 ACCOUNTING CLARK 10 ACCOUNTING ... 40 OPERATIONS 15 rows selected.
74
Self Joins
EMP (WORKER)
EMPNO ----7839 7698 7782 7566 7654 7499 ENAME -----KING BLAKE CLARK JONES MARTIN ALLEN MGR ---7839 7839 7839 7698 7698
EMP (MANAGER)
EMPNO ENAME ----- -------7839 7839 7839 7698 7698 KING KING KING BLAKE BLAKE
75
WORKER.ENAME||'WORKSFOR'||MANAG ------------------------------BLAKE works for KING CLARK works for KING JONES works for KING MARTIN works for BLAKE ... 13 rows selected.
76
Summary
SELECT FROM WHERE table1.column, table2.column table1, table2 table1.column1 = table2.column2;
77
A transaction consists of a collection of DML statements that form a logical unit of work.
80
50 DEVELOPMENT DETROIT
81
82
84
Do not use the VALUES clause. Match the number of columns in the INSERT clause to those in the subquery.
89
EMP
EMPNO ENAME 7839 7698 7782 7566 ... KING BLAKE CLARK JONES JOB PRESIDENT MANAGER MANAGER MANAGER ... DEPTNO 10 30 20 10 20
90
91
All rows in the table are modified if you omit the WHERE clause.
SQL> UPDATE employee 2 SET deptno = 20; 14 rows updated.
92
94
96
97
All rows in the table are deleted if you omit the WHERE clause.
SQL> DELETE FROM 4 rows deleted. department;
98
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
101
Committing Data
Make the changes.
SQL> UPDATE emp 2 SET deptno = 10 3 WHERE empno = 7782; 1 row updated.
108
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.
Read consistency ensures that on the same data:
Readers do not wait for writers Writers do not wait for readers
112
User A
SELECT * FROM emp;
User B
113
Locking
Oracle locks: Prevent destructive interaction between concurrent transactions Require no user action Automatically use the lowest level of restrictiveness Are held for the duration of the transaction Have two basic modes: Exclusive Share
114
Summary
Statement INSERT UPDATE DELETE COMMIT SAVEPOINT ROLLBACK Description Adds a new row to the table Modifies existing rows in the table Removes existing rows from the table Makes all pending changes permanent Allows a rollback to the savepoint marker Discards all pending data changes
115
Database Objects
Object
Table
Description
Basic unit of storage; composed of rows and columns
View
Generates primary key values Improves the performance of some queries Gives alternative names to objects
118
Naming Conventions
Must begin with a letter Can 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
119
You specify:
Table name Column name, column datatype, and
121
Creating Tables
Create the table.
SQL> CREATE TABLE dept 2 (deptno NUMBER(2), 3 dname VARCHAR2(14), 4 loc VARCHAR2(13)); Table created.
123
Datatypes
Datatype VARCHAR2(size) CHAR(size) Description Variable-length character data Fixed-length character data
NUMBER(p,s)
DATE LONG
CLOB
RAW and LONG RAW BLOB
BFILE
126
129
Adding a Column
DEPT30
EMPNO -----7698 7654 7499 7844 ... ENAME ANNSAL ---------- -------BLAKE 34200 MARTIN 15000 ALLEN 19200 TURNER 18000
New column
HIREDATE JOB
DEPT30
EMPNO -----7698 7654 7499 7844 ... ENAME ANNSAL ---------- -------BLAKE 34200 MARTIN 15000 ALLEN 19200 TURNER 18000 HIREDATE 01-MAY-81 28-SEP-81 20-FEB-81 08-SEP-81 JOB
130
Adding a Column
You use the ADD clause to add columns.
SQL> ALTER TABLE dept30 2 ADD (job VARCHAR2(9)); Table altered.
131
Modifying a Column
You can change a columns datatype, 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.
132
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.
133
134
Summary
Statement CREATE TABLE Description Creates a table
ALTER TABLE
DROP TABLE RENAME TRUNCATE COMMENT
137
6. Creating Views
Objectives
After completing this lesson, you should be able to do the following:
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
139
Database Objects
Object Table Description Basic unit of storage; composed of rows and columns Logically represents subsets of data from one or more tables Generates primary key values Improves the performance of some queries Alternative name for an object
View
140
What Is a View?
EMP Table
EMPNO ENAME JOB JOB MGR HIREDATE SAL COMM DEPTNO SAL COMM DEPTNO ----- ------- --------- ----- --------- ----- ----- -------
----- KING 7839 --------PRESIDENT ---- 17-NOV-81 ------ ----- ---------------------- 5000 10
-7698 BLAKE 7839 CLARK 7782 KING 10 7566 JONES MANAGER MANAGER 7839 01-MAY-81 7839 02-APR-81 2850 2450 5000 2975 1250 1400 1500 300 1600 300 30 10 20 30 30 MANAGER PRESIDENT 7839 09-JUN-81 17-NOV-81
7782 MARTIN 7654 CLARK MANAGER 7839 09-JUN-81 EMPVU10 ViewSALESMAN 7698 28-SEP-81 10 7499 ALLEN SALESMAN 7698 20-FEB-81 EMPNO 7844 TURNER CLERK ENAME JOB 7698 08-SEP-81 ------ 7934 MILLER SALESMAN 7782 23-JAN-82 -------- ----------10 7900 JAMES CLERK 7698 03-DEC-81 7839 7566 WARD SALESMAN 7698 22-FEB-81 KING PRESIDENT 7521 JONES MANAGER 7839 02-APR-81 7902 7782 20 FORD ANALYST 7566 03-DEC-81 CLARK MANAGER 7369 SCOTT 7566 7934 7788 SMITH CLERK MILLER ANALYST 7902 17-DEC-80 CLERK 09-DEC-82 20 7788 SCOTT ANALYST 7566 09-DEC-82 7782 23-JAN-82 7902 17-DEC-80 7566 03-DEC-81
1500 1300
950 1250 2975 3000 3000 800 3000
0
500
30
30 30 20 20 20
CLERK CLERK
CLERK CLERK ANALYST
7788 12-JAN-83
1100 1100
1300 800 3000
20
10
7698
BLAKE
MANAGER
7839 01-MAY-81
2850
141
142
Yes
Not always
143
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.
144
Creating a View
Create a view, EMPVU10, that contains details of employees in department 10.
SQL> 2 3 4 View CREATE VIEW AS SELECT FROM WHERE created. empvu10 empno, ename, job emp deptno = 10;
Describe the structure of the view by using the SQL*Plus DESCRIBE command.
SQL> DESCRIBE empvu10
145
Creating a View
Create a view by using column aliases in the subquery.
SQL> 2 3 4 5 View CREATE VIEW AS SELECT FROM WHERE created. salvu30 empno EMPLOYEE_NUMBER, ename NAME, sal SALARY emp deptno = 30;
Select the columns from this view by the given alias names.
146
6 rows selected.
147
Querying a View
SQL*Plus USER_VIEWS
SELECT * FROM empvu10;
EMPVU10
SELECT FROM WHERE empno, ename, job emp deptno = 10;
EMP
148
Modifying a View
Modify the EMPVU10 view by using CREATE OR REPLACE VIEW clause. Add an alias for each column name.
SQL> 2 3 4 5 View CREATE OR REPLACE VIEW empvu10 (employee_number, employee_name, job_title) AS SELECT empno, ename, job FROM emp WHERE deptno = 10; created.
Column aliases in the CREATE VIEW clause are listed in the same order as the columns in the subquery.
149
150
151
mentioned above or in the previous slide There are NOT NULL columns in the base tables that are not selected by the view
152
You can ensure that DML on the view stays within the domain of the view by using the WITH CHECK OPTION clause.
SQL> 2 3 4 5 View CREATE OR REPLACE VIEW empvu20 AS SELECT * FROM emp WHERE deptno = 20 WITH CHECK OPTION CONSTRAINT empvu20_ck; created.
Any attempt to change the department number for any row in the view will fail because it violates the WITH CHECK OPTION constraint.
153
Any attempt to perform a DML on any row in the view will result in Oracle Server error.
154
Removing a View
Remove a view without losing data because a view is based on underlying tables in the database.
DROP VIEW view;
155
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
underlying data
156