0oracle sql scribe)
TRANSCRIPT
-
8/4/2019 0Oracle SQL Scribe)
1/128
Oracle SQL Overview
1. Writing Basic SQL Statements2. Restricting and Sorting Data
3. Displaying Data from Multiple Tables
4. Manipulating Data:INSERT, UPDATE, DELETE
5. Creating and Managing Tables6. Creating Views
-
8/4/2019 0Oracle SQL Scribe)
2/128
2
1. Writing Basic
SQL Statements
-
8/4/2019 0Oracle SQL Scribe)
3/128
3
Capabilities of SQL SELECT
StatementsSelection Projection
Table 1 Table 2
Table 1 Table 1Join
-
8/4/2019 0Oracle SQL Scribe)
4/128
4
Basic SELECT Statement
SELECT [DISTINCT] {*, column [alias],...}
FROM table;
SELECT identifies whatcolumns.
FROM identifies whichtable.
-
8/4/2019 0Oracle SQL Scribe)
5/128
5
Writing SQL Statements
SQL statements are not case sensitive.
SQL statements can be on one ormore lines.
Keywords cannot be abbreviated orsplit across lines.
Clauses are usually placed on separate
lines. Tabs and indents are used to enhance
readability.
-
8/4/2019 0Oracle SQL Scribe)
6/128
6
Selecting All Columns
DEPTNO DNAME LOC--------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
SQL> SELECT *
2 FROM dept;
-
8/4/2019 0Oracle SQL Scribe)
7/1287
Selecting Specific Columns
DEPTNO LOC
--------- -------------
10 NEW YORK
20 DALLAS
30 CHICAGO
40 BOSTON
SQL> SELECT deptno, loc
2 FROM dept;
-
8/4/2019 0Oracle SQL Scribe)
8/1288
Arithmetic Expressions
Create expressions on NUMBER and DATEdata by using arithmetic operators.
Operator
+
-
*
/
Description
Add
Subtract
Multiply
Divide
-
8/4/2019 0Oracle SQL Scribe)
9/1289
Using Arithmetic Operators
SQL> SELECT ename, sal, sal+300
2 FROM emp;
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.
-
8/4/2019 0Oracle SQL Scribe)
10/12810
Operator Precedence
Multiplication and division take priority
over addition and subtraction. Operators of the same priority are
evaluated from left to right.
Parentheses are used to forceprioritized evaluation and to clarifystatements.
* / + _
-
8/4/2019 0Oracle SQL Scribe)
11/12811
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.
-
8/4/2019 0Oracle SQL Scribe)
12/12812
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.
-
8/4/2019 0Oracle SQL Scribe)
13/12813
Defining a Null Value
A null is a value that is unavailable,unassigned, unknown, or inapplicable.
A null is not the same as zero or a blankspace.
SQL> SELECT ename, job, comm2 FROM emp;
ENAME JOB COMM
---------- --------- ---------
KING PRESIDENT
BLAKE MANAGER
...
TURNER SALESMAN 0
...
14 rows selected.
-
8/4/2019 0Oracle SQL Scribe)
14/128
14
Null Values
in Arithmetic ExpressionsArithmetic expressions containing a nullvalue evaluate to null.
SQL> select ename, 12*sal+comm2 from emp
3 WHERE ename='KING';
ENAME 12*SAL+COMM---------- -----------
KING
-
8/4/2019 0Oracle SQL Scribe)
15/128
15
Defining a Column Alias
Renames a column heading
Is useful with calculations
Immediately follows column name;optional AS keyword between columnname and alias
Requires double quotation marks if it
contains spaces or special charactersor is case sensitive
-
8/4/2019 0Oracle SQL Scribe)
16/128
16
Using Column Aliases
SQL> SELECT ename AS name, sal salary2 FROM emp;
NAME SALARY
------------- ---------
...
SQL> SELECT ename "Name",
2 sal*12 "Annual Salary"
3 FROM emp;
Name Annual Salary
------------- -------------
...
-
8/4/2019 0Oracle SQL Scribe)
17/128
17
Concatenation Operator
Concatenates columns or characterstrings to other columns
Is represented by two vertical bars (||)
Creates a resultant column that is acharacter expression
-
8/4/2019 0Oracle SQL Scribe)
18/128
18
Using the Concatenation
OperatorSQL> SELECT ename||job AS "Employees"
2 FROM emp;
Employees-------------------
KINGPRESIDENT
BLAKEMANAGER
CLARKMANAGER
JONESMANAGER
MARTINSALESMANALLENSALESMAN
...
14 rows selected.
-
8/4/2019 0Oracle SQL Scribe)
19/128
19
Literal Character Strings
A literal is a character, expression, ornumber included in the SELECT list.
Date and character literal values mustbe enclosed within single quotationmarks.
Each character string is output once for
each row returned.
-
8/4/2019 0Oracle SQL Scribe)
20/128
20
Using Literal Character Strings
Employee Details-------------------------
KING is a PRESIDENT
BLAKE is a MANAGER
CLARK is a MANAGER
JONES is a MANAGER
MARTIN is a SALESMAN...
14 rows selected.
SQL> SELECT ename ||' '||'is a'||' '||job
2 AS "Employee Details"
3 FROM emp;
-
8/4/2019 0Oracle SQL Scribe)
21/128
21
Duplicate Rows
The default display of queries is all rows,including duplicate rows.
SQL> SELECT deptno
2 FROM emp;
DEPTNO
---------
10
30
1020
...
14 rows selected.
-
8/4/2019 0Oracle SQL Scribe)
22/128
22
Eliminating Duplicate Rows
Eliminate duplicate rows by using theDISTINCT keyword in the SELECT clause.
SQL> SELECT DISTINCT deptno
2 FROM emp;
DEPTNO
---------
10
20
30
-
8/4/2019 0Oracle SQL Scribe)
23/128
23
SQL and SQL*Plus Interaction
SQL*Plus
SQL Statements Buffer SQL Statements
Server
Query ResultsSQL*PlusCommands
Formatted Report
-
8/4/2019 0Oracle SQL Scribe)
24/128
24
SQL Statements Versus
SQL*Plus Commands
SQLstatements
SQL
A language
ANSI standard
Keyword cannot beabbreviated
Statements manipulatedata and tabledefinitions in thedatabase
SQL*Plus
An environment
Oracle proprietary
Keywords can beabbreviated
Commands do notallow manipulation ofvalues in the database
SQLbuffer
SQL*Pluscommands
SQL*Plusbuffer
-
8/4/2019 0Oracle SQL Scribe)
25/128
25
Log in to SQL*Plus. Describe the table structure.
Edit your SQL statement.
Execute SQL from SQL*Plus.
Save SQL statements to files andappend SQL statements to files.
Execute saved files. Load commands from file to buffer
to edit.
Overview of SQL*Plus
-
8/4/2019 0Oracle SQL Scribe)
26/128
26
Logging In to SQL*Plus
From Windows environment:
From command line:sqlplus [username[/password
[@database]]]
-
8/4/2019 0Oracle SQL Scribe)
27/128
27
Displaying Table Structure
Use the SQL*Plus DESCRIBE command todisplay the structure of a table.
DESC[RIBE] tablename
-
8/4/2019 0Oracle SQL Scribe)
28/128
28
Displaying Table Structure
SQL> DESCRIBE dept
Name Null? Type
----------------- -------- ------------
DEPTNO NOT NULL NUMBER(2)DNAME VARCHAR2(14)
LOC VARCHAR2(13)
-
8/4/2019 0Oracle SQL Scribe)
29/128
2. Restricting and Sorting Data
-
8/4/2019 0Oracle SQL Scribe)
30/128
32
Objectives
After completing this lesson, you shouldbe able to do the following:
Limit the rows retrieved by a query
Sort the rows retrieved by a query
-
8/4/2019 0Oracle SQL Scribe)
31/128
33
Limiting Rows Using a Selection
"retrieve allemployees
in department 10"
EMP
EMPNO ENAME JOB ... DEPTNO
7839 KING PRESIDENT 107698 BLAKE MANAGER 307782 CLARK MANAGER 107566 JONES MANAGER 20...
EMP
EMPNO ENAME JOB ... DEPTNO
7839 KING PRESIDENT 107782 CLARK MANAGER 107934 MILLER CLERK 10
-
8/4/2019 0Oracle SQL Scribe)
32/128
34
Limiting Rows Selected
Restrict the rows returned by using theWHERE clause.
The WHERE clause follows the FROM
clause.
SELECT [DISTINCT] {*| column [alias], ...}
FROM table[WHERE condition(s)];
-
8/4/2019 0Oracle SQL Scribe)
33/128
35
Using the WHERE Clause
SQL> SELECT ename, job, deptno
2 FROM emp
3 WHERE job='CLERK';
ENAME JOB DEPTNO
---------- --------- ---------
JAMES CLERK 30
SMITH CLERK 20
ADAMS CLERK 20
MILLER CLERK 10
-
8/4/2019 0Oracle SQL Scribe)
34/128
36
Character Strings and Dates
Character strings and date values areenclosed in single quotation marks.
Character values are case sensitive and
date values are format sensitive. The default date format is DD-MON-YY.
SQL> SELECT ename, job, deptno
2 FROM emp3 WHERE ename = 'JAMES';
-
8/4/2019 0Oracle SQL Scribe)
35/128
37
Comparison Operators
Operator
=
>
>=
SELECT ename, sal, comm
2 FROM emp
3 WHERE sal
-
8/4/2019 0Oracle SQL Scribe)
37/128
39
Other Comparison Operators
Operator
BETWEEN
...AND...
IN(list)
LIKE
IS NULL
Meaning
Between two values (inclusive)
Match any of a list of values
Match a character pattern
Is a null value
-
8/4/2019 0Oracle SQL Scribe)
38/128
40
Using the BETWEEN Operator
ENAME SAL
---------- ---------
MARTIN 1250
TURNER 1500
WARD 1250ADAMS 1100
MILLER 1300
SQL> SELECT ename, sal
2 FROM emp
3 WHERE sal BETWEEN 1000 AND 1500;
Lowerlimit
Higherlimit
Use the BETWEEN operator to displayrows based on a range of values.
-
8/4/2019 0Oracle SQL Scribe)
39/128
41
Using the IN Operator
Use the IN operator to test for values in alist.
SQL> SELECT empno, ename, sal, mgr
2 FROM emp3 WHERE mgr IN (7902, 7566, 7788);
EMPNO ENAME SAL MGR
--------- ---------- --------- ---------
7902 FORD 3000 75667369 SMITH 800 7902
7788 SCOTT 3000 7566
7876 ADAMS 1100 7788
-
8/4/2019 0Oracle SQL Scribe)
40/128
42
Using the LIKE Operator
Use the LIKE operator to performwildcard searches of valid search stringvalues.
Search conditions can contain either
literal characters or numbers. % denotes zero or many characters.
_ denotes one character.
SQL> SELECT ename
2 FROM emp
3 WHERE ename LIKE 'S%';
-
8/4/2019 0Oracle SQL Scribe)
41/128
43
Using the LIKE Operator
You can combine pattern-matchingcharacters.
You can use the ESCAPE identifier tosearch for "%" or "_".
SQL> SELECT ename
2 FROM emp3 WHERE ename LIKE '_A%';
ENAME
----------
MARTIN
JAMES
WARD
-
8/4/2019 0Oracle SQL Scribe)
42/128
44
Using the IS NULL Operator
Test for null values with the IS NULLoperator.
SQL> SELECT ename, mgr2 FROM emp
3 WHERE mgr IS NULL;
ENAME MGR
---------- ---------KING
-
8/4/2019 0Oracle SQL Scribe)
43/128
45
Logical Operators
Operator
AND
OR
NOT
Meaning
Returns TRUE if bothcomponent
conditions are TRUE
Returns TRUE if eithercomponent
condition is TRUE
Returns TRUE if the following
condition is FALSE
-
8/4/2019 0Oracle SQL Scribe)
44/128
46
Using the 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
-
8/4/2019 0Oracle SQL Scribe)
45/128
47
Using the 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...
7900 JAMES CLERK 950
...
14 rows selected.
-
8/4/2019 0Oracle SQL Scribe)
46/128
48
Using the 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 SALESMANWARD SALESMAN
-
8/4/2019 0Oracle SQL Scribe)
47/128
49
Rules of Precedence
Override rules of precedence by usingparentheses.
Order Evaluated Operator
1 All comparisonoperators
2 NOT3 AND
4 OR
-
8/4/2019 0Oracle SQL Scribe)
48/128
50
Rules of Precedence
ENAME JOB SAL
---------- --------- ---------
KING PRESIDENT 5000
MARTIN SALESMAN 1250
ALLEN SALESMAN 1600TURNER SALESMAN 1500
WARD SALESMAN 1250
SQL> SELECT ename, job, sal2 FROM emp
3 WHERE job='SALESMAN'
4 OR job='PRESIDENT'
5 AND sal>1500;
-
8/4/2019 0Oracle SQL Scribe)
49/128
51
Rules of Precedence
ENAME JOB SAL
---------- --------- ---------
KING PRESIDENT 5000
ALLEN SALESMAN 1600
Use parentheses to force priority.SQL> SELECT ename, job, sal
2 FROM emp
3 WHERE (job='SALESMAN'
4 OR job='PRESIDENT')
5 AND sal>1500;
-
8/4/2019 0Oracle SQL Scribe)
50/128
52
ORDER BY Clause Sort rows with the ORDER BY clause
ASC: ascending order, default DESC: descending order
The ORDER BY clause comes last in theSELECT 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.
-
8/4/2019 0Oracle SQL Scribe)
51/128
53
Sorting in Descending Order
SQL> SELECT ename, job, deptno, hiredate2 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-81MARTIN SALESMAN 30 28-SEP-81
...
14 rows selected.
-
8/4/2019 0Oracle SQL Scribe)
52/128
54
Sorting by Column Alias
SQL> SELECT empno, ename, sal*12 annsal2 FROM emp
3 ORDER BY annsal;
EMPNO ENAME ANNSAL
--------- ---------- ---------7369 SMITH 9600
7900 JAMES 11400
7876 ADAMS 13200
7654 MARTIN 15000
7521 WARD 15000
7934 MILLER 15600
7844 TURNER 18000
...
14 rows selected.
-
8/4/2019 0Oracle SQL Scribe)
53/128
55
Sorting by Multiple Columns The order of ORDER BY list is the order of
sort.
You can sort by a column that is not in theSELECT list.
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.
-
8/4/2019 0Oracle SQL Scribe)
54/128
56
Summary
SELECT [DISTINCT] {*| column [alias], ...}
FROM table
[WHERE condition(s)]
[ORDER BY {column, expr, alias} [ASC|DESC]];
-
8/4/2019 0Oracle SQL Scribe)
55/128
3. Displaying Datafrom Multiple Tables
-
8/4/2019 0Oracle SQL Scribe)
56/128
58
Objectives
After completing this lesson, you shouldbe able to do the following:
Write SELECT statements to access
data from more than one table usingequality and nonequality joins
View data that generally does not meet
a join condition by using outer joins Join a table to itself
-
8/4/2019 0Oracle SQL Scribe)
57/128
59
EMPNO DEPTNO LOC----- ------- --------7839 10 NEW YORK7698 30 CHICAGO
7782 10 NEW YORK7566 20 DALLAS7654 30 CHICAGO7499 30 CHICAGO...14 rows selected.
Obtaining Data from Multiple TablesEMP DEPT
EMPNO ENAME ... DEPTNO------ ----- ... ------7839 KING ... 107698 BLAKE ... 30...7934 MILLER ... 10
DEPTNO DNAME LOC------ ---------- --------
10 ACCOUNTING NEW YORK20 RESEARCH DALLAS30 SALES CHICAGO40 OPERATIONS BOSTON
-
8/4/2019 0Oracle SQL Scribe)
58/128
60
What Is a Join?
Use a join to query data from more thanone table.
Write the join condition in the WHEREclause.
Prefix the column name with the tablename when the same column nameappears in more than one table.
SELECT table1.column, table2.column
FROM table1, table2
WHERE table1.column1 = table2.column2;
-
8/4/2019 0Oracle SQL Scribe)
59/128
61
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
all rows in the second table
To avoid a Cartesian product, alwaysinclude a valid join condition in aWHERE clause.
-
8/4/2019 0Oracle SQL Scribe)
60/128
62
Generating a Cartesian Product
ENAME DNAME------ ----------KING ACCOUNTINGBLAKE ACCOUNTING
...KING RESEARCHBLAKE RESEARCH...56 rows selected.
EMP (14 rows) DEPT (4 rows)
EMPNO ENAME ... DEPTNO------ ----- ... ------7839 KING ... 107698 BLAKE ... 30...7934 MILLER ... 10
DEPTNO DNAME LOC------ ---------- --------10 ACCOUNTING NEW YORK20 RESEARCH DALLAS30 SALES CHICAGO40 OPERATIONS BOSTON
Cartesian
product:14*4=56 rows
-
8/4/2019 0Oracle SQL Scribe)
61/128
63
Types of Joins
Equijoin Non-equijoin Outer join Self join
-
8/4/2019 0Oracle SQL Scribe)
62/128
64
What Is an Equijoin?EMP DEPT
EMPNO ENAME DEPTNO------ ------- -------7839 KING 107698 BLAKE 307782 CLARK 107566 JONES 20
7654 MARTIN 307499 ALLEN 307844 TURNER 307900 JAMES 307521 WARD 307902 FORD 20
7369 SMITH 20...14 rows selected.
DEPTNO DNAME LOC------- ---------- --------
10 ACCOUNTING NEW YORK30 SALES CHICAGO10 ACCOUNTING NEW YORK20 RESEARCH DALLAS
30 SALES CHICAGO30 SALES CHICAGO30 SALES CHICAGO30 SALES CHICAGO30 SALES CHICAGO20 RESEARCH DALLAS
20 RESEARCH DALLAS...14 rows selected.
Foreign key Primary key
-
8/4/2019 0Oracle SQL Scribe)
63/128
65
Retrieving Recordswith Equijoins
SQL> SELECT emp.empno, emp.ename, emp.deptno,
2 dept.deptno, dept.loc
3 FROM emp, dept
4 WHERE emp.deptno=dept.deptno;
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.
-
8/4/2019 0Oracle SQL Scribe)
64/128
66
Qualifying AmbiguousColumn Names
Use table prefixes to qualify columnnames that are in multiple tables.
Improve performance by using table
prefixes.
Distinguish columns that have identicalnames but reside in different tables by
using column aliases.
-
8/4/2019 0Oracle SQL Scribe)
65/128
67
Additional Search ConditionsUsing the AND Operator
EMP DEPT
EMPNO ENAME DEPTNO------ ------- -------7839 KING 107698 BLAKE 30
7782 CLARK 107566 JONES 207654 MARTIN 307499 ALLEN 307844 TURNER 307900 JAMES 30
7521 WARD 307902 FORD 207369 SMITH 20
...14 rows selected.
DEPTNO DNAME LOC------ --------- --------
10 ACCOUNTING NEW YORK30 SALES CHICAGO
10 ACCOUNTING NEW YORK20 RESEARCH DALLAS30 SALES CHICAGO30 SALES CHICAGO30 SALES CHICAGO30 SALES CHICAGO
30 SALES CHICAGO20 RESEARCH DALLAS20 RESEARCH DALLAS
...14 rows selected.
-
8/4/2019 0Oracle SQL Scribe)
66/128
68
Using Table Aliases
Simplify queries by using table aliases.SQL> SELECT emp.empno, emp.ename, emp.deptno,
2 dept.deptno, dept.loc
3 FROM emp, dept
4 WHERE emp.deptno=dept.deptno;
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;
-
8/4/2019 0Oracle SQL Scribe)
67/128
69
Joining More Than Two Tables
NAME CUSTID----------- ------JOCKSPORTS 100TKB SPORT SHOP 101VOLLYRITE 102JUST TENNIS 103
K+T SPORTS 105SHAPE UP 106WOMENS SPORTS 107... ...9 rows selected.
CUSTOMER
CUSTID ORDID------- -------
101 610102 611104 612106 601
102 602106 604106 605
...21 rows selected.
ORD
ORDID ITEMID------ -------
610 3611 1612 1601 1602 1
...64 rows selected.
ITEM
-
8/4/2019 0Oracle SQL Scribe)
68/128
70
Non-Equijoins
EMP SALGRADE
salary in the EMP
table is between
low salary and high
salary in the SALGRADE
table
EMPNO ENAME SAL------ ------- ------7839 KING 50007698 BLAKE 28507782 CLARK 2450
7566 JONES 29757654 MARTIN 12507499 ALLEN 16007844 TURNER 15007900 JAMES 950
...14 rows selected.
GRADE LOSAL HISAL----- ----- ------1 700 12002 1201 14003 1401 2000
4 2001 30005 3001 9999
-
8/4/2019 0Oracle SQL Scribe)
69/128
71
Retrieving Recordswith Non-Equijoins
ENAME SAL GRADE
---------- --------- ---------
JAMES 950 1
SMITH 800 1
ADAMS 1100 1
...
14 rows selected.
SQL> SELECT e.ename, e.sal, s.grade
2 FROM emp e, salgrade s
3 WHERE e.sal
4 BETWEEN s.losal AND s.hisal;
-
8/4/2019 0Oracle SQL Scribe)
70/128
72
Outer Joins
EMP DEPT
No employee in the
OPERATIONS department
ENAME DEPTNO----- ------KING 10BLAKE 30CLARK 10JONES 20...
DEPTNO DNAME------ ----------10 ACCOUNTING30 SALES10 ACCOUNTING
20 RESEARCH...40 OPERATIONS
-
8/4/2019 0Oracle SQL Scribe)
71/128
73
Outer Joins
You use an outer join to also see rowsthat do not usually meet the joincondition.
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(+);
-
8/4/2019 0Oracle SQL Scribe)
72/128
74
Using Outer Joins
SQL> SELECT e.ename, d.deptno, d.dname2 FROM emp e, dept d
3 WHERE e.deptno(+) = d.deptno
4 ORDER BY e.deptno;
ENAME DEPTNO DNAME
---------- --------- -------------
KING 10 ACCOUNTING
CLARK 10 ACCOUNTING
...
40 OPERATIONS15 rows selected.
-
8/4/2019 0Oracle SQL Scribe)
73/128
75
Self Joins
EMP (WORKER) EMP (MANAGER)
MGR in the WORKER table is equal to EMPNO in the
MANAGER table
EMPNO ENAME MGR----- ------ ----7839 KING7698 BLAKE 78397782 CLARK 7839
7566 JONES 78397654 MARTIN 76987499 ALLEN 7698
EMPNO ENAME----- --------
7839 KING7839 KING
7839 KING7698 BLAKE7698 BLAKE
-
8/4/2019 0Oracle SQL Scribe)
74/128
76
Joining a Table to Itself
WORKER.ENAME||'WORKSFOR'||MANAG-------------------------------
BLAKE works for KING
CLARK works for KING
JONES works for KING
MARTIN works for BLAKE
...13 rows selected.
SQL> SELECT worker.ename||' works for '||manager.ename2 FROM emp worker, emp manager
3 WHERE worker.mgr = manager.empno;
-
8/4/2019 0Oracle SQL Scribe)
75/128
77
Summary
Equijoin Non-equijoin Outer join Self join
SELECT table1.column, table2.column
FROM table1, table2
WHERE table1.column1 = table2.column2;
-
8/4/2019 0Oracle SQL Scribe)
76/128
4. Manipulating Data:INSERT, UPDATE, DELETE
-
8/4/2019 0Oracle SQL Scribe)
77/128
80
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 transactionconsists of a collection ofDML statements that form a logical unit
of work.
-
8/4/2019 0Oracle SQL Scribe)
78/128
81
Adding a New Row to a Table
DEPT
DEPTNO DNAME LOC
------ ---------- --------10 ACCOUNTING NEW YORK20 RESEARCH DALLAS30 SALES CHICAGO40 OPERATIONS BOSTON
New row
50 DEVELOPMENT DETROIT
DEPT
DEPTNO DNAME LOC------ ---------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS30 SALES CHICAGO40 OPERATIONS BOSTON
insert a new row
into DEPT table
50 DEVELOPMENT DETROIT
-
8/4/2019 0Oracle SQL Scribe)
79/128
82
The INSERT Statement
Add new rows to a table by using theINSERT statement.
Only one row is inserted at a time with
this syntax.
INSERT INTO table [(column [, column...])]
VALUES (value [, value...]);
I i N R
-
8/4/2019 0Oracle SQL Scribe)
80/128
83
Inserting New Rows
Insert a new row containing values foreach column.
List values in the default order of the
columns in the table. Optionally list the columns in the
INSERT clause.
Enclose character and date valueswithin single quotation marks.
SQL> INSERT INTO dept (deptno, dname, loc)
2 VALUES (50, 'DEVELOPMENT', 'DETROIT');1 row created.
I i R i h N ll V l
-
8/4/2019 0Oracle SQL Scribe)
81/128
84
Inserting Rows with Null Values
Implicit method: Omit the column fromthe column list.
SQL> INSERT INTO dept (deptno, dname )
2 VALUES (60, 'MIS');
1 row created.
Explicit method: Specify the NULLkeyword.
SQL> INSERT INTO dept2 VALUES (70, 'FINANCE', NULL);
1 row created.
C i R
-
8/4/2019 0Oracle SQL Scribe)
82/128
89
Copying Rowsfrom Another Table
Write your INSERT statement with asubquery.
Do not use the VALUES clause.
Match the number of columns in theINSERT clause to those in the subquery.
SQL> INSERT INTO managers(id, name, salary, hiredate)
2 SELECT empno, ename, sal, hiredate3 FROM emp
4 WHERE job = 'MANAGER';
3 rows created.
Ch i D t i T bl
-
8/4/2019 0Oracle SQL Scribe)
83/128
90
Changing Data in a TableEMP
update a row
in EMP table
EMP
EMPNO ENAME JOB ... DEPTNO
7839 KING PRESIDENT 107698 BLAKE MANAGER 307782 CLARK MANAGER 107566 JONES MANAGER 20...
20
EMPNO ENAME JOB ... DEPTNO
7839 KING PRESIDENT 107698 BLAKE MANAGER 307782 CLARK MANAGER 107566 JONES MANAGER 20
...
Th UPDATE St t t
-
8/4/2019 0Oracle SQL Scribe)
84/128
91
The UPDATE Statement
Modify existing rows with the UPDATEstatement.
Update more than one row at a time, ifrequired.
UPDATE table
SETcolumn
=value
[,column
=value, ...
][WHERE condition];
U d ti R i T bl
-
8/4/2019 0Oracle SQL Scribe)
85/128
92
Updating Rows in a Table
Specific row or rows are modified whenyou specify the WHERE clause.
All rows in the table are modified if youomit the WHERE clause.
SQL> UPDATE emp
2 SET deptno = 20
3 WHERE empno = 7782;1 row updated.
SQL> UPDATE employee
2 SET deptno = 20;
14 rows updated.
U d ti R B d
-
8/4/2019 0Oracle SQL Scribe)
86/128
94
Updating Rows Basedon Another Table
Use subqueries in UPDATE statements toupdate rows in a table based on valuesfrom another table.
SQL> UPDATE employee2 SET deptno = (SELECT deptno
3 FROM emp
4 WHERE empno = 7788)
5 WHERE job = (SELECT job
6 FROM emp
7 WHERE empno = 7788);2 rows updated.
R i R f T bl
-
8/4/2019 0Oracle SQL Scribe)
87/128
96
delete a row
from DEPT table
Removing a Row from a TableDEPT
DEPTNO DNAME LOC------ ---------- --------10 ACCOUNTING NEW YORK20 RESEARCH DALLAS30 SALES CHICAGO40 OPERATIONS BOSTON50 DEVELOPMENTDETROIT60 MIS...
DEPT
DEPTNO DNAME LOC------ ---------- --------
10 ACCOUNTING NEW YORK20 RESEARCH DALLAS
30 SALES CHICAGO40 OPERATIONS BOSTON60 MIS...
Th DELETE St t t
-
8/4/2019 0Oracle SQL Scribe)
88/128
97
The DELETE Statement
You can remove existing rows from atable by using the DELETE statement.
DELETE [FROM] table
[WHERE condition];
D l ti R f T bl
-
8/4/2019 0Oracle SQL Scribe)
89/128
98
Specific rows are deleted when youspecify the WHERE clause.
All rows in the table are deleted if youomit the WHERE clause.
Deleting Rows from a Table
SQL> DELETE FROM department
2 WHERE dname = 'DEVELOPMENT';
1 row deleted.
SQL> DELETE FROM department;
4 rows deleted.
Database Transactions
-
8/4/2019 0Oracle SQL Scribe)
90/128
101
Database Transactions
Consist of one of the followingstatements:
DML statements that make up one
consistent change to the data One DDL statement
One DCL statement
Committing Data
-
8/4/2019 0Oracle SQL Scribe)
91/128
108
Committing Data
SQL> UPDATE emp
2 SET deptno = 10
3 WHERE empno = 7782;
1 row updated.
Make the changes.
Commit the changes.SQL> COMMIT;
Commit complete.
Read Consistency
-
8/4/2019 0Oracle SQL Scribe)
92/128
112
Read Consistency
Read consistency guarantees aconsistent view of the data at all times.
Changes made by one user do notconflict with changes made by anotheruser.
Read consistency ensures that on thesame data:
Readers do not wait for writers Writers do not wait for readers
Implementation of Read
-
8/4/2019 0Oracle SQL Scribe)
93/128
113
Implementation of ReadConsistency
UPDATE emp
SET sal = 2000
WHERE ename ='SCOTT';
Datablocks
Rollbacksegments
changedandunchangeddata
beforechangeold data
User A
User B
Readconsistentimage
SELECT *
FROM emp;
Locking
-
8/4/2019 0Oracle SQL Scribe)
94/128
114
Locking
Oracle locks:
Prevent destructive interaction betweenconcurrent transactions
Require no user action
Automatically use the lowest level ofrestrictiveness
Are held for the duration of thetransaction
Have two basic modes: Exclusive Share
Summary
-
8/4/2019 0Oracle SQL Scribe)
95/128
115
Summary
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
Statement
INSERT
UPDATE
DELETE
COMMIT
SAVEPOINT
ROLLBACK
-
8/4/2019 0Oracle SQL Scribe)
96/128
5. Creating and ManagingTables
Database Objects
-
8/4/2019 0Oracle SQL Scribe)
97/128
118
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
Naming Conventions
-
8/4/2019 0Oracle SQL Scribe)
98/128
119
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 anotherobject owned by the same user
Must not be an Oracle Server reservedword
The CREATE TABLE Statement
-
8/4/2019 0Oracle SQL Scribe)
99/128
120
The CREATE TABLE Statement
You must have : CREATE TABLE privilege
A storage area
You specify:
Table name Column name, column datatype, and
column size
CREATE TABLE [schema.]table(columndatatype [DEFAULT expr][, ...]);
Referencing Another Users
-
8/4/2019 0Oracle SQL Scribe)
100/128
121
Referencing Another User s
Tables
Tables belonging to other users are notin the users schema.
You should use the owners name as aprefix to the table.
Creating Tables
-
8/4/2019 0Oracle SQL Scribe)
101/128
123
Creating Tables
SQL> CREATE TABLE dept2 (deptno NUMBER(2),
3 dname VARCHAR2(14),
4 loc VARCHAR2(13));
Table created.
Create the table.
Confirm table creation.SQL> DESCRIBE dept
Name Null? Type
--------------------------- -------- ---------
DEPTNO NUMBER(2)
DNAME VARCHAR2(14)
LOC VARCHAR2(13)
Datatypes
-
8/4/2019 0Oracle SQL Scribe)
102/128
126
yp
Datatype 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 dataup to 2 gigabytes
CLOB Single-byte character data up to 4gigabytes
RAW and LONG RAW Raw binary data
BLOB Binary data up to 4 gigabytes
BFILE Binary data stored in an externalfile; up to 4 gigabytes
The ALTER TABLE Statement
-
8/4/2019 0Oracle SQL Scribe)
103/128
129
The ALTER TABLE Statement
Use the ALTER TABLE statement to:
Add a new column
Modify an existing column
Define a default value for the new columnALTER TABLE table
ADD (column datatype [DEFAULT expr]
[, column datatype]...);
ALTER TABLE tableMODIFY (column datatype [DEFAULT expr]
[, column datatype]...);
Adding a Column
-
8/4/2019 0Oracle SQL Scribe)
104/128
130
Adding a ColumnDEPT30
EMPNO ENAME ANNSAL HIREDATE------ ---------- --------7698 BLAKE 34200 01-MAY-817654 MARTIN 15000 28-SEP-817499 ALLEN 19200 20-FEB-817844 TURNER 18000 08-SEP-81
...
add anewcolumnintoDEPT30table
DEPT30
EMPNO ENAME ANNSAL HIREDATE------ ---------- --------7698 BLAKE 34200 01-MAY-817654 MARTIN 15000 28-SEP-817499 ALLEN 19200 20-FEB-817844 TURNER 18000 08-SEP-81
...
JOB
JOB
New column
Adding a Column
-
8/4/2019 0Oracle SQL Scribe)
105/128
131
Adding a Column
You use the ADD clause to add columns.
EMPNO ENAME ANNSAL HIREDATE JOB
--------- ---------- --------- --------- ----
7698 BLAKE 34200 01-MAY-81
7654 MARTIN 15000 28-SEP-81
7499 ALLEN 19200 20-FEB-817844 TURNER 18000 08-SEP-81
...
6 rows selected.
SQL> ALTER TABLE dept30
2 ADD (job VARCHAR2(9));
Table altered.
The new column becomes the last column.
Modifying a Column
-
8/4/2019 0Oracle SQL Scribe)
106/128
132
Modifying a Column
You can change a columns datatype,size, and default value.
A change to the default value affectsonly subsequent insertions to the table.
ALTER TABLE dept30
MODIFY (ename VARCHAR2(15));
Table altered.
Dropping a Table
-
8/4/2019 0Oracle SQL Scribe)
107/128
133
Dropping a Table
All data and structure in the table isdeleted.
Any pending transactions are
committed. All indexes are dropped.
You cannotroll back this statement.
SQL> DROP TABLE dept30;
Table dropped.
Changing the Name of an Object
-
8/4/2019 0Oracle SQL Scribe)
108/128
134
Changing the Name of an Object
To change the name of a table, view,sequence, or synonym, you execute theRENAME statement.
You must be the owner of the object.
SQL> RENAME dept TO department;Table renamed.
Summary
-
8/4/2019 0Oracle SQL Scribe)
109/128
137
Summary
Statement Description
CREATE TABLE Creates a table
ALTER TABLE Modifies table structures
DROP TABLE Removes the rows and table structure
RENAME Changes the name of a table, view,sequence, or synonym
TRUNCATE Removes all rows from a table andreleases the storage space
COMMENT Adds comments to a table or view
-
8/4/2019 0Oracle SQL Scribe)
110/128
6. Creating Views
Objectives
-
8/4/2019 0Oracle SQL Scribe)
111/128
139
Objectives
After completing this lesson, you shouldbe 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 througha view
Drop a view
Database Objects
-
8/4/2019 0Oracle SQL Scribe)
112/128
140
Database Objects
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
Object
Table
View
Sequence
Index
Synonym
What Is a View?
-
8/4/2019 0Oracle SQL Scribe)
113/128
141
What Is a View?
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO----- ------- --------- ----- --------- ----- ----- -------
7839 KING PRESIDENT 17-NOV-81 5000 10
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7900 JAMES CLERK 7698 03-DEC-81 950 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7369 SMITH CLERK 7902 17-DEC-80 800 20
7788 SCOTT ANALYST 7566 09-DEC-82 3000 20
7876 ADAMS CLERK 7788 12-JAN-83 1100 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10
EMP Table
EMPNO ENAME JOB MGR HIREDATE SAL COMMDEPTNO
----- -------- --------- ---- --------- ------ ----- ------
-
7839 KING PRESIDENT 17-NOV-81 5000
10
7782 CLARK MANAGER 7839 09-JUN-81 1500 300
10
7934 MILLER CLERK 7782 23-JAN-82 1300
10
7566 JONES MANAGER 7839 02-APR-81 2975
20
7788 SCOTT ANALYST 7566 09-DEC-82 3000
20
7876 ADAMS CLERK 7788 12-JAN-83 1100
20
7369 SMITH CLERK 7902 17-DEC-80 800
20
7902 FORD ANALYST 7566 03-DEC-81 3000
20
7698 BLAKE MANAGER 7839 01-MAY-81 2850
EMPNO ENAME JOB------ -------- -----------
7839 KING PRESIDENT
7782 CLARK MANAGER
7934 MILLER CLERK
EMPVU10 View
Why Use Views?
-
8/4/2019 0Oracle SQL Scribe)
114/128
142
Why Use Views?
To restrict database access
To make complex queries easy
To allow data independence
To present different views of the samedata
Simple Views
-
8/4/2019 0Oracle SQL Scribe)
115/128
143
Simple Viewsand Complex Views
Feature Simple Views Complex Views
Number of tables One One or more
Contain functions No YesContain groups of data No Yes
DML through view Yes Not always
Creating a View
-
8/4/2019 0Oracle SQL Scribe)
116/128
144
Creating a View
You embed a subquery within theCREATE VIEW statement.
The subquery can contain complexSELECT syntax.
The subquery cannot contain anORDER BY clause.
CREATE [OR REPLACE] [FORCE|NOFORCE] VIEWview
[(alias[, alias]...)]
AS subquery
[WITH CHECK OPTION [CONSTRAINTconstraint
]][WITH READ ONLY]
Creating a View
-
8/4/2019 0Oracle SQL Scribe)
117/128
145
Creating a View
Create a view, EMPVU10, that containsdetails of employees in department 10.
Describe the structure of the view byusing the SQL*Plus DESCRIBE
command.SQL> DESCRIBE empvu10
SQL> CREATE VIEW empvu10
2 AS SELECT empno, ename, job
3 FROM emp
4 WHERE deptno = 10;View created.
Creating a View
-
8/4/2019 0Oracle SQL Scribe)
118/128
146
Creating a View
Create a view by using column aliasesin the subquery.
Select the columns from this view bythe given alias names.
SQL> CREATE VIEW salvu30
2 AS SELECT empno EMPLOYEE_NUMBER, ename NAME,
3 sal SALARY
4 FROM emp5 WHERE deptno = 30;
View created.
Retrieving Data from a View
-
8/4/2019 0Oracle SQL Scribe)
119/128
147
et e g ata o a e
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.
SQL> SELECT *2 FROM salvu30;
Querying a View
-
8/4/2019 0Oracle SQL Scribe)
120/128
148
Q y g
USER_VIEWS
EMPVU10SELECT empno, ename, jobFROM empWHERE deptno = 10;
SQL*Plus
SELECT *FROM empvu10;
EMP7839 KING PRESIDENT7782 CLARK MANAGER7934 MILLER CLERK
Modifying a View
-
8/4/2019 0Oracle SQL Scribe)
121/128
149
y g
Modify the EMPVU10 view by using
CREATE OR REPLACE VIEW clause. Addan alias for each column name.
Column aliases in the CREATE VIEWclause are listed in the same order as thecolumns in the subquery.
SQL> CREATE OR REPLACE VIEW empvu10
2 (employee_number, employee_name, job_title)
3 AS SELECT empno, ename, job4 FROM emp
5 WHERE deptno = 10;
View created.
Creating a Complex View
-
8/4/2019 0Oracle SQL Scribe)
122/128
150
g p
Create a complex view that contains groupfunctions to display values from two tables.
SQL> CREATE VIEW dept_sum_vu
2 (name, minsal, maxsal, avgsal)
3 AS SELECT d.dname, MIN(e.sal), MAX(e.sal),
4 AVG(e.sal)5 FROM emp e, dept d
6 WHERE e.deptno = d.deptno
7 GROUP BY d.dname;
View created.
Rules for Performing
-
8/4/2019 0Oracle SQL Scribe)
123/128
151
gDML Operations on a View
You can perform DML operations onsimple views.
You cannot remove a row if the view
contains the following: Group functions
A GROUP BY clause
The DISTINCT keyword
Rules for PerformingDML Operations on a View
-
8/4/2019 0Oracle SQL Scribe)
124/128
152
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 pseudocolumn
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
Using the WITH CHECK OPTION
-
8/4/2019 0Oracle SQL Scribe)
125/128
153
gClause
You can ensure that DML on the view stayswithin the domain of the view by using theWITH CHECK OPTION clause.
Any attempt to change the departmentnumber for any row in the view will failbecause it violates the WITH CHECK OPTIONconstraint.
SQL> CREATE OR REPLACE VIEW empvu20
2 AS SELECT *
3 FROM emp4 WHERE deptno = 20
5 WITH CHECK OPTION CONSTRAINT empvu20_ck;
View created.
Denying DML Operations
-
8/4/2019 0Oracle SQL Scribe)
126/128
154
y g p
You can ensure that no DML operationsoccur by adding the WITH READ ONLYoption to your view definition.
SQL> CREATE OR REPLACE VIEW empvu10
2 (employee_number, employee_name, job_title)
3 AS SELECT empno, ename, job4 FROM emp
5 WHERE deptno = 10
6 WITH READ ONLY;
View created.
Any attempt to perform a DML on anyrow in the view will result in OracleServer error.
Removing a View
-
8/4/2019 0Oracle SQL Scribe)
127/128
155
g
Remove a view without losing databecause a view is based on underlyingtables in the database.
SQL> DROP VIEW empvu10;
View dropped.
DROP VIEWview;
Summary
-
8/4/2019 0Oracle SQL Scribe)
128/128
y
A view is derived from data in other
tables or other views.
A view provides the followingadvantages:
Restricts database access Simplifies queries
Provides data independence
Allows multiple views of the same data Can be dropped without removing the