Upload
ihab-mortada
View
124
Download
1
Tags:
Embed Size (px)
Citation preview
2
Chapter 1. SQL : Structured Query Language
3
Creating Tables: Syntax
You must have specific privileges:CREATE TABLEA storage area
CREATE TABLE CREATE TABLE table_nametable_name
((column datatypecolumn datatype [DEFAULT [DEFAULT exprexpr]]
[[column_constraintcolumn_constraint], ],
......
[[table_constrainttable_constraint]);]);
CREATE TABLE CREATE TABLE table_nametable_name
((column datatypecolumn datatype [DEFAULT [DEFAULT exprexpr]]
[[column_constraintcolumn_constraint], ],
......
[[table_constrainttable_constraint]);]);
4
Naming Rules
Must begin with a letter
Can be 1–30 characters long
Must contain only A–Z, a–z, 0–9, _, $, and #
Must not duplicate the name of another object owned by the same user
5
Datatypes
DatatypeDatatype
VARCHAR2(VARCHAR2(sizesize))
CHAR(CHAR(sizesize))
NUMBERNUMBER
NUMBER(NUMBER(pp,,ss))
DATEDATE
LONGLONG
CharChar
NUMBER (NUMBER (pp))
DescriptionDescription
Variable length character valuesVariable length character values
Fixed length character valuesFixed length character values
Floating point numbersFloating point numbers
Number values, p digits in which s are Number values, p digits in which s are
after the pointafter the point
Date and time valuesDate and time values
Variable length character values up to Variable length character values up to
2 GB2 GB
Single characterSingle character
Integer Number of p digits at maxInteger Number of p digits at max
6
Constraint: Syntax
Column-constraint level
Table-constraint level
columncolumn [CONSTRAINT [CONSTRAINT constraint_nameconstraint_name] ] constraint_typeconstraint_type,,columncolumn [CONSTRAINT [CONSTRAINT constraint_nameconstraint_name] ] constraint_typeconstraint_type,,
column,...column,...
[CONSTRAINT constraint_name] constraint_type[CONSTRAINT constraint_name] constraint_type
(column, ...),(column, ...),
column,...column,...
[CONSTRAINT constraint_name] constraint_type[CONSTRAINT constraint_name] constraint_type
(column, ...),(column, ...),
7
The NOT NULL Constraint
Ensures that null values are not permitted for the columnIs defined at the column-constraint level
Example
CREATE TABLECREATE TABLE friend...friend...
phonephone VARCHAR2(15) NOT NULL,...VARCHAR2(15) NOT NULL,...
last_namelast_name VARCHAR2(25) VARCHAR2(25)
CONSTRAINT friend_last_name_nn NOT NULL,...CONSTRAINT friend_last_name_nn NOT NULL,...
CREATE TABLECREATE TABLE friend...friend...
phonephone VARCHAR2(15) NOT NULL,...VARCHAR2(15) NOT NULL,...
last_namelast_name VARCHAR2(25) VARCHAR2(25)
CONSTRAINT friend_last_name_nn NOT NULL,...CONSTRAINT friend_last_name_nn NOT NULL,...
8
The UNIQUE Constraint
Designates a column or combination of columns so that no two rows in the table can have the same value for this keyAllows null values if the UNIQUE key is based on a single columnIs defined at either the table or column-constraint levelAutomatically creates a UNIQUE index
... phone... phone VARCHAR2(10)VARCHAR2(10)
CONSTRAINT s_emp_phone_uk UNIQUE,...CONSTRAINT s_emp_phone_uk UNIQUE,...
... phone... phone VARCHAR2(10)VARCHAR2(10)
CONSTRAINT s_emp_phone_uk UNIQUE,...CONSTRAINT s_emp_phone_uk UNIQUE,...
9
The PRIMARY KEY Constraint
Creates a primary key for the table; only one primary key is allowed for each tableEnforces uniqueness of columnsDoes not allow null values in any part of the primary keyIs defined at either the table or column constraint levelAutomatically creates a UNIQUE index
... id... id NUMBER(7)NUMBER(7)
CONSTRAINT s_emp_id_pk PRIMARY KEY,...CONSTRAINT s_emp_id_pk PRIMARY KEY,...
... id... id NUMBER(7)NUMBER(7)
CONSTRAINT s_emp_id_pk PRIMARY KEY,...CONSTRAINT s_emp_id_pk PRIMARY KEY,...
10
The PRIMARY KEY Constraint
CREATE TABLE Sells (bar CHAR(20),goods VARCHAR2(20) DEFAULT ‘HouseBeer’,price REAL NOT NULL,
PRIMARY KEY (bar,goods) );
11
The FOREIGN KEY Constraint
Designates a column or combination of columns as a foreign keyEstablishes a relationship between the primary or unique key in the same table or between tablesIs defined at either the table or column constraint levelMust match an existing value in the parent table or be NULL
... dept_id... dept_id NUMBER(7)NUMBER(7)
CONSTRAINT s_emp_dept_id_fk CONSTRAINT s_emp_dept_id_fk
REFERENCES s_dept(id),...REFERENCES s_dept(id),...
... dept_id... dept_id NUMBER(7)NUMBER(7)
CONSTRAINT s_emp_dept_id_fk CONSTRAINT s_emp_dept_id_fk
REFERENCES s_dept(id),...REFERENCES s_dept(id),...
12
FOREIGN KEY Constraint Keywords
FOREIGN KEYDefines the column in the child table at the table constraint level
REFERENCESIdentifies the table and column in the parent table
ON DELETE CASCADEAllows deletion in the parent table and deletion of the dependent rows in the child table
13
Foreign Key Violations
Two kinds of violating:1. Insert or update a tuple so it refers to a
nonexistent reference.Always rejected.
2. Delete or update a tuple that has a value some tuples refer to. Three choices:
a) Reject: This is the default.b) Cascade: Ripple changes to referring tuple.c) Set Null: Change referring tuples to have NULL
in referring components.
Oracle allows ‘ON DELETE CASCADE or ON DELETE SET NULL’ options. But, ‘ON UPDATE’ options are not allowed.
14
Selecting a Policy
ON [DELETE, UPDATE] [CASCADE, SET NULL].
Example
CREATE TABLE Sells (bar CHAR(20),beer CHAR(20),price REAL,FOREIGN KEY beer REFERENCES Beers(name)
ON DELETE SET NULLON DELETE CASCADE);
15
Attribute-Based Checks
Follow an attribute by a condition that must hold for that attribute in each tuple of its relation.
Syntax: CHECK <condition>.Condition may involve the checked attribute.
Condition is checked only when the associated attribute changes (i.e., an insert or update occurs).
16
Attribute based Check: Example
CREATE TABLE Sells (bar CHAR(20),goods CHAR(20) ,price REAL CHECK (price <= 5.00)
);
Check occurs only when a ‘Sells’ tuple inserted or updated.
17
Tuple-Based Checks
Separate element of table declaration.Syntax: similar to attribute-based check.
Checked whenever a tuple is inserted or updated.
Example Only Joe's Bar can sell goods for more than $5.
CREATE TABLE Sells (bar CHAR(20),goods CHAR(20),price REAL,CONSTRAINT joe_bar CHECK (bar = 'Joe''s Bar' OR
price <= 5.00));
18
Create Table: Example
SQL> CREATE TABLE s_deptSQL> CREATE TABLE s_dept
2 (id 2 (id NUMBER(7)NUMBER(7)
3 CONSTRAINT s_dept_id_pk PRIMARY KEY, 3 CONSTRAINT s_dept_id_pk PRIMARY KEY,
4 name 4 name VARCHAR2(25)VARCHAR2(25)
5 CONSTRAINT s_dept_name_nn NOT NULL, 5 CONSTRAINT s_dept_name_nn NOT NULL,
6 region_id 6 region_id NUMBER(7)NUMBER(7)
7 CONSTRAINT s_dept_region_id_fk REFERENCES 7 CONSTRAINT s_dept_region_id_fk REFERENCES
8 s_region (id), 8 s_region (id),
9 CONSTRAINT s_dept_name_region_id_uk UNIQUE 9 CONSTRAINT s_dept_name_region_id_uk UNIQUE
10 (name, region_id)); 10 (name, region_id));
SQL> CREATE TABLE s_deptSQL> CREATE TABLE s_dept
2 (id 2 (id NUMBER(7)NUMBER(7)
3 CONSTRAINT s_dept_id_pk PRIMARY KEY, 3 CONSTRAINT s_dept_id_pk PRIMARY KEY,
4 name 4 name VARCHAR2(25)VARCHAR2(25)
5 CONSTRAINT s_dept_name_nn NOT NULL, 5 CONSTRAINT s_dept_name_nn NOT NULL,
6 region_id 6 region_id NUMBER(7)NUMBER(7)
7 CONSTRAINT s_dept_region_id_fk REFERENCES 7 CONSTRAINT s_dept_region_id_fk REFERENCES
8 s_region (id), 8 s_region (id),
9 CONSTRAINT s_dept_name_region_id_uk UNIQUE 9 CONSTRAINT s_dept_name_region_id_uk UNIQUE
10 (name, region_id)); 10 (name, region_id));
19
Create Table: Example
SQL> CREATE TABLE s_empSQL> CREATE TABLE s_emp
2 (id 2 (id NUMBER(7)NUMBER(7)
3 CONSTRAINT s_emp_id_pk PRIMARY KEY, 3 CONSTRAINT s_emp_id_pk PRIMARY KEY,
4 last_name 4 last_name VARCHAR2(25)VARCHAR2(25)
5 CONSTRAINT s_emp_last_name_nn NOT NULL, 5 CONSTRAINT s_emp_last_name_nn NOT NULL,
6 first_name6 first_name VARCHAR2(25),VARCHAR2(25),
7 userid 7 userid VARCHAR2(8)VARCHAR2(8)
8 CONSTRAINT s_emp_userid_nn NOT NULL 8 CONSTRAINT s_emp_userid_nn NOT NULL
9 CONSTRAINT s_emp_userid_uk UNIQUE, 9 CONSTRAINT s_emp_userid_uk UNIQUE,
10 start_date 10 start_date DATE DEFAULT SYSDATE,DATE DEFAULT SYSDATE,
11 manager_id 11 manager_id NUMBER(7),NUMBER(7),
12 dept_id 12 dept_id NUMBER(7)NUMBER(7)
13 CONSTRAINT s_emp_dept_id_fk REFERENCES 13 CONSTRAINT s_emp_dept_id_fk REFERENCES
14 s_dept (id), 14 s_dept (id),
15 commission_pct 15 commission_pct NUMBER(4,2)NUMBER(4,2)
16 CONSTRAINT s_emp_commission_pct_ck CHECK 16 CONSTRAINT s_emp_commission_pct_ck CHECK
17 (commission_pct IN(10,12.5,15,17.5,20))); 17 (commission_pct IN(10,12.5,15,17.5,20)));
SQL> CREATE TABLE s_empSQL> CREATE TABLE s_emp
2 (id 2 (id NUMBER(7)NUMBER(7)
3 CONSTRAINT s_emp_id_pk PRIMARY KEY, 3 CONSTRAINT s_emp_id_pk PRIMARY KEY,
4 last_name 4 last_name VARCHAR2(25)VARCHAR2(25)
5 CONSTRAINT s_emp_last_name_nn NOT NULL, 5 CONSTRAINT s_emp_last_name_nn NOT NULL,
6 first_name6 first_name VARCHAR2(25),VARCHAR2(25),
7 userid 7 userid VARCHAR2(8)VARCHAR2(8)
8 CONSTRAINT s_emp_userid_nn NOT NULL 8 CONSTRAINT s_emp_userid_nn NOT NULL
9 CONSTRAINT s_emp_userid_uk UNIQUE, 9 CONSTRAINT s_emp_userid_uk UNIQUE,
10 start_date 10 start_date DATE DEFAULT SYSDATE,DATE DEFAULT SYSDATE,
11 manager_id 11 manager_id NUMBER(7),NUMBER(7),
12 dept_id 12 dept_id NUMBER(7)NUMBER(7)
13 CONSTRAINT s_emp_dept_id_fk REFERENCES 13 CONSTRAINT s_emp_dept_id_fk REFERENCES
14 s_dept (id), 14 s_dept (id),
15 commission_pct 15 commission_pct NUMBER(4,2)NUMBER(4,2)
16 CONSTRAINT s_emp_commission_pct_ck CHECK 16 CONSTRAINT s_emp_commission_pct_ck CHECK
17 (commission_pct IN(10,12.5,15,17.5,20))); 17 (commission_pct IN(10,12.5,15,17.5,20)));
Creating a Table by Using a SubQuery
Create a table and insert rows by combining the CREATE TABLE statement and AS subquery option.
Match the number of specified columns to the number of subquery columns.
Define columns with column names anddefault values.
CREATE TABLE tableCREATE TABLE table
[([(column, columncolumn, column...)]...)]
AS subquery;AS subquery;
CREATE TABLE tableCREATE TABLE table
[([(column, columncolumn, column...)]...)]
AS subquery;AS subquery;
Name Null? Type ---------------------------- -------- ----- EMPNO NOT NULL NUMBER(4) ENAME VARCHAR2(10) ANNSAL NUMBER HIREDATE DATE
Name Null? Type ---------------------------- -------- ----- EMPNO NOT NULL NUMBER(4) ENAME VARCHAR2(10) ANNSAL NUMBER HIREDATE DATE
SQL> DESCRIBE dept30SQL> DESCRIBE dept30SQL> DESCRIBE dept30SQL> DESCRIBE dept30
SQL> CREATE TABLE SQL> CREATE TABLE dept30dept30
22 AS AS
33 SELECTSELECT empno, ename, sal empno, ename, sal**12 AS ANNSAL, 12 AS ANNSAL,
hiredatehiredate
44 FROMFROM emp emp
55 WHEREWHERE deptno deptno = = 30;30;
Table createdTable created..
SQL> CREATE TABLE SQL> CREATE TABLE dept30dept30
22 AS AS
33 SELECTSELECT empno, ename, sal empno, ename, sal**12 AS ANNSAL, 12 AS ANNSAL,
hiredatehiredate
44 FROMFROM emp emp
55 WHEREWHERE deptno deptno = = 30;30;
Table createdTable created..
Creating a Table by using a Subquery
ALTER TABLE tableALTER TABLE table
ADDADD ( (column datatype column datatype [[DEFAULT exprDEFAULT expr]]
[[, column datatype, column datatype]...)]...);;
ALTER TABLE tableALTER TABLE table
ADDADD ( (column datatype column datatype [[DEFAULT exprDEFAULT expr]]
[[, column datatype, column datatype]...)]...);;
ALTER TABLE tableALTER TABLE table
MODIFYMODIFY ( (column datatype column datatype [[DEFAULT exprDEFAULT expr]]
[[, column datatype, column datatype]...)]...);;
ALTER TABLE tableALTER TABLE table
MODIFYMODIFY ( (column datatype column datatype [[DEFAULT exprDEFAULT expr]]
[[, column datatype, column datatype]...)]...);;
Use the ALTER TABLE statement to:Add a new columnModify an existing columnDefine a default value for the new columnDrop a Column
The ALTER TABLE Statement
23
Altering Tables
Add a new column.Define a default value for the new column.Specify that the column must contain a value.
ALTER TABLE ALTER TABLE tabletable
ADDADD ((column datatype column datatype [DEFAULT [DEFAULT exprexpr][NOT NULL]][NOT NULL]
[, [, column datatypecolumn datatype]...);]...);
ALTER TABLE ALTER TABLE tabletable
ADDADD ((column datatype column datatype [DEFAULT [DEFAULT exprexpr][NOT NULL]][NOT NULL]
[, [, column datatypecolumn datatype]...);]...);
24
Adding a Column: Example
Add a COMMENTS column to the S_REGION table.
The new column becomes the last column.
SQL> ALTER TABLESQL> ALTER TABLE s_regions_region
2 ADD2 ADD (comments VARCHAR2(255));(comments VARCHAR2(255));
Table altered.Table altered.
SQL> ALTER TABLESQL> ALTER TABLE s_regions_region
2 ADD2 ADD (comments VARCHAR2(255));(comments VARCHAR2(255));
Table altered.Table altered.
25
Modifying a Column: Syntax
Change a column's datatype, size, default value, and NOT NULL column constraint.
ALTER TABLEALTER TABLE tabletableMODIFYMODIFY ((column datatype column datatype [DEFAULT [DEFAULT exprexpr][NOT NULL]][NOT NULL]
[, [, column datatypecolumn datatype]...);]...);
ALTER TABLEALTER TABLE tabletableMODIFYMODIFY ((column datatype column datatype [DEFAULT [DEFAULT exprexpr][NOT NULL]][NOT NULL]
[, [, column datatypecolumn datatype]...);]...);
26
Modifying a Column
Change the data type if the column contains null values.Change the default value to affect only subsequent insertions into the table.
ExampleExtend the maximum length of the TITLE column in the S_EMP table to 50 characters.
SQL> ALTER TABLESQL> ALTER TABLE s_emps_emp
2 MODIFY 2 MODIFY (title VARCHAR2(50));(title VARCHAR2(50));
Table altered.Table altered.
SQL> ALTER TABLESQL> ALTER TABLE s_emps_emp
2 MODIFY 2 MODIFY (title VARCHAR2(50));(title VARCHAR2(50));
Table altered.Table altered.
27
Adding a Constraint: Example
Add a foreign key constraint to the S_EMP table indicating that a manager must already exist as a valid employee in the S_EMP table.
SQL> ALTER TABLESQL> ALTER TABLE s_emps_emp
ADD CONSTRAINTADD CONSTRAINT s_emp_manager_id_fks_emp_manager_id_fk
FOREIGN KEY (manager_id)FOREIGN KEY (manager_id)
REFERENCES REFERENCES s_emp(id);s_emp(id);
Table altered.Table altered.
SQL> ALTER TABLESQL> ALTER TABLE s_emps_emp
ADD CONSTRAINTADD CONSTRAINT s_emp_manager_id_fks_emp_manager_id_fk
FOREIGN KEY (manager_id)FOREIGN KEY (manager_id)
REFERENCES REFERENCES s_emp(id);s_emp(id);
Table altered.Table altered.
SQL> DROP TABLE dept30;SQL> DROP TABLE dept30;
Table droppedTable dropped..
SQL> DROP TABLE dept30;SQL> DROP TABLE dept30;
Table droppedTable dropped..
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> RENAME dept TO department;SQL> RENAME dept TO department;
Table renamedTable renamed..
SQL> RENAME dept TO department;SQL> RENAME dept TO department;
Table renamedTable renamed..
Changing the Name of an Object
To change the name of a table, view, sequence…
Execute the RENAME statement
You must be the owner of the object
SQL> TRUNCATE TABLE department;SQL> TRUNCATE TABLE department;
Table truncatedTable truncated..
SQL> TRUNCATE TABLE department;SQL> TRUNCATE TABLE department;
Table truncatedTable truncated..
Truncating a Table
The TRUNCATE TABLE Statement:Removes all rows from a tableReleases the storage space used by that table
You cannot roll back row removal when using TRUNCATE.
Alternatively, you can remove rows by using the DELETE statement.
You can add comments to a table or column by using the COMMENT statement.
Comments can be viewed through the data dictionary views.ALL_TAB_COMMENTSUSER_TAB_COMMENTS
Adding Comments to a Table
SQL> COMMENT ON TABLE emp SQL> COMMENT ON TABLE emp
2 IS 'Employee Information';2 IS 'Employee Information';
Comment createdComment created..
SQL> COMMENT ON TABLE emp SQL> COMMENT ON TABLE emp
2 IS 'Employee Information';2 IS 'Employee Information';
Comment createdComment created..
32
Inserting Rows into a Table: Syntax
Add new rows to a table by using the INSERT command.
Only one row is inserted at a time with this syntax.
INSERT INTOINSERT INTO tabletable [( [(columncolumn [, [, columncolumn...])]...])]
VALUESVALUES ((valuevalue [, [, valuevalue...]);...]);
INSERT INTOINSERT INTO tabletable [( [(columncolumn [, [, columncolumn...])]...])]
VALUESVALUES ((valuevalue [, [, valuevalue...]);...]);
33
Inserting Rows: Example
Insert a new row containing values for each column.Optionally list the columns in the INSERT clause.
List values in the default order of the columns in the table.
Enclose character and date values within single quotation marks.
SQL> INSERT INTOSQL> INSERT INTO s_depts_dept
2 VALUES2 VALUES (11, 'Finance', 2);(11, 'Finance', 2);
1 row created.1 row created.
SQL> INSERT INTOSQL> INSERT INTO s_depts_dept
2 VALUES2 VALUES (11, 'Finance', 2);(11, 'Finance', 2);
1 row created.1 row created.
SQL> INSERT INTO managersSQL> INSERT INTO managers((id, name, salary, hiredateid, name, salary, hiredate))
22 SELECTSELECT empno, ename, sal, hiredateempno, ename, sal, hiredate
33 FROM empFROM emp
44 WHEREWHERE job job = = 'MANAGER';'MANAGER';
3 rows created3 rows created..
SQL> INSERT INTO managersSQL> INSERT INTO managers((id, name, salary, hiredateid, name, salary, hiredate))
22 SELECTSELECT empno, ename, sal, hiredateempno, ename, sal, hiredate
33 FROM empFROM emp
44 WHEREWHERE job job = = 'MANAGER';'MANAGER';
3 rows created3 rows created..
Write your INSERT statement with a subquery.
Do not use the VALUES clause.Match the number of columns in the INSERT clause to those in the subquery.
Copying Rows from another Table
35
Sequential lists of numbers to create unique surrogate key values
To use a sequence:SELECT sequence_name.NEXTVAL FROM DUAL;
INSERT INTO location (LOC_ID) VALUES(loc_id_sequence.NEXTVAL);
Loc_id_sequence.currval: Current Value
Sequences
36
The Basic Query Block
SELECT identifies what columns
FROM identifies which table
SELECTSELECT [DISTINCT][DISTINCT] {*,column [alias],....}{*,column [alias],....}
FROMFROM table;table;
SELECTSELECT [DISTINCT][DISTINCT] {*,column [alias],....}{*,column [alias],....}
FROMFROM table;table;
37
Selecting All Columns, All Rows
Simplest SELECT statement contains the followingtwo clauses:
SELECT clauseAsterisk (*) indicates all columns
FROM clause
SQL> SELECT SQL> SELECT ** 2 FROM 2 FROM s_dept;s_dept;
SQL> SELECT SQL> SELECT ** 2 FROM 2 FROM s_dept;s_dept;
38
Selecting All Columns, All Rows
SQL> SELECT SQL> SELECT ** 2 FROM 2 FROM s_dept;s_dept;
SQL> SELECT SQL> SELECT ** 2 FROM 2 FROM s_dept;s_dept;
IDID NAMENAME REGION_IDREGION_ID---------------- -------------------------- --------------------
1010 FinanceFinance 113131 SalesSales 113232 SalesSales 223333 SalesSales 333434 SalesSales 443535 SalesSales 554141 OperationsOperations 114242 OperationsOperations 224343 OperationsOperations 334444 OperationsOperations 444545 OperationsOperations 555050 AdministrationAdministration 11
12 rows selected.12 rows selected.
IDID NAMENAME REGION_IDREGION_ID---------------- -------------------------- --------------------
1010 FinanceFinance 113131 SalesSales 113232 SalesSales 223333 SalesSales 333434 SalesSales 443535 SalesSales 554141 OperationsOperations 114242 OperationsOperations 224343 OperationsOperations 334444 OperationsOperations 444545 OperationsOperations 555050 AdministrationAdministration 11
12 rows selected.12 rows selected.
39
Selecting Specific Columns
List the columns in the SELECT clause.Separate columns by using a comma.Specify columns in the order you want them to appear.
SQL> SELECTSQL> SELECT dept_id, last_name, manager_iddept_id, last_name, manager_id 2 FROM2 FROM s_emp;s_emp;
SQL> SELECTSQL> SELECT dept_id, last_name, manager_iddept_id, last_name, manager_id 2 FROM2 FROM s_emp;s_emp;
40
Arithmetic Expressions
Create expressions on NUMBER and DATE datatypes by using operators.
Add +Subtract -Multiply *Divide /
41
Display the annual salary for all employees.
Arithmetic Expressions
SQL> SELECTSQL> SELECT last_name, salary * 12, commission_pctlast_name, salary * 12, commission_pct 2 FROM2 FROM s_emp;s_emp;
SQL> SELECTSQL> SELECT last_name, salary * 12, commission_pctlast_name, salary * 12, commission_pct 2 FROM2 FROM s_emp;s_emp;
LAST_NAMELAST_NAME SALARY*12SALARY*12 COMMISSION_PCTCOMMISSION_PCT------------------------ ------------------------ ----------------------------......HavelHavel 15684 15684MageeMagee 1680016800 1010GiljumGiljum 1788017880 12.512.5SedeghiSedeghi 1818018180 1010NguyenNguyen 1830018300 1515DumasDumas 1740017400 17.517.5MaduroMaduro 1680016800......
LAST_NAMELAST_NAME SALARY*12SALARY*12 COMMISSION_PCTCOMMISSION_PCT------------------------ ------------------------ ----------------------------......HavelHavel 15684 15684MageeMagee 1680016800 1010GiljumGiljum 1788017880 12.512.5SedeghiSedeghi 1818018180 1010NguyenNguyen 1830018300 1515DumasDumas 1740017400 17.517.5MaduroMaduro 1680016800......
42
Column Aliases
A column alias renames a column heading.
Especially useful with calculations
Immediately follows column nameOptional AS keyword between column name and alias
Double quotation marks are required if an alias contains spaces, special characters, or is case-sensitive.
SQL> SELECT ename SQL> SELECT ename ""NameName"",,
2 sal2 sal**1212 " "Annual SalaryAnnual Salary""
3 FROM emp;3 FROM emp;
SQL> SELECT ename SQL> SELECT ename ""NameName"",,
2 sal2 sal**1212 " "Annual SalaryAnnual Salary""
3 FROM emp;3 FROM emp;
SQL> SELECT ename AS name, sal AS salarySQL> SELECT ename AS name, sal AS salary
2 FROM emp;2 FROM emp;
SQL> SELECT ename AS name, sal AS salarySQL> SELECT ename AS name, sal AS salary
2 FROM emp;2 FROM emp;
NAME SALARY
------------- ---------
...
Name Annual Salary
------------- -------------
...
Using Column Aliases
44
Literal Character String
A literal is a character, expression, or number included in the SELECT list.
Date and character literal values must be enclosed within single quotation marks.
45
Concatenation Operator
The concatenation operatorIs represented by two vertical bars (||).(MS Access: & operator)
Links columns or character strings to other columns.
Creates a resultant column that is a character expression.
46
Concatenation Operator: Example
EmployeesEmployees----------------------------------------------------------------------------------------Carmen Velasquez, PresidentCarmen Velasquez, PresidentLaDoris Ngao, VP, OperationsLaDoris Ngao, VP, OperationsMidori Nagayama, VP, SalesMidori Nagayama, VP, SalesMark Quick-To-See, VP, FinanceMark Quick-To-See, VP, FinanceAudry Ropeburn, VP, AdministrationAudry Ropeburn, VP, AdministrationMolly Urguhart, Warehouse ManagerMolly Urguhart, Warehouse Manager......
EmployeesEmployees----------------------------------------------------------------------------------------Carmen Velasquez, PresidentCarmen Velasquez, PresidentLaDoris Ngao, VP, OperationsLaDoris Ngao, VP, OperationsMidori Nagayama, VP, SalesMidori Nagayama, VP, SalesMark Quick-To-See, VP, FinanceMark Quick-To-See, VP, FinanceAudry Ropeburn, VP, AdministrationAudry Ropeburn, VP, AdministrationMolly Urguhart, Warehouse ManagerMolly Urguhart, Warehouse Manager......
SQL> SELECTSQL> SELECT first_name ||' '|| last_namefirst_name ||' '|| last_name 22 ||', '|| title "Employees"||', '|| title "Employees" 3 FROM 3 FROM s_emp;s_emp;
SQL> SELECTSQL> SELECT first_name ||' '|| last_namefirst_name ||' '|| last_name 22 ||', '|| title "Employees"||', '|| title "Employees" 3 FROM 3 FROM s_emp;s_emp;
47
Managing Null Values in expressions
NULL is a value that is unavailable, unassigned, unknown, or inapplicable.
NULL is not the same as zero or space.
Arithmetic expressions containing a null value evaluate to NULL.
SQL> SELECTSQL> SELECT last_name, title,last_name, title, 22 salary*commission_pct/100 COMMsalary*commission_pct/100 COMM 3 FROM 3 FROM s_emp;s_emp;
SQL> SELECTSQL> SELECT last_name, title,last_name, title, 22 salary*commission_pct/100 COMMsalary*commission_pct/100 COMM 3 FROM 3 FROM s_emp;s_emp;
48
NVL Function
Convert NULL to an actual value with NVL.Datatypes to use are date, character, and number.Datatypes must match.
NVL (start_date, '01-JAN-95')NVL (title, 'No Title Yet')NVL (salary, 1000)
SQL> SELECTSQL> SELECT last_name, title,last_name, title, 22 salary*NVL(commission_pct,0)/100 COMMsalary*NVL(commission_pct,0)/100 COMM 3 FROM 3 FROM s_emp;s_emp;
SQL> SELECTSQL> SELECT last_name, title,last_name, title, 22 salary*NVL(commission_pct,0)/100 COMMsalary*NVL(commission_pct,0)/100 COMM 3 FROM 3 FROM s_emp;s_emp;
49
Duplicate Rows
The default display of queries is all rows including duplicate rows.
Eliminate duplicate rows by using DISTINCT in the SELECT clause.
SQL> SELECTSQL> SELECT DISTINCT nameDISTINCT name 2 FROM 2 FROM s_dept;s_dept;
SQL> SELECTSQL> SELECT DISTINCT nameDISTINCT name 2 FROM 2 FROM s_dept;s_dept;
SQL> SELECTSQL> SELECT namename 2 FROM 2 FROM s_dept;s_dept;
SQL> SELECTSQL> SELECT namename 2 FROM 2 FROM s_dept;s_dept;
50
DISTINCT with Multiple Columns
DISTINCT applies to all columns in the SELECT list.
When DISTINCT is applied to multiple columns, the result represents the distinct combination of the columns.
SQL> SELECT DISTINCT dept_id, titleSQL> SELECT DISTINCT dept_id, title 2 FROM 2 FROM s_emp;s_emp;SQL> SELECT DISTINCT dept_id, titleSQL> SELECT DISTINCT dept_id, title 2 FROM 2 FROM s_emp;s_emp;
51
The ORDER BY Clause
Sort rows with the ORDER BY clause.ASC – ascending order, default.DESC – descending order.ORDER BY clause is last in SELECT command.
SQL> SELECTSQL> SELECT last_name, dept_id, start_date last_name, dept_id, start_date 2 FROM 2 FROM s_emp s_emp 3 ORDER BY3 ORDER BY last_name; last_name;
SQL> SELECTSQL> SELECT last_name, dept_id, start_date last_name, dept_id, start_date 2 FROM 2 FROM s_emp s_emp 3 ORDER BY3 ORDER BY last_name; last_name;
52
The ORDER BY Clause
The default sort order is ascending.The sort order can be reversed by using DESC.You can sort by expressions or aliases.
Null values are displayedLast for ascending sequences.First for descending sequences.
SQL> SELECTSQL> SELECT last_name EMPLOYEE, start_date last_name EMPLOYEE, start_date 2 FROM 2 FROM s_emp s_emp 3 ORDER BY3 ORDER BY EMPLOYEE DESC; EMPLOYEE DESC;
SQL> SELECTSQL> SELECT last_name EMPLOYEE, start_date last_name EMPLOYEE, start_date 2 FROM 2 FROM s_emp s_emp 3 ORDER BY3 ORDER BY EMPLOYEE DESC; EMPLOYEE DESC;
53
Sorting by Multiple Columns
You can order by position to save time.
SQL> SELECTSQL> SELECT last_name, dept_id, salarylast_name, dept_id, salary 2 FROM 2 FROM s_emps_emp 3 ORDER BY3 ORDER BY dept_id, salary DESC;dept_id, salary DESC;
SQL> SELECTSQL> SELECT last_name, dept_id, salarylast_name, dept_id, salary 2 FROM 2 FROM s_emps_emp 3 ORDER BY3 ORDER BY dept_id, salary DESC;dept_id, salary DESC;
SQL> SELECTSQL> SELECT last_name, salary * 12 last_name, salary * 12 2 FROM 2 FROM s_emp s_emp 3 ORDER BY3 ORDER BY 2; 2;
SQL> SELECTSQL> SELECT last_name, salary * 12 last_name, salary * 12 2 FROM 2 FROM s_emp s_emp 3 ORDER BY3 ORDER BY 2; 2;
You can sort by multiple columns
The order of ORDER BY list is order of sort.
You can sort by a column that is not in the SELECT list.
54
SQL : Structured Query Language
Limiting Selected Rows
55
Limiting Rows Selected
Restrict the rows returned by using the WHERE
clause.The WHERE clause follows the FROM clause.Conditions consist of the following:
Column name, expression, constantComparison operatorLiteralSQL> SELECTSQL> SELECT last_name, dept_id, salarylast_name, dept_id, salary
2 FROM 2 FROM s_emps_emp 3 WHERE3 WHERE dept_id = 42;dept_id = 42;
SQL> SELECTSQL> SELECT last_name, dept_id, salarylast_name, dept_id, salary 2 FROM 2 FROM s_emps_emp 3 WHERE3 WHERE dept_id = 42;dept_id = 42;
56
Character Strings and Dates
Character strings and dates are enclosed within single quotation marks.Number values are not enclosed within quotation marks.Character values are case-sensitive.
SQL> SELECTSQL> SELECT first_name, last_name, titlefirst_name, last_name, title 2 FROM 2 FROM s_emps_emp 3 WHERE3 WHERE last_name = 'Magee';last_name = 'Magee';
SQL> SELECTSQL> SELECT first_name, last_name, titlefirst_name, last_name, title 2 FROM 2 FROM s_emps_emp 3 WHERE3 WHERE last_name = 'Magee';last_name = 'Magee';
57
Comparison and Logical Operators
Logical comparison operators= > >= < <=
SQL comparison operatorsBETWEEN ... AND...IN(list)LIKEIS NULL
Logical operatorsANDORNOT
58
Negating Expressions
Sometimes it is easier to exclude rows you know you do not want.Logical Operators
!= <> ^=
SQL OperatorsNOT BETWEENNOT INNOT LIKEIS NOT NULL
59
BETWEEN and IN SQL Operators
Use the BETWEEN operator to test for values between, and inclusive of, a range of values.
SQL> SELECTSQL> SELECT id, name, region_idid, name, region_id 2 FROM 2 FROM s_depts_dept 3 WHERE3 WHERE region_id IN (1,3);region_id IN (1,3);
SQL> SELECTSQL> SELECT id, name, region_idid, name, region_id 2 FROM 2 FROM s_depts_dept 3 WHERE3 WHERE region_id IN (1,3);region_id IN (1,3);
SQL> SELECTSQL> SELECT first_name, last_name, start_datefirst_name, last_name, start_date 2 FROM 2 FROM s_emps_emp 3 WHERE3 WHERE start_date BETWEEN '09-may-91'start_date BETWEEN '09-may-91' 4 4 AND '17-jun-91';AND '17-jun-91';
SQL> SELECTSQL> SELECT first_name, last_name, start_datefirst_name, last_name, start_date 2 FROM 2 FROM s_emps_emp 3 WHERE3 WHERE start_date BETWEEN '09-may-91'start_date BETWEEN '09-may-91' 4 4 AND '17-jun-91';AND '17-jun-91';
• Use IN to test for values in a list.Use IN to test for values in a list.
Use IN to test for values in a list.
60
LIKE SQL Operator
You can use the LIKE operator to perform wildcard searches of valid search string values.
Search conditions can contain either literal characters or numbers.
"%" denotes none or many characters."_" denotes one character.
SQL> SELECTSQL> SELECT last_namelast_name 2 FROM 2 FROM s_emps_emp 3 WHERE3 WHERE last_name LIKE 'M%';last_name LIKE 'M%';
SQL> SELECTSQL> SELECT last_namelast_name 2 FROM 2 FROM s_emps_emp 3 WHERE3 WHERE last_name LIKE 'M%';last_name LIKE 'M%';
61
LIKE SQL Operator
The LIKE operator can be used as a shortcut for some BETWEEN comparisons.
You can combine pattern matching characters.SQL> SELECTSQL> SELECT last_namelast_name 2 FROM 2 FROM s_emps_emp 3 WHERE3 WHERE last_name LIKE '_a%';last_name LIKE '_a%';
SQL> SELECTSQL> SELECT last_namelast_name 2 FROM 2 FROM s_emps_emp 3 WHERE3 WHERE last_name LIKE '_a%';last_name LIKE '_a%';
SQL> SELECTSQL> SELECT last_name, start_datelast_name, start_date 2 FROM 2 FROM s_emps_emp 3 WHERE3 WHERE start_date LIKE '%91';start_date LIKE '%91';
SQL> SELECTSQL> SELECT last_name, start_datelast_name, start_date 2 FROM 2 FROM s_emps_emp 3 WHERE3 WHERE start_date LIKE '%91';start_date LIKE '%91';
62
IS NULL SQL Operator
Test for null values with the IS NULL operator.Do not use the = operator.SQL> SELECTSQL> SELECT id, name, credit_ratingid, name, credit_rating 2 FROM 2 FROM s_customers_customer 3 WHERE3 WHERE sales_rep_id IS NULL;sales_rep_id IS NULL;
SQL> SELECTSQL> SELECT id, name, credit_ratingid, name, credit_rating 2 FROM 2 FROM s_customers_customer 3 WHERE3 WHERE sales_rep_id IS NULL;sales_rep_id IS NULL;
63
Multiple Conditions
Use complex criteria.Combine conditions with AND or OR operators.AND requires both conditions to be TRUE.
• OR requires either condition to be TRUE.OR requires either condition to be TRUE.
SQL> SELECTSQL> SELECT last_name, salary, dept_id, titlelast_name, salary, dept_id, title 2 FROM 2 FROM s_emps_emp 3 WHERE3 WHERE dept_id = 41dept_id = 41 4 AND4 AND title = 'Stock Clerk';title = 'Stock Clerk';
SQL> SELECTSQL> SELECT last_name, salary, dept_id, titlelast_name, salary, dept_id, title 2 FROM 2 FROM s_emps_emp 3 WHERE3 WHERE dept_id = 41dept_id = 41 4 AND4 AND title = 'Stock Clerk';title = 'Stock Clerk';
SQL> SELECTSQL> SELECT last_name, salary, dept_id, titlelast_name, salary, dept_id, title 2 FROM 2 FROM s_emps_emp 3 WHERE3 WHERE dept_id = 41dept_id = 41 4 OR4 OR title = 'Stock Clerk';title = 'Stock Clerk';
SQL> SELECTSQL> SELECT last_name, salary, dept_id, titlelast_name, salary, dept_id, title 2 FROM 2 FROM s_emps_emp 3 WHERE3 WHERE dept_id = 41dept_id = 41 4 OR4 OR title = 'Stock Clerk';title = 'Stock Clerk';
64
Rules of Precedence
Order Evaluated Operator1 All comparison
operators.2 AND3 OR
Override rules of precedence by using Override rules of precedence by using parentheses.parentheses.
65
Display information for those employees in department 44 who earn 1000 or more, and any employees in department 42.
SQL> SELECTSQL> SELECT last_name, salary, dept_idlast_name, salary, dept_id 2 FROM 2 FROM s_emps_emp 3 WHERE3 WHERE salary >= 1000salary >= 1000 4 AND4 AND dept_id = 44dept_id = 44 5 OR5 OR dept_id = 42;dept_id = 42;
SQL> SELECTSQL> SELECT last_name, salary, dept_idlast_name, salary, dept_id 2 FROM 2 FROM s_emps_emp 3 WHERE3 WHERE salary >= 1000salary >= 1000 4 AND4 AND dept_id = 44dept_id = 44 5 OR5 OR dept_id = 42;dept_id = 42;
Rules of Precedence: Examples
SQL> SELECTSQL> SELECT last_name, salary, dept_idlast_name, salary, dept_id 2 FROM 2 FROM s_emps_emp 3 WHERE3 WHERE salary >= 1000salary >= 1000 4 AND4 AND (dept_id = 44(dept_id = 44 5 OR5 OR dept_id = 42);dept_id = 42);
SQL> SELECTSQL> SELECT last_name, salary, dept_idlast_name, salary, dept_id 2 FROM 2 FROM s_emps_emp 3 WHERE3 WHERE salary >= 1000salary >= 1000 4 AND4 AND (dept_id = 44(dept_id = 44 5 OR5 OR dept_id = 42);dept_id = 42);
Display information for those employees in department 44 or 42 who earn 1000 or more.
66
Summary – Selecting Rows
SELECTSELECT [DISTINCT] {*, [DISTINCT] {*, column column [[aliasalias], ...}], ...}FROM FROM tabletable[WHERE[WHERE condition(s)condition(s)]][ORDER BY[ORDER BY {{column, expr, aliascolumn, expr, alias} [ASC|DESC]];} [ASC|DESC]];
SELECTSELECT [DISTINCT] {*, [DISTINCT] {*, column column [[aliasalias], ...}], ...}FROM FROM tabletable[WHERE[WHERE condition(s)condition(s)]][ORDER BY[ORDER BY {{column, expr, aliascolumn, expr, alias} [ASC|DESC]];} [ASC|DESC]];
67
68
Single Row Functions
69
Overview of Functions in SQL
Use functions toPerform calculations on data.Modify individual data items.Manipulate output for groups of rows.Alter date formats for display.Convert column data types.
70
Two Types of SQL Functions
Single row functionsCharacterNumberDateConversion
Multiple row functionsGroup
SINGLESINGLEROWROW
MULTIMULTIROWROW
FUNCTIONFUNCTION
71
Single Row Functions: Syntax
Single row functionsManipulate data items.Accept arguments and return one value.Act on each row returned.Return one result per row.Modify the datatype.Can be nested.
Syntax
function_name function_name ((columncolumn||expressionexpression, [, [arg1, arg2,...arg1, arg2,...])])function_name function_name ((columncolumn||expressionexpression, [, [arg1, arg2,...arg1, arg2,...])])
72
Character Functions
LOWER Converts to lowercaseUPPER Converts to uppercaseINITCAP Converts to initial capitalizationCONCAT Concatenates valuesSUBSTR Returns substringLENGTH Returns number of characters
73
Character Manipulation Functions
Manipulate character strings
CONCAT('Good', 'String') GoodStringSUBSTR('String',1,5) StrinSUBSTR('String',3) ringLENGTH('String') 6
74
Number Functions
ROUND Rounds value to specified decimalTRUNC Truncates value to specified decimalMOD Returns remainder of divisionPOWER Returns the power
75
ROUND and TRUNC Functions
ROUND (45.923, 2) 45.92ROUND (45.923, 0) 46ROUND (45.923, -1) 50TRUNC (45.923, 2) 45.92TRUNC (45.923) 45TRUNC (45.923, -1) 40
76
Oracle Date Format
Oracle stores dates in an internal numeric format.
Century, year, month, day, hours, minutes, seconds
Default date display is DD-MON-YY.
SYSDATE is a function returning date and time.
DUAL is a dummy table used to view SYSDATE.
77
Arithmetic Operators with Dates
Add or subtract a number to or from a date for a resultant date value.
Subtract two dates to find the number of days between those dates.
Add hours to a date by dividing the number of hours by 24.
78
Date Functions
MONTHS_BETWEEN Number of monthsbetween two dates
ADD_MONTHS Add calendar months
to dateNEXT_DAY Next day of the date
specifiedLAST_DAY Last day of the month
79
Date Functions
MONTHS_BETWEEN(to_date(’01-JAN-2003’, ’DD-MON-YYYY’),to_date(’14-Mar-2003’, ’DD-MON-YYYY’))
-2.429354838ADD_MONTHS('11-JAN-94',6)
'11-JUL-94'NEXT_DAY('01-SEP-95','FRIDAY')
'08-SEP-95'
LAST_DAY('01-SEP-95')'30-SEP-
95'
80
Conversion Functions: Overview
TO_CHAR converts a number or date string to a character string.
TO_NUMBER converts a character string containing digits to a number.
TO_DATE converts a character string of a date to a date value.
Conversion functions can use a format model composed of many elements.
81
Summary
Single row functions can be nested to any level.Single row functions work on character, number, and date data.Conversion functions are TO_CHAR, TO_DATE, and TO_NUMBER.SYSDATE is a pseudo-column used to return current date and time.DUAL is a dummy table in the database.
82
Group Functions
83
Group Functions
Group functions operate on sets of rows to give one result per group.Group functions appear in both SELECT lists and HAVING clauses.The GROUP BY clause in the SELECT statement divides rows into smaller groups.The HAVING clause restricts result groups.
84
GROUP BY and HAVING Clauses in the SELECT Statement: Syntax
GROUP BY divides rows into smaller groups.HAVING further restricts the result groups.
SELECTSELECT columncolumn, , group_functiongroup_function
FROMFROM tabletable
[WHERE[WHERE conditioncondition]]
[GROUP BY[GROUP BY group_by_expressiongroup_by_expression]]
[HAVING[HAVING group_conditiongroup_condition]]
[ORDER BY[ORDER BY columncolumn];];
SELECTSELECT columncolumn, , group_functiongroup_function
FROMFROM tabletable
[WHERE[WHERE conditioncondition]]
[GROUP BY[GROUP BY group_by_expressiongroup_by_expression]]
[HAVING[HAVING group_conditiongroup_condition]]
[ORDER BY[ORDER BY columncolumn];];
85
Group Functions
AVG (DISTINCT|ALL|n)COUNT (DISTINCT|ALL|expr|*)MAX (DISTINCT|ALL|expr)MIN (DISTINCT|ALL|expr)SUM (DISTINCT|ALL|n)
86
Group Functions: Example
You can use MAX and MIN for any datatype.
SQL> SELECTSQL> SELECT MIN(last_name), MAX(last_name)MIN(last_name), MAX(last_name)
2 FROM2 FROM s_emps_emp;;
SQL> SELECTSQL> SELECT MIN(last_name), MAX(last_name)MIN(last_name), MAX(last_name)
2 FROM2 FROM s_emps_emp;;
SQL> SELECTSQL> SELECT AVG(salary), MAX(salary),AVG(salary), MAX(salary),
22 MIN(salary), SUM(salary)MIN(salary), SUM(salary)
3 FROM3 FROM s_emps_emp
4 WHERE4 WHERE UPPER(title) LIKE 'SALES%';UPPER(title) LIKE 'SALES%';
SQL> SELECTSQL> SELECT AVG(salary), MAX(salary),AVG(salary), MAX(salary),
22 MIN(salary), SUM(salary)MIN(salary), SUM(salary)
3 FROM3 FROM s_emps_emp
4 WHERE4 WHERE UPPER(title) LIKE 'SALES%';UPPER(title) LIKE 'SALES%';
You can use AVG and SUM against columns that can store numeric data.
87
The GROUP BY Clause: Syntax
Divide rows in a table into smaller groups by using the GROUP BY clause.Include the column list in the GROUP BY clause if columns are used in the SELECT clause.Override the default sort order by using the ORDER BY clause.
SELECTSELECT columncolumn, , group_functiongroup_function
FROMFROM tabletable
[WHERE[WHERE conditioncondition]]
[GROUP BY[GROUP BY group_by_expressiongroup_by_expression]]
[ORDER BY[ORDER BY columncolumn];];
SELECTSELECT columncolumn, , group_functiongroup_function
FROMFROM tabletable
[WHERE[WHERE conditioncondition]]
[GROUP BY[GROUP BY group_by_expressiongroup_by_expression]]
[ORDER BY[ORDER BY columncolumn];];
88
The GROUP BY Clause: Example
The GROUP BY clause The GROUP BY clause displays one line of data displays one line of data for each department for each department retrieved in the WHERE retrieved in the WHERE clause, and COUNT(*) clause, and COUNT(*) displays the number of displays the number of employees in each employees in each department (group) department (group) displayed.displayed.
SQL> SELECTSQL> SELECT dept_id, COUNT(*) ”Number” dept_id, COUNT(*) ”Number”
2 FROM 2 FROM s_emps_emp
3 WHERE 3 WHERE dept_id = 41dept_id = 41
4 GROUP BY 4 GROUP BY dept_id;dept_id;
SQL> SELECTSQL> SELECT dept_id, COUNT(*) ”Number” dept_id, COUNT(*) ”Number”
2 FROM 2 FROM s_emps_emp
3 WHERE 3 WHERE dept_id = 41dept_id = 41
4 GROUP BY 4 GROUP BY dept_id;dept_id;
DEPT_ID Number DEPT_ID Number
------- ------------- ------
41 4 41 4
DEPT_ID Number DEPT_ID Number
------- ------------- ------
41 4 41 4
89
The GROUP BY Clause: Example
All columns in the SELECT list that are not in group functions must be in the GROUP BY clause.The GROUP BY column does not have to be in the SELECT clause.The results are more meaningful if the GROUP BY column is in the SELECT clause.
SQL> SELECTSQL> SELECT title, MAX(salary)title, MAX(salary)
2 FROM2 FROM s_emps_emp
3 GROUP BY3 GROUP BY title;title;
SQL> SELECTSQL> SELECT title, MAX(salary)title, MAX(salary)
2 FROM2 FROM s_emps_emp
3 GROUP BY3 GROUP BY title;title;
90
Groups Within Groups: Example
Return summary results for groups and subgroups by listing more than one GROUP BY column.Determine the default sort order of the results by the order of the columns in the GROUP BY clause.SQL> SELECTSQL> SELECT dept_id, title, COUNT(*)dept_id, title, COUNT(*)
2 FROM2 FROM s_emps_emp
3 GROUP BY3 GROUP BY dept_id, title;dept_id, title;
SQL> SELECTSQL> SELECT dept_id, title, COUNT(*)dept_id, title, COUNT(*)
2 FROM2 FROM s_emps_emp
3 GROUP BY3 GROUP BY dept_id, title;dept_id, title;
91
SQL> SELECTSQL> SELECT title, 12 * AVG(salary) AS ”ANNUAL SALARY”,title, 12 * AVG(salary) AS ”ANNUAL SALARY”, 2 2 COUNT(*) COUNT(*) AS ”NUMBER OF EMPLOYEES”AS ”NUMBER OF EMPLOYEES” 3 FROM 3 FROM s_emps_emp 4 GROUP BY 4 GROUP BY titletitle 5 HAVING 5 HAVING COUNT(*) > 2;COUNT(*) > 2;
SQL> SELECTSQL> SELECT title, 12 * AVG(salary) AS ”ANNUAL SALARY”,title, 12 * AVG(salary) AS ”ANNUAL SALARY”, 2 2 COUNT(*) COUNT(*) AS ”NUMBER OF EMPLOYEES”AS ”NUMBER OF EMPLOYEES” 3 FROM 3 FROM s_emps_emp 4 GROUP BY 4 GROUP BY titletitle 5 HAVING 5 HAVING COUNT(*) > 2;COUNT(*) > 2;
Display Specific Groups by Using the HAVING Clause
TITLETITLE ANNUAL SALARYANNUAL SALARY NUMBER OF EMPLOYEESNUMBER OF EMPLOYEES---------------------------------------- ---------------------------- --------------------------------------Sales RepresentativeSales Representative $17,712.00$17,712.00 55Stock ClerkStock Clerk $11,388.00$11,388.00 1010Warehouse ManagerWarehouse Manager $14,776.80$14,776.80 55
HAVING clause (Restrict Groups)HAVING clause (Restrict Groups)
Display specific groups of job titles as Display specific groups of job titles as restricted in the HAVING clause.restricted in the HAVING clause.
92
The HAVING Clause: Syntax
Use the HAVING clause to further restrict groups.
Step 1: Rows are grouped.Step 2: The group function is applied to the group.Step 3: Groups matching the HAVING condition are displayed.
SELECTSELECT columncolumn, , group_functiongroup_function
FROMFROM tabletable
[WHERE[WHERE conditioncondition]]
[GROUP BY[GROUP BY group_by_expressiongroup_by_expression]]
[HAVING[HAVING group_conditiongroup_condition]]
[ORDER BY[ORDER BY columncolumn];];
SELECTSELECT columncolumn, , group_functiongroup_function
FROMFROM tabletable
[WHERE[WHERE conditioncondition]]
[GROUP BY[GROUP BY group_by_expressiongroup_by_expression]]
[HAVING[HAVING group_conditiongroup_condition]]
[ORDER BY[ORDER BY columncolumn];];
93
94
Displaying Data from Multiple Tables
95
Joining Tables - What Is a Join?
A join is used to query data from more than one table.Rows are joined using common values, typically primary and foreign key values.Join methods
EquijoinNon-equijoinOuter joinSelf joinSet operators
96
S_EMP TableS_EMP TableID LAST_NAME ID LAST_NAME DEPT_IDDEPT_ID-- --------------- --------- --------------- ------- 1 Velasquez1 Velasquez 5050 2 Ngao2 Ngao 4141 3 Nagayama3 Nagayama 3131 4 Quick-To-See4 Quick-To-See 1010 5 Ropeburn5 Ropeburn 5050 6 Urguhart6 Urguhart 4141 7 Menchu7 Menchu 4242 8 Biri8 Biri 4343 9 Catchpole9 Catchpole 444410 Havel10 Havel 454511 Magee11 Magee 313112 Giljum12 Giljum 323213 Sedeghi13 Sedeghi 333314 Nguyen14 Nguyen 343415 Dumas15 Dumas 353516 Maduro16 Maduro 4141
S_EMP TableS_EMP TableID LAST_NAME ID LAST_NAME DEPT_IDDEPT_ID-- --------------- --------- --------------- ------- 1 Velasquez1 Velasquez 5050 2 Ngao2 Ngao 4141 3 Nagayama3 Nagayama 3131 4 Quick-To-See4 Quick-To-See 1010 5 Ropeburn5 Ropeburn 5050 6 Urguhart6 Urguhart 4141 7 Menchu7 Menchu 4242 8 Biri8 Biri 4343 9 Catchpole9 Catchpole 444410 Havel10 Havel 454511 Magee11 Magee 313112 Giljum12 Giljum 323213 Sedeghi13 Sedeghi 333314 Nguyen14 Nguyen 343415 Dumas15 Dumas 353516 Maduro16 Maduro 4141
Relations Between Tables
S_DEPT TableS_DEPT TableID NAME REGION_IDID NAME REGION_ID-- --------------- ----------- --------------- ---------30 Finance 130 Finance 131 Sales 131 Sales 132 Sales 232 Sales 243 Operations 343 Operations 350 Administration 150 Administration 1
S_DEPT TableS_DEPT TableID NAME REGION_IDID NAME REGION_ID-- --------------- ----------- --------------- ---------30 Finance 130 Finance 131 Sales 131 Sales 132 Sales 232 Sales 243 Operations 343 Operations 350 Administration 150 Administration 1S_REGION TableS_REGION Table
ID NAMEID NAME-- ----------------------- --------------------- 1 North America1 North America 2 South America2 South America 3 Africa / Middle East3 Africa / Middle East 4 Asia4 Asia 5 Europe5 Europe
S_REGION TableS_REGION TableID NAMEID NAME-- ----------------------- --------------------- 1 North America1 North America 2 South America2 South America 3 Africa / Middle East3 Africa / Middle East 4 Asia4 Asia 5 Europe5 Europe
97
Cartesian Product
The results of a cartesian product are displayed 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.
98
Simple Join Query: Syntax
Write the join condition in the WHERE clause.
Precede each column name with the table name for clarity.
Column names must be prefixed with the table name when the same column name appears in more than one table.
SELECTSELECT table.column, table.columntable.column, table.column
FROMFROM table1, table2table1, table2
WHEREWHERE table1.column1 = table2.column2table1.column1 = table2.column2;;
SELECTSELECT table.column, table.columntable.column, table.column
FROMFROM table1, table2table1, table2
WHEREWHERE table1.column1 = table2.column2table1.column1 = table2.column2;;
99
Equijoin: Columns must match
S_EMPS_EMP S_DEPTS_DEPT
ServerServer
LAST_NAME LAST_NAME DEPT_IDDEPT_ID IDID NAMENAME------------------ -------------- ---- ------------------------------VelasquezVelasquez 5050 5050 AdministrationAdministrationNgaoNgao 4141 4141 OperationsOperationsNagayamaNagayama 3131 3131 SalesSalesRopeburnRopeburn 5050 5050 AdministrationAdministrationUrguhartUrguhart 4141 4141 OperationsOperationsMenchuMenchu 4242 4242 OperationsOperationsBiriBiri 4343 4343 OperationsOperationsHavelHavel 4545 4545 OperationsOperations...... ......
100
Equijoin: Example
Equijoins are most often used when a column in one table corresponds directly to a column in another table.The join condition includes the equal (=) operator.
Alternative (new) syntax:
SQL> SELECT e.ename, e.job, e.sal, d.dnameSQL> SELECT e.ename, e.job, e.sal, d.dname
22 FROM emp e, dept dFROM emp e, dept d
33 WHERE e.deptno = d.deptno;WHERE e.deptno = d.deptno;
SQL> SELECT e.ename, e.job, e.sal, d.dnameSQL> SELECT e.ename, e.job, e.sal, d.dname
22 FROM emp e, dept dFROM emp e, dept d
33 WHERE e.deptno = d.deptno;WHERE e.deptno = d.deptno;
SQL> SELECT e.ename, e.job, e.sal, d.dnameSQL> SELECT e.ename, e.job, e.sal, d.dname
22 FROM emp e INNER JOIN dept dFROM emp e INNER JOIN dept d
33 ON e.deptno = d.deptno;ON e.deptno = d.deptno;
SQL> SELECT e.ename, e.job, e.sal, d.dnameSQL> SELECT e.ename, e.job, e.sal, d.dname
22 FROM emp e INNER JOIN dept dFROM emp e INNER JOIN dept d
33 ON e.deptno = d.deptno;ON e.deptno = d.deptno;
101
Qualifying Ambiguous Column Names
Use table prefixes to qualify column names that are in multiple tables.
Improve performance by using table prefixes.
Distinguish columns that have identical names but reside in different tables by using column aliases.
102
Non-Equijoins: Example
Non-equijoins result when no column in one table corresponds directly to a column in the second table.
The join condition contains an operator other than equal (=).
SQL> SELECT e.ename, e.job, e.sal, s.gradeSQL> SELECT e.ename, e.job, e.sal, s.grade
22 FROM emp e, salgrade sFROM emp e, salgrade s
33 WHERE e.sal BETWEEN s.losal AND s.hisal;WHERE e.sal BETWEEN s.losal AND s.hisal;
SQL> SELECT e.ename, e.job, e.sal, s.gradeSQL> SELECT e.ename, e.job, e.sal, s.grade
22 FROM emp e, salgrade sFROM emp e, salgrade s
33 WHERE e.sal BETWEEN s.losal AND s.hisal;WHERE e.sal BETWEEN s.losal AND s.hisal;
103
Outer Joins: Old Syntax
Use an outer join to see rows that do not normally meet the join condition.Outer join operator is the plus sign (+).Place the operator on the side of the join where there is no value to join to.
SELECTSELECT table.column, table.columntable.column, table.column
FROMFROM table1, table2table1, table2
WHEREWHERE table1.column(+) = table2.columntable1.column(+) = table2.column;;
SELECTSELECT table.column, table.columntable.column, table.column
FROMFROM table1, table2table1, table2
WHEREWHERE table1.column(+) = table2.columntable1.column(+) = table2.column;;
104
Outer Joins: New Syntax
Use LEFT JOIN or RIGHT JOIN operators instead of INNER JOIN.LEFT JOIN returns all rows in first table.
RIGHT JOIN returns all rows in second table.
SELECTSELECT table.column, table.columntable.column, table.column
FROMFROM table1 LEFT JOIN table2table1 LEFT JOIN table2
ONON table1.column = table2.columntable1.column = table2.column;;
SELECTSELECT table.column, table.columntable.column, table.column
FROMFROM table1 LEFT JOIN table2table1 LEFT JOIN table2
ONON table1.column = table2.columntable1.column = table2.column;;
SELECTSELECT table.column, table.columntable.column, table.column
FROMFROM table1 RIGHT JOIN table2table1 RIGHT JOIN table2
ONON table1.column = table2.columntable1.column = table2.column;;
SELECTSELECT table.column, table.columntable.column, table.column
FROMFROM table1 RIGHT JOIN table2table1 RIGHT JOIN table2
ONON table1.column = table2.columntable1.column = table2.column;;
105
Outer join - Exemple
Select Employee.Num, Employee.name, Office.ONum, Office.Buildfrom Employee, Officewhere Employee.NumOff= Office.ONum(+);
or :
Select Employee. Num, Employee.name, Office.ONum, Office.Build from Employee LEFT JOIN OfficeON Employee.NumOff= Office.ONum
Employee OfficeNum Name NumOff ONum Build23 Toto 47 40 A183 Babette 18 42 B369 Loulou 03 47 A170 Marie 40 62 C1
Num Name ONum Build
23 Toto 47 A1
83 Babette 18 69 Loulou 03 70 Marie 40 A1
23
106
Self Joins: Example
Join rows in a table to rows in the same table by using a self join.Simulate two tables in the FROM clause by creating two aliases for the table.
SQL> SELECTSQL> SELECT worker.last_name||' works for '||worker.last_name||' works for '||
2 2 manager.last_namemanager.last_name
3 FROM3 FROM s_emp worker, s_emp managers_emp worker, s_emp manager
4 WHERE4 WHERE worker.manager_id = manager.id;worker.manager_id = manager.id;
SQL> SELECTSQL> SELECT worker.last_name||' works for '||worker.last_name||' works for '||
2 2 manager.last_namemanager.last_name
3 FROM3 FROM s_emp worker, s_emp managers_emp worker, s_emp manager
4 WHERE4 WHERE worker.manager_id = manager.id;worker.manager_id = manager.id;
107
Summary
You can use multiple methods to join tables:EquijoinNon-equijoinOuter joinSelf join
Create a Cartesian product if you omit the WHERE clause.
Speed up database access with table aliases.
Use aliases to set up self joins.
108
Operations on Result Sets
109
Sometimes it is useful to combine query results from two or more queries into a single result.
SQL supports three set operators which have the pattern
The set operators are:UNIONINTERSECTMINUS
<select statement1><select statement1>
<set operator><set operator>
<select statement 2>;<select statement 2>;
<select statement1><select statement1>
<set operator><set operator>
<select statement 2>;<select statement 2>;
110
Union
Combine two companies customer lists where they have names in common so that the final list has no duplicate names
Column attributes must be the same
Can include more than two tables where applicable
SELECTSELECT <COLUMN> <COLUMN> [AS [AS “Column names”“Column names”]] FROMFROM customer customerUNIONUNION SELECTSELECT <COLUMN> <COLUMN> FROMFROM CUSTOMER_2; CUSTOMER_2;
SELECTSELECT <COLUMN> <COLUMN> [AS [AS “Column names”“Column names”]] FROMFROM customer customerUNIONUNION SELECTSELECT <COLUMN> <COLUMN> FROMFROM CUSTOMER_2; CUSTOMER_2;
SELECTSELECT <COLUMN NAMES> <COLUMN NAMES> FROMFROM T1 T1 UNIONUNION SELECTSELECT <COLUMN NAMES> <COLUMN NAMES> FROMFROM T2 T2 UNIONUNIONSELECTSELECT <COLUMN NAMES> <COLUMN NAMES> FROMFROM T3; T3;
SELECTSELECT <COLUMN NAMES> <COLUMN NAMES> FROMFROM T1 T1 UNIONUNION SELECTSELECT <COLUMN NAMES> <COLUMN NAMES> FROMFROM T2 T2 UNIONUNIONSELECTSELECT <COLUMN NAMES> <COLUMN NAMES> FROMFROM T3; T3;
111
UNION Query Result
SELECTSELECT CUS_LNAME, CUS_FNAME, … FROM CUSTOMER_1 CUS_LNAME, CUS_FNAME, … FROM CUSTOMER_1UNIONUNIONSELECT CUS_LNAME, CUS_FNAME, … FROM CUSTOMER_2;SELECT CUS_LNAME, CUS_FNAME, … FROM CUSTOMER_2;
SELECTSELECT CUS_LNAME, CUS_FNAME, … FROM CUSTOMER_1 CUS_LNAME, CUS_FNAME, … FROM CUSTOMER_1UNIONUNIONSELECT CUS_LNAME, CUS_FNAME, … FROM CUSTOMER_2;SELECT CUS_LNAME, CUS_FNAME, … FROM CUSTOMER_2;
112
UNION ALL Query ResultUNION ALL merges the tables but keeps duplicates in the result table
SELECTSELECT CUS_LNAME, CUS_FNAME, … FROM CUSTOMER_1 CUS_LNAME, CUS_FNAME, … FROM CUSTOMER_1UNION ALLUNION ALLSELECT CUS_LNAME, CUS_FNAME, … FROM CUSTOMER_2;SELECT CUS_LNAME, CUS_FNAME, … FROM CUSTOMER_2;
SELECTSELECT CUS_LNAME, CUS_FNAME, … FROM CUSTOMER_1 CUS_LNAME, CUS_FNAME, … FROM CUSTOMER_1UNION ALLUNION ALLSELECT CUS_LNAME, CUS_FNAME, … FROM CUSTOMER_2;SELECT CUS_LNAME, CUS_FNAME, … FROM CUSTOMER_2;
113
Intersection - Example
Number and names of managers who are engineers
select n°Employee, namefrom Engineerintersectselect n°Employee, namefrom Manager
UEngineerManager
Engineer Managern°Employee name n°Employee name
10 Toto 13 Babette12 Jojo 14 Loulou13 Babette 15 Lolo15 Lolo
n°Employee name13 Babette15 Lolo
114
Difference - Example
Names of the students that didn’t assist
-select nameId, UV from Inscribedminusselect nameId, UVfrom Attendance
Inscribed AttendancenameId UV nameId UV
Toto Maths Toto MathsJojo Maths Jojo MathsToto Physics Babette comp
Babette compJojo comp
nomId UVToto PhysicsJojo comp
115
Remark
Union, intersection and difference need to have relations with the same data types.
These operators are frequently used after projections in order to have these same domains
116
Subqueries
117
What Is a Subquery?
SELECT Syntax
SELECT...SELECT...
FROM...FROM...
WHERE...WHERE...SELECT Syntax
(SELECT...(SELECT...
FROM...FROM...
WHERE...);WHERE...);
Main Main QueryQuery
SubquerySubquery
A subquery is a SELECT statement embedded in a clause of another SQL statement.
118
Subqueries: Syntax
The subquery executes once before the main query.The result of the subquery is used by the main outer query.
SELECTSELECT select_listselect_listFROMFROM tabletableWHEREWHERE expr operatorexpr operator
(SELECT(SELECT select_listselect_list FROMFROM tabletable););
SELECTSELECT select_listselect_listFROMFROM tabletableWHEREWHERE expr operatorexpr operator
(SELECT(SELECT select_listselect_list FROMFROM tabletable););
119
How Are Nested Subqueries Processed?
SELECTSELECT dept_iddept_idFROMFROM s_emps_empWHEREWHERE last_name='Biri';last_name='Biri';
Nested QueryNested Query
SELECTSELECT last_name, titlelast_name, titleFROMFROM s_emps_empWHEREWHERE dept_iddept_id = =
Main QueryMain Query
4343
1. Nested SELECT statement is executed first.2. Result is passed into condition of main
query.
120
Single Row Subqueries
SELECT last_name, titleSELECT last_name, titleFROM FROM s_emp s_empWHERE WHERE title = title =
SELECT titleSELECT titleFROM FROM s_emp s_empWHERE WHERE last_name = ’Smith’ last_name = ’Smith’
SQL> SELECT last_name, titleSQL> SELECT last_name, title 2 FROM s_emp 2 FROM s_emp 3 WHERE title = 3 WHERE title = 4 4 (SELECT title (SELECT title 5 5 FROM s_emp FROM s_emp 6 6 WHERE last_name = ’Smith’); WHERE last_name = ’Smith’);
Write the SQLWrite the SQLstatement tostatement todisplay thedisplay thelast name last name and title of and title of an employee.an employee.
Write the SQLWrite the SQLstatement tostatement tofind out find out Smith’s title.Smith’s title.
Put bothPut bothstatementsstatementstogether and together and let SQL let SQL determinedeterminethe title forthe title forSmith.Smith.
121
Multiple Row Subqueries: Example
A multiple row subquery returns many rows.You must use a multiple row operator in the WHERE clause, for example the [NOT]IN operator.
SQL> SELECTSQL> SELECT last_name, first_name, titlelast_name, first_name, title 2 FROM2 FROM s_emps_emp 3 WHERE3 WHERE dept_in INdept_in IN 44 (SELECT(SELECT IDID 55 FROMFROM s_depts_dept66 WHERE name = 'Finance'WHERE name = 'Finance'77 OR region_id = 2); OR region_id = 2);
SQL> SELECTSQL> SELECT last_name, first_name, titlelast_name, first_name, title 2 FROM2 FROM s_emps_emp 3 WHERE3 WHERE dept_in INdept_in IN 44 (SELECT(SELECT IDID 55 FROMFROM s_depts_dept66 WHERE name = 'Finance'WHERE name = 'Finance'77 OR region_id = 2); OR region_id = 2);
122
Summary
Subqueries are useful when a query is based on unknown values.A subquery contains more than one SELECT statement.
SELECTSELECT select_listselect_listFROMFROM tabletableWHEREWHERE expr operatorexpr operator
(SELECT(SELECT select_listselect_list FROMFROM tabletable););
SELECTSELECT select_listselect_listFROMFROM tabletableWHEREWHERE expr operatorexpr operator
(SELECT(SELECT select_listselect_list FROMFROM tabletable););
123
Chapter 2. SQL*plus
124
What is it?
SQL*PLUS is an Oracle interactive user interface with application language
Typically used to issue ad-hoc queries and to view the query result on the screen
Provides an interactive environment that allows users to:
Connect to and disconnect from a database;Analyze SQL statements;Control the output format;Execute a bunch of SQL statements from a file.
125
Logging in to SQL*Plus
From a windows environment Double-click the icon. Fill in username and password.
From command line sqlplus [username[/password]]
126
Entering Commands in SQL*Plus
SQL commands to manipulate data and database structures
SQL*Plus commands to format query results, edit commands, and create variables
PL/SQL blocks to execute procedural statements
An SQL statement must always be terminated by a semicolon (;)SQL*Plus commands need not be terminated by a semicolon. Upper and lower case letters are only important for string comparisons.
127
Comparison of SQL and SQL*Plus Commands
Communicates with Oracle Server.Uses database commands - SELECT.Is stored in the SQL buffer.Uses functions to perform formatting.
• Recognizes SQL Recognizes SQL commands.commands.
• Is not a database Is not a database command language.command language.
• Is not stored in the Is not stored in the SQL buffer.SQL buffer.
• Uses commands to Uses commands to format data.format data.
SQLSQL SQL*PlusSQL*Plus
128
How to Get HELP
SQLPLUS commands are described in SQLPLUS Help system
SQL> HELP indexThis command returns list of all SQLPLUS commands
SQL> HELP Command
129
Useful SQLPLUS Commands
Current SQL statement is stored in a buffer To display the buffer content use L[IST] command
To modify buffer content use CHANGE commandC[HANGE] /old_string/new_string/
To re-execute the statement from the bufferSQL> /
Or SQL> R[UN]
130
Other Useful SQLPLUS Commands
SAVE [REPLACE | APPEND] saves buffer content into a file on the host
DESC[RIBE] displays table’s definition (its fields and data types)
DESC Table_name;
NOT NULL columns must contain data. Example column data type and length
NUMBER (p,s)VARCHAR2(s)DATECHAR(s)
SAVE SAVE File_name.sql [REPLACE|APPEND];File_name.sql [REPLACE|APPEND];SAVE SAVE File_name.sql [REPLACE|APPEND];File_name.sql [REPLACE|APPEND];
131
Other Useful SQLPLUS Commands
GET loads the file content from the host into statement buffer
GET File_name.sql;
The statement can be re-executed by “/” command or “RUN”
To execute a statement from a file without GET command@File_name.sql;
Or start File_name.sql;
132
Editors
ED[IT] invokes an editor and loads the current buffer into the editor.
EDIT File_name;Invokes the editor and load the file into it
After exiting the editor, the modified SQL statement is stored in the buffer and can be executed
(command run).
133
Other Useful SQLPLUS Commands
SET PAUSE commandAllows you to control scrolling of your terminal. You must press [Return] after seeing each pause.
SET LINESIZE Controls the length of line
An SQL query can always be interrupted by using <Control>C.
To exit SQL*Plus you can either type exit or quit.
SET PAUSE {OFF|ON| text}SET PAUSE {OFF|ON| text}SET PAUSE {OFF|ON| text}SET PAUSE {OFF|ON| text}
134
SQL*Plus User Variables
A SQL*Plus user variable is a CHAR variable, which can be assigned a string value.User variables can be defined as substitution variable in SQL statementsAn ampersand (&) precedes the substitution variable inside a SQL statement.SELECT * SELECT *
FROM s_dept FROM s_dept
WHERE region_id = &id;WHERE region_id = &id;
Enter value for id: 2Enter value for id: 2
......
SELECT * SELECT *
FROM s_dept FROM s_dept
WHERE region_id = &id;WHERE region_id = &id;
Enter value for id: 2Enter value for id: 2
......
135
SQL*Plus User Variables
DEFINE variable [ = text ]Defines a CHAR user variable and stores input from the user into the variable.
UNDEFINE variable Erases the user variable.
DEFINE id = 2DEFINE id = 2
SELECT * FROM s_dept WHERE region_id = &id;SELECT * FROM s_dept WHERE region_id = &id;
... ...
UNDEFINE idUNDEFINE id
DEFINE id = 2DEFINE id = 2
SELECT * FROM s_dept WHERE region_id = &id;SELECT * FROM s_dept WHERE region_id = &id;
... ...
UNDEFINE idUNDEFINE id
136
Record Your Session
SPOOL file_nameThe command records SQL statements, SQLPLUS commands and system’s responses to the specified file (.lst)
SPOOL OFF – stops spooling
SPOOL OUT – stops spooling and sends the file to the printer
137
Chapter 3.
PL/SQL: Procedural Language SQL
138
What is PL/SQL?
PL/SQL is an extension to SQL with design features of programming languages.Data manipulation and query statements are included within procedural units of code.
Benefits of PL/SQLModularize program developmentDeclare identifiersProgram with procedural language control structuresHandle errorsImprove performance
Introduction
139
Why PL/SQL
Oracle Database Server
Client Application Server
SQL SQL SQL
140
SQL
Program resides on client machineLots of requests to database serverRequests made through SQLEach request sends back information
One network trip for each SQL request
141
Why PL/SQL
Oracle Database Server
Client Application Server
Call PL/SQL prog
Call PL/SQL prog
Call PL/SQL prog
PL/SQL prog------------
SQLSQLSQLSQL
142
Pl/SQL sits inside database
Programs reside on client machinesRequests DB server to run PL/SQL programSeveral SQL statements bundled together as a single PL/SQL blockRun as a single unitIntermediate operation results stay on database serverResults sent backLess network traffic
143
PL/SQL Block Structure
[DECLARE] -- OptionalVariables, constants, cursors, user-defined exceptions
BEGIN -- MandatorySQL statementsPL/SQL control statements
[EXCEPTION ] -- OptionalActions to perform when errors occur
END; -- Mandatory
[DECLARE] -- OptionalVariables, constants, cursors, user-defined exceptions
BEGIN -- MandatorySQL statementsPL/SQL control statements
[EXCEPTION ] -- OptionalActions to perform when errors occur
END; -- Mandatory
144
Example PL/SQL Block
DECLARE v_product_id s_product.id%TYPE;BEGIN SELECT idINTO v_product_idFROM s_productWHERE id = &p_product_id; DELETE FROM s_inventoryWHERE product_id = v_product_id; COMMIT;EXCEPTION WHEN OTHERS THENROLLBACK;INSERT INTO exception_table (message)VALUES ('Some error occurred in the database.');COMMIT;END;
DECLARE v_product_id s_product.id%TYPE;BEGIN SELECT idINTO v_product_idFROM s_productWHERE id = &p_product_id; DELETE FROM s_inventoryWHERE product_id = v_product_id; COMMIT;EXCEPTION WHEN OTHERS THENROLLBACK;INSERT INTO exception_table (message)VALUES ('Some error occurred in the database.');COMMIT;END;
145
Program Structure
May span multiple text editor lines
Each line ends with a semicolon
Text is not case sensitive
Comments /* */
Single line comments --
146
Data Types
integer --signed integernumber(p,n)realchar(n) varchar2(n)boolean – true or falsedate
147
Variable declaration
name datatype [not null] [ := value ]name [constant] datatype := valueNote:
assignment is :=Constants and not nulls must be initialized with a value
instead of standard datatype we can use:name%type
where name is a column or variable name whose type you want to use.
for example: id employees.empID%type
foo integer not null := 20;
pi constant real not null := 3.14;
foo integer not null := 20;
pi constant real not null := 3.14;
148
The %TYPE Attribute
Declare a variable according to Another previously declared variable.A database column definition.
Prefix %TYPE withThe database table and column.The previously declared variable name.
PL/SQL determines the datatype and size of the variable.
149
The %TYPE Attribute: Examples
Advantages of using the %TYPE attributeThe datatype of the underlying database column may be unknown.The datatype of the underlying database column may change at runtime.
......
v_last_namev_last_name s_emp.last_name%TYPE;s_emp.last_name%TYPE;
v_first_name v_first_name s_emp.first_name%TYPE;s_emp.first_name%TYPE;
v_balancev_balance NUMBER(7,2);NUMBER(7,2);
v_minimum_balancev_minimum_balance v_balance%TYPE := 10;v_balance%TYPE := 10;
......
......
v_last_namev_last_name s_emp.last_name%TYPE;s_emp.last_name%TYPE;
v_first_name v_first_name s_emp.first_name%TYPE;s_emp.first_name%TYPE;
v_balancev_balance NUMBER(7,2);NUMBER(7,2);
v_minimum_balancev_minimum_balance v_balance%TYPE := 10;v_balance%TYPE := 10;
......
150
Variables
Must start with a letter (A-Z)
optionally followed by one or more letters, numbers 0-9, or the special characters $, #, or _
no longer than 30 characters
no spaces embedded in variable name
Cannot use reserved words as variable names
151
Scalar Variable Declarations: Examples
v_gender CHAR(1);
v_total_sal NUMBER(9,2) := 0;
v_order_date DATE := SYSDATE + 7;
c_tax_rate CONSTANT NUMBER(3,2) := 8.25;
v_valid BOOLEAN NOT NULL := TRUE;
v_gender CHAR(1);
v_total_sal NUMBER(9,2) := 0;
v_order_date DATE := SYSDATE + 7;
c_tax_rate CONSTANT NUMBER(3,2) := 8.25;
v_valid BOOLEAN NOT NULL := TRUE;
152
Controlling PL/SQL Flow of ExecutionChange the logical flow of statements by
usingcontrol structures:
Conditional control structures (IF statement)Loop control structures
Basic loopFOR loopWHILE loopEXIT statement
153
If Guidelines
Each if statement followed by its own then
each if statement block terminated by a matching end if
can be one and only one else with every if statement
no matching end if with each elsif
154
The IF Statement: Syntax
You can perform actions selectively based upon conditions being met.
ELSIF is one word.END IF is two words.At most, one ELSE clause is permitted.
IF IF conditioncondition THEN THEN
statementsstatements;;
[ELSIF [ELSIF conditioncondition THEN THEN
statementsstatements;];]
[ELSE[ELSE
statementsstatements;];]
END IF;END IF;
IF IF conditioncondition THEN THEN
statementsstatements;;
[ELSIF [ELSIF conditioncondition THEN THEN
statementsstatements;];]
[ELSE[ELSE
statementsstatements;];]
END IF;END IF;
155
Simple IF Statements: Example
Set the job title to Sales Representative and the region number to 35 if the last name is Dumas.
. . .. . .
IF v_last_name = 'Dumas' THENIF v_last_name = 'Dumas' THEN
v_job := 'Sales Representative'; v_job := 'Sales Representative';
v_region_id := 35;v_region_id := 35;
END IF;END IF;
. . .. . .
. . .. . .
IF v_last_name = 'Dumas' THENIF v_last_name = 'Dumas' THEN
v_job := 'Sales Representative'; v_job := 'Sales Representative';
v_region_id := 35;v_region_id := 35;
END IF;END IF;
. . .. . .
156
IF-THEN-ELSE Statements: ExampleSet a flag for orders where there are fewer than 5 days between order date and ship date.
. . .. . .
IF v_date_shipped - v_date_ordered < 5 THEN IF v_date_shipped - v_date_ordered < 5 THEN
v_ship_flag := 'Acceptable';v_ship_flag := 'Acceptable';
ELSEELSE
v_ship_flag := 'Unacceptable';v_ship_flag := 'Unacceptable';
END IF;END IF;
. . .. . .
. . .. . .
IF v_date_shipped - v_date_ordered < 5 THEN IF v_date_shipped - v_date_ordered < 5 THEN
v_ship_flag := 'Acceptable';v_ship_flag := 'Acceptable';
ELSEELSE
v_ship_flag := 'Unacceptable';v_ship_flag := 'Unacceptable';
END IF;END IF;
. . .. . .
157
IF-THEN-ELSIF Statements: Example
For a given value entered, return a calculated value.
. . .. . .
IF v_start > 100 THENIF v_start > 100 THEN
RETURN (2 * v_start);RETURN (2 * v_start);
ELSIF v_start >= 50 THEN ELSIF v_start >= 50 THEN
RETURN (.5 * v_start);RETURN (.5 * v_start);
ELSEELSE
RETURN (.1 * v_start);RETURN (.1 * v_start);
END IF;END IF;
. . .. . .
. . .. . .
IF v_start > 100 THENIF v_start > 100 THEN
RETURN (2 * v_start);RETURN (2 * v_start);
ELSIF v_start >= 50 THEN ELSIF v_start >= 50 THEN
RETURN (.5 * v_start);RETURN (.5 * v_start);
ELSEELSE
RETURN (.1 * v_start);RETURN (.1 * v_start);
END IF;END IF;
. . .. . .
158
Example
SQL> SET SERVEROUTPUT ON ;SQL> SET SERVEROUTPUT ON ;SQL> SET SERVEROUTPUT ON ;SQL> SET SERVEROUTPUT ON ;
DECLARE DECLARE
v_num NUMBER (2);v_num NUMBER (2);
BEGINBEGIN
v_num := 50;v_num := 50;
DBMS_OUTPUT.PUT_LINE ( ‘Number is ‘ || TO_CHAR (v_num));DBMS_OUTPUT.PUT_LINE ( ‘Number is ‘ || TO_CHAR (v_num));
END;END;
DECLARE DECLARE
v_num NUMBER (2);v_num NUMBER (2);
BEGINBEGIN
v_num := 50;v_num := 50;
DBMS_OUTPUT.PUT_LINE ( ‘Number is ‘ || TO_CHAR (v_num));DBMS_OUTPUT.PUT_LINE ( ‘Number is ‘ || TO_CHAR (v_num));
END;END;
159
Hello World
SET SERVEROUTPUT ON
BEGIN DBMS_OUTPUT.enable; DBMS_OUTPUT.put_line (‘Hello World’);END;/
Will stay on until sessionis completed or it is turnedoff...
SQL*Plus writes out whateverthe server returns to it...
Output mechanism is turnedon. . .
Prints the string. . .
Executes the PL/SQL block
160
Debugging
to see compilation error informationshow errors;
set serveroutput on; -- to enable output from statements below
dbms_output.put_line(expression)Print expression and returns to a new Line
dbms_output.put(expression)Print expression
dbms_output.new_lineNew line
161
Circle Program
SET SERVEROUPUT ONDECLARE PI CONSTANT REAL := 3.14159265359; circumference REAL; area REAL; radius REAL :=&Radius;
BEGIN DBMS_OUTPUT.enable; circumference := PI * 2.0 * radius; area := PI * power(radius,2); DBMS_OUTPUT.put_line(‘Radius = ‘ || TO_CHAR(radius) || ‘, Circumference = ‘ || TO_CHAR(circumference) || ‘, Area = ‘ || TO_CHAR(area));END;/
SET SERVEROUPUT ONDECLARE PI CONSTANT REAL := 3.14159265359; circumference REAL; area REAL; radius REAL :=&Radius;
BEGIN DBMS_OUTPUT.enable; circumference := PI * 2.0 * radius; area := PI * power(radius,2); DBMS_OUTPUT.put_line(‘Radius = ‘ || TO_CHAR(radius) || ‘, Circumference = ‘ || TO_CHAR(circumference) || ‘, Area = ‘ || TO_CHAR(area));END;/
162
LOOP Statements
Loops repeat a statement or sequence of statements multiple times.Three loop types:
Basic loopFOR loopWHILE loop
163
• Iterate through your statements with a basic Iterate through your statements with a basic loop.loop.
• Without the EXIT statement, the loop would be Without the EXIT statement, the loop would be infinite.infinite.
LOOP LOOP
statement1statement1;;
. . .. . .
EXIT [WHEN EXIT [WHEN conditioncondition];];
END LOOP;END LOOP;
LOOP LOOP
statement1statement1;;
. . .. . .
EXIT [WHEN EXIT [WHEN conditioncondition];];
END LOOP;END LOOP;
Basic Loop: Syntax
-- delimiter
-- statements
-- EXIT statement
-- delimiter
164
Basic Loop: Example II
I integer := 0;I integer := 0;
LOOPLOOP
IF (I > 10) thenIF (I > 10) then
EXIT; EXIT; -- “break”-- “break”
END IF;END IF;
I := I + 1;I := I + 1;
END LOOP;END LOOP;
I integer := 0;I integer := 0;
LOOPLOOP
IF (I > 10) thenIF (I > 10) then
EXIT; EXIT; -- “break”-- “break”
END IF;END IF;
I := I + 1;I := I + 1;
END LOOP;END LOOP;
165
Basic Loop: Example I
Insert ten new lines into the table s_item with order number 101
. . .. . .
v_ord_idv_ord_id s_item.ord_id%TYPE := 101;s_item.ord_id%TYPE := 101;
v_counterv_counter NUMBER(2) := 1;NUMBER(2) := 1;
BEGINBEGIN
. . .. . .
LOOPLOOP
INSERT INTO s_item (ord_id, item_id) INSERT INTO s_item (ord_id, item_id)
VALUES (v_ord_id, v_counter);VALUES (v_ord_id, v_counter);
v_counter := v_counter + 1;v_counter := v_counter + 1;
EXIT WHEN v_counter > 10;EXIT WHEN v_counter > 10;
END LOOP;END LOOP;
. . .. . .
. . .. . .
v_ord_idv_ord_id s_item.ord_id%TYPE := 101;s_item.ord_id%TYPE := 101;
v_counterv_counter NUMBER(2) := 1;NUMBER(2) := 1;
BEGINBEGIN
. . .. . .
LOOPLOOP
INSERT INTO s_item (ord_id, item_id) INSERT INTO s_item (ord_id, item_id)
VALUES (v_ord_id, v_counter);VALUES (v_ord_id, v_counter);
v_counter := v_counter + 1;v_counter := v_counter + 1;
EXIT WHEN v_counter > 10;EXIT WHEN v_counter > 10;
END LOOP;END LOOP;
. . .. . .
166
FOR Loop: Syntax
Use a FOR loop to shortcut the test for the number of iterations.
Do not declare the index; it is declared implicitly.
FOR FOR indexindex in [REVERSE] in [REVERSE]
lower_bound..upper_boundlower_bound..upper_bound LOOP LOOP
statement1statement1;;
statement2statement2;;
. . .. . .
END LOOP;END LOOP;
FOR FOR indexindex in [REVERSE] in [REVERSE]
lower_bound..upper_boundlower_bound..upper_bound LOOP LOOP
statement1statement1;;
statement2statement2;;
. . .. . .
END LOOP;END LOOP;
167
FOR Loop: Guidelines
Reference the index within the loop only; it is undefined outside the loop.
Use an expression to reference the existing value of an index.
Do not reference the index as the target of an assignment outside the loop
168
For-in-loop-end Loop
DECLAREDECLARE
Temp integer:=0;Temp integer:=0;
Lv integer;Lv integer;
BEGINBEGIN
For cnt in 1 .. 5 loopFor cnt in 1 .. 5 loop Lv := cnt;Lv := cnt; dbms_output.put_line(‘the index: ‘ || to_char(cnt));dbms_output.put_line(‘the index: ‘ || to_char(cnt)); Temp := Temp+1;Temp := Temp+1;end loop;end loop;dbms_output.put_line(‘the last value : ‘ || to_char(Lv));dbms_output.put_line(‘the last value : ‘ || to_char(Lv));Dbms_output.put_line(‘number of iterations :’ || Dbms_output.put_line(‘number of iterations :’ || to_char(temp));to_char(temp));End;End;
DECLAREDECLARE
Temp integer:=0;Temp integer:=0;
Lv integer;Lv integer;
BEGINBEGIN
For cnt in 1 .. 5 loopFor cnt in 1 .. 5 loop Lv := cnt;Lv := cnt; dbms_output.put_line(‘the index: ‘ || to_char(cnt));dbms_output.put_line(‘the index: ‘ || to_char(cnt)); Temp := Temp+1;Temp := Temp+1;end loop;end loop;dbms_output.put_line(‘the last value : ‘ || to_char(Lv));dbms_output.put_line(‘the last value : ‘ || to_char(Lv));Dbms_output.put_line(‘number of iterations :’ || Dbms_output.put_line(‘number of iterations :’ || to_char(temp));to_char(temp));End;End;
ExamplePrint the number of times the loop is executed and the last value for the index.
169
WHILE Loop: Syntax
Use the WHILE loop to repeat statements while a condition is TRUE.
WHILE WHILE conditioncondition LOOP LOOP
statement1statement1;;
statement2statement2;;
. . .. . .
END LOOP;END LOOP;
WHILE WHILE conditioncondition LOOP LOOP
statement1statement1;;
statement2statement2;;
. . .. . .
END LOOP;END LOOP;
Condition isevaluated at the beginning ofeach iteration.
170
WHILE Loop: Example
Insert the first ten new line items for order number 101.
. . .. . .
v_ord_idv_ord_id s_item.ord_id%TYPE := 101;s_item.ord_id%TYPE := 101;
v_counterv_counter NUMBER(2) := 1;NUMBER(2) := 1;
BEGINBEGIN
. . .. . .
WHILE v_counter <= 10 LOOPWHILE v_counter <= 10 LOOP
INSERT INTO s_item (ord_id, item_id)INSERT INTO s_item (ord_id, item_id)
VALUES (v_ord_id, v_counter);VALUES (v_ord_id, v_counter);
v_counter := v_counter + 1;v_counter := v_counter + 1;
END LOOP;END LOOP;
. . .. . .
. . .. . .
v_ord_idv_ord_id s_item.ord_id%TYPE := 101;s_item.ord_id%TYPE := 101;
v_counterv_counter NUMBER(2) := 1;NUMBER(2) := 1;
BEGINBEGIN
. . .. . .
WHILE v_counter <= 10 LOOPWHILE v_counter <= 10 LOOP
INSERT INTO s_item (ord_id, item_id)INSERT INTO s_item (ord_id, item_id)
VALUES (v_ord_id, v_counter);VALUES (v_ord_id, v_counter);
v_counter := v_counter + 1;v_counter := v_counter + 1;
END LOOP;END LOOP;
. . .. . .
171
Nested Loops and Labels
Nest loops to multiple levels.Use labels to distinguish between blocks and loops.Exit the outer loop with the EXIT statement referencing the label.
172
Nested Loops and Labels: ExampleExit an outer loop based on the values of an
inner block.
......BEGINBEGIN <<Outer-loop>> LOOP<<Outer-loop>> LOOP
v_counter :=v_counter+1;v_counter :=v_counter+1;EXIT WHEN v_counter>10;EXIT WHEN v_counter>10;<<Inner_loop>> LOOP<<Inner_loop>> LOOP
......EXIT Outer_loop WHEN total_done = ‘YES’;EXIT Outer_loop WHEN total_done = ‘YES’;
--Leave both loops--Leave both loops EXIT WHEN inner_done = ‘YES’;EXIT WHEN inner_done = ‘YES’;
--Leave inner loop only--Leave inner loop only ......
END LOOP Inner_loop;END LOOP Inner_loop;......
END LOOP Outer_loop;END LOOP Outer_loop;END; END;
......BEGINBEGIN <<Outer-loop>> LOOP<<Outer-loop>> LOOP
v_counter :=v_counter+1;v_counter :=v_counter+1;EXIT WHEN v_counter>10;EXIT WHEN v_counter>10;<<Inner_loop>> LOOP<<Inner_loop>> LOOP
......EXIT Outer_loop WHEN total_done = ‘YES’;EXIT Outer_loop WHEN total_done = ‘YES’;
--Leave both loops--Leave both loops EXIT WHEN inner_done = ‘YES’;EXIT WHEN inner_done = ‘YES’;
--Leave inner loop only--Leave inner loop only ......
END LOOP Inner_loop;END LOOP Inner_loop;......
END LOOP Outer_loop;END LOOP Outer_loop;END; END;
173
CASE Statement
CASE grade WHEN 'A' THEN dbms_output.put_line('Excellent'); WHEN 'B' THEN dbms_output.put_line('Very Good'); WHEN 'C' THEN dbms_output.put_line('Good'); WHEN 'D' THEN dbms_output.put_line('Fair');WHEN 'F' THEN dbms_output.put_line('Poor');ELSE dbms_output.put_line('No such grade');
END CASE;
174
CASE StatementUsing the following syntax, the CASE statement can evaluate a condition and returns a value for each case:
CASE WHEN shape = 'square' THEN area := side * side;WHEN shape = 'circle' THEN
BEGIN area := pi * (radius * radius);
DBMS_OUTPUT.PUT_LINE('Value is not exact because pi is irrational.'); END;
WHEN shape = 'rectangle' THEN area := length * width; ELSE BEGIN DBMS_OUTPUT.PUT_LINE('No formula to calculate area of a' || shape);
RAISE PROGRAM_ERROR; END; END CASE;
175
Where the parameter syntax isWhere the parameter syntax is
Creating a Procedure: Syntax
PROCEDURE name
[(parameter,...)]
IS
pl/sql_block;
PROCEDURE name
[(parameter,...)]
IS
pl/sql_block;
parameter_nameparameter_name [IN | OUT | IN OUT] [IN | OUT | IN OUT] datatypedatatypeparameter_nameparameter_name [IN | OUT | IN OUT] [IN | OUT | IN OUT] datatypedatatype
176
Creating a Procedure: Guidelines
Use the CREATE OR REPLACE clause when building your procedure in SQL*Plus.
Enter any parameter.
Start the PL/SQL block with IS.
Enter a local variable declaration or the keyword BEGIN after IS.
View procedures and functions:Select text from user_source where name=‘function_or_procedure name’;
177
Procedural Parameter Modes
ProcedureProcedure
(DECLARE)(DECLARE)
BEGINBEGIN
EXCEPTIONEXCEPTION
END;END;
IN Argument
OUT Argument
IN OUT Argument
CallingEnvironment
178
Creating a Procedure: Example
PROCEDURE change_salary
(v_emp_id IN NUMBER,
v_new_salary IN NUMBER)
IS
BEGIN
UPDATE s_emp
SET salary = v_new_salary
WHERE id = v_emp_id;
COMMIT;
END change_salary;
PROCEDURE change_salary
(v_emp_id IN NUMBER,
v_new_salary IN NUMBER)
IS
BEGIN
UPDATE s_emp
SET salary = v_new_salary
WHERE id = v_emp_id;
COMMIT;
END change_salary;
179
Invoking Procedures from Procedure BuilderEnter the procedure name with actual parameters, if applicable, at the Interpreter prompt.
PL/SQL> execute change_salary (17, 1000);PL/SQL> execute change_salary (17, 1000);PL/SQL> execute change_salary (17, 1000);PL/SQL> execute change_salary (17, 1000);
180
Invoking Procedures from Another Procedure: Example
PROCEDURE process_salPROCEDURE process_sal
(v_emp_id IN NUMBER,(v_emp_id IN NUMBER,
v_new_salary IN NUMBER)v_new_salary IN NUMBER)
ISIS
BEGINBEGIN
change_salary (v_emp_id, v_new_salary);change_salary (v_emp_id, v_new_salary);
--invoking procedure change_salary--invoking procedure change_salary
......
END;END;
PROCEDURE process_salPROCEDURE process_sal
(v_emp_id IN NUMBER,(v_emp_id IN NUMBER,
v_new_salary IN NUMBER)v_new_salary IN NUMBER)
ISIS
BEGINBEGIN
change_salary (v_emp_id, v_new_salary);change_salary (v_emp_id, v_new_salary);
--invoking procedure change_salary--invoking procedure change_salary
......
END;END;
181
Creating a Function
Create a PL/SQL function to return a value to the calling environment.
Add a RETURN clause with the datatype in the declaration of the function.
Include at least one RETURN statement in the PL/SQL block.
Use the CREATE OR REPLACE clause when building your FUNCTION in SQL*Plus.
182
Creating a Function: Syntax
FUNCTION FUNCTION namename
[([(parameter,...parameter,...)])]
RETURN RETURN datatypedatatype
ISIS
pl/sql_blockpl/sql_block;;
FUNCTION FUNCTION namename
[([(parameter,...parameter,...)])]
RETURN RETURN datatypedatatype
ISIS
pl/sql_blockpl/sql_block;;
Remember to include at least one RETURN Remember to include at least one RETURN statement in the PL/SQL block.statement in the PL/SQL block.
183
Creating a Function: Example
FUNCTION tax
(v_value IN NUMBER)
RETURN NUMBER
IS
BEGIN
RETURN (v_value * .07);
END;
FUNCTION tax
(v_value IN NUMBER)
RETURN NUMBER
IS
BEGIN
RETURN (v_value * .07);
END;
Return the tax based on the value.Return the tax based on the value.
184
Invoking Functions in SQL Statements
AdvantagesPermit calculations otherwise not easily obtained in SQL.
Increase efficiency of queries.
GuidelinesOnly use stored functions, not procedures.
Single row functions
No DDL statements
Formal parameters must be IN.
185
Calling a Function in a SQL Statement
Valid SQL clausesSelect list of SELECT commandCondition of WHERE and HAVING clauseORDER BY, and GROUP BY clausesVALUES clause of the INSERT commandSET clause of the UPDATE command
186
Invoking Functions in SQL Statements: ExampleEnter a SQL statement with a function call at the Interpreter prompt.
PL/SQL> SELECT total, tax(total)PL/SQL> SELECT total, tax(total)
+> FROM s_ord +> FROM s_ord
+> WHERE id = 100; +> WHERE id = 100;
TOTAL TAX(TOTAL)TOTAL TAX(TOTAL)
------------- ----------------------- ----------
601100.00 42077 601100.00 42077
PL/SQL> SELECT total, tax(total)PL/SQL> SELECT total, tax(total)
+> FROM s_ord +> FROM s_ord
+> WHERE id = 100; +> WHERE id = 100;
TOTAL TAX(TOTAL)TOTAL TAX(TOTAL)
------------- ----------------------- ----------
601100.00 42077 601100.00 42077
187
Retrieving Data: Syntax
Retrieve data from the database with SELECT.
INTO clause is required.Exactly one row must be returned.Full SELECT syntax is available.
SELECTSELECT select_listselect_list
INTOINTO variable_namevariable_name | | record_name record_name
FROMFROM tabletable
WHEREWHERE conditioncondition;;
SELECTSELECT select_listselect_list
INTOINTO variable_namevariable_name | | record_name record_name
FROMFROM tabletable
WHEREWHERE conditioncondition;;
188
Retrieving Data: Example
Retrieve the order date and the ship date for the specified order.
PROCEDURE ship_datePROCEDURE ship_date
(v_ord_id IN NUMBER)(v_ord_id IN NUMBER)
ISIS
v_date_ordered s_ord.date_ordered%TYPE;v_date_ordered s_ord.date_ordered%TYPE;
v_date_shipped s_ord.date_shipped%TYPE; v_date_shipped s_ord.date_shipped%TYPE;
BEGINBEGIN
SELECTSELECT date_ordered, date_shippeddate_ordered, date_shipped
INTOINTO v_date_ordered, v_date_shippedv_date_ordered, v_date_shipped
FROMFROM s_ords_ord
WHEREWHERE id = v_ord_id;id = v_ord_id;
......
END ship_date;END ship_date;
PROCEDURE ship_datePROCEDURE ship_date
(v_ord_id IN NUMBER)(v_ord_id IN NUMBER)
ISIS
v_date_ordered s_ord.date_ordered%TYPE;v_date_ordered s_ord.date_ordered%TYPE;
v_date_shipped s_ord.date_shipped%TYPE; v_date_shipped s_ord.date_shipped%TYPE;
BEGINBEGIN
SELECTSELECT date_ordered, date_shippeddate_ordered, date_shipped
INTOINTO v_date_ordered, v_date_shippedv_date_ordered, v_date_shipped
FROMFROM s_ords_ord
WHEREWHERE id = v_ord_id;id = v_ord_id;
......
END ship_date;END ship_date;
189
Retrieving Data: Example
Return the sum of the salaries for all employees in the specified department.FUNCTION sum_empFUNCTION sum_emp
(v_dept_id IN NUMBER)(v_dept_id IN NUMBER)
RETURN NUMBERRETURN NUMBER
ISIS
v_sum_salary s_emp.salary%TYPE; v_sum_salary s_emp.salary%TYPE;
BEGINBEGIN
SELECTSELECT SUM(salary) SUM(salary) --group function--group function
INTOINTO v_sum_salaryv_sum_salary
FROMFROM s_emps_emp
WHEREWHERE dept_id = v_dept_id;dept_id = v_dept_id;
RETURN (v_sum_salary);RETURN (v_sum_salary);
END sum_emp;END sum_emp;
FUNCTION sum_empFUNCTION sum_emp
(v_dept_id IN NUMBER)(v_dept_id IN NUMBER)
RETURN NUMBERRETURN NUMBER
ISIS
v_sum_salary s_emp.salary%TYPE; v_sum_salary s_emp.salary%TYPE;
BEGINBEGIN
SELECTSELECT SUM(salary) SUM(salary) --group function--group function
INTOINTO v_sum_salaryv_sum_salary
FROMFROM s_emps_emp
WHEREWHERE dept_id = v_dept_id;dept_id = v_dept_id;
RETURN (v_sum_salary);RETURN (v_sum_salary);
END sum_emp;END sum_emp;
190
Retrieving Data: Example
Retrieve all information about the specified department.
PROCEDURE all_deptPROCEDURE all_dept
(v_dept_id IN NUMBER)(v_dept_id IN NUMBER)
ISIS
dept_recorddept_record s_dept%ROWTYPE; s_dept%ROWTYPE;
BEGINBEGIN
SELECTSELECT **
INTOINTO dept_record dept_record --PL/SQL RECORD--PL/SQL RECORD
FROMFROM s_depts_dept
WHEREWHERE id = v_dept_id;id = v_dept_id;
......
END all_dept;END all_dept;
PROCEDURE all_deptPROCEDURE all_dept
(v_dept_id IN NUMBER)(v_dept_id IN NUMBER)
ISIS
dept_recorddept_record s_dept%ROWTYPE; s_dept%ROWTYPE;
BEGINBEGIN
SELECTSELECT **
INTOINTO dept_record dept_record --PL/SQL RECORD--PL/SQL RECORD
FROMFROM s_depts_dept
WHEREWHERE id = v_dept_id;id = v_dept_id;
......
END all_dept;END all_dept;
191
Manipulating Data
Make changes to database tables by using DML commands.
INSERTUPDATEDELETE
192
Inserting Data: ExampleAdd a new order to the S_ORD table for the specified customer.PROCEDURE cust_orderPROCEDURE cust_order
(v_customer_id IN s_ord.customer_id%TYPE)(v_customer_id IN s_ord.customer_id%TYPE)
ISIS
v_date_ordered s_ord.date_ordered%TYPE := SYSDATE;v_date_ordered s_ord.date_ordered%TYPE := SYSDATE;
v_sales_rep_id s_ord.sales_rep_id%TYPE := 11;v_sales_rep_id s_ord.sales_rep_id%TYPE := 11;
v_payment_type s_ord.payment_type%TYPE := 'CASH';v_payment_type s_ord.payment_type%TYPE := 'CASH';
v_order_filled s_ord.order_filled%TYPE := 'N';v_order_filled s_ord.order_filled%TYPE := 'N';
BEGINBEGIN
INSERT INTO s_ord (id, customer_id,INSERT INTO s_ord (id, customer_id,
date_ordered, date_shipped, sales_rep_id, date_ordered, date_shipped, sales_rep_id,
total, payment_type, order_filled)total, payment_type, order_filled)
VALUES (s_ord_id.NEXTVAL, v_customer_id, VALUES (s_ord_id.NEXTVAL, v_customer_id,
v_date_ordered, NULL, v_sales_rep_id,v_date_ordered, NULL, v_sales_rep_id,
0, v_payment_type, v_order_filled);0, v_payment_type, v_order_filled);
END cust_order;END cust_order;
PROCEDURE cust_orderPROCEDURE cust_order
(v_customer_id IN s_ord.customer_id%TYPE)(v_customer_id IN s_ord.customer_id%TYPE)
ISIS
v_date_ordered s_ord.date_ordered%TYPE := SYSDATE;v_date_ordered s_ord.date_ordered%TYPE := SYSDATE;
v_sales_rep_id s_ord.sales_rep_id%TYPE := 11;v_sales_rep_id s_ord.sales_rep_id%TYPE := 11;
v_payment_type s_ord.payment_type%TYPE := 'CASH';v_payment_type s_ord.payment_type%TYPE := 'CASH';
v_order_filled s_ord.order_filled%TYPE := 'N';v_order_filled s_ord.order_filled%TYPE := 'N';
BEGINBEGIN
INSERT INTO s_ord (id, customer_id,INSERT INTO s_ord (id, customer_id,
date_ordered, date_shipped, sales_rep_id, date_ordered, date_shipped, sales_rep_id,
total, payment_type, order_filled)total, payment_type, order_filled)
VALUES (s_ord_id.NEXTVAL, v_customer_id, VALUES (s_ord_id.NEXTVAL, v_customer_id,
v_date_ordered, NULL, v_sales_rep_id,v_date_ordered, NULL, v_sales_rep_id,
0, v_payment_type, v_order_filled);0, v_payment_type, v_order_filled);
END cust_order;END cust_order;
193
Updating Data: Example
Change the ship date for the specified order.
PROCEDURE new_ship_datePROCEDURE new_ship_date
(v_ord_id(v_ord_id ININ s_ord.id%TYPE,s_ord.id%TYPE,
v_ship_datev_ship_date IN s_ord.date_shipped%TYPE) IN s_ord.date_shipped%TYPE)
ISIS
BEGINBEGIN
UPDATEUPDATE s_ords_ord
SETSET date_shipped = v_ship_datedate_shipped = v_ship_date
WHEREWHERE id = v_ord_id;id = v_ord_id;
END new_ship_date;END new_ship_date;
PROCEDURE new_ship_datePROCEDURE new_ship_date
(v_ord_id(v_ord_id ININ s_ord.id%TYPE,s_ord.id%TYPE,
v_ship_datev_ship_date IN s_ord.date_shipped%TYPE) IN s_ord.date_shipped%TYPE)
ISIS
BEGINBEGIN
UPDATEUPDATE s_ords_ord
SETSET date_shipped = v_ship_datedate_shipped = v_ship_date
WHEREWHERE id = v_ord_id;id = v_ord_id;
END new_ship_date;END new_ship_date;
194
Deleting Data: Example
Delete a specified order.
PROCEDURE del_orderPROCEDURE del_order
(v_ord_id IN s_ord.id%TYPE) (v_ord_id IN s_ord.id%TYPE)
ISIS
BEGINBEGIN
DELETE FROM s_ordDELETE FROM s_ord
WHERE id = v_ord_id;WHERE id = v_ord_id;
END del_order;END del_order;
PROCEDURE del_orderPROCEDURE del_order
(v_ord_id IN s_ord.id%TYPE) (v_ord_id IN s_ord.id%TYPE)
ISIS
BEGINBEGIN
DELETE FROM s_ordDELETE FROM s_ord
WHERE id = v_ord_id;WHERE id = v_ord_id;
END del_order;END del_order;