Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

Assume that we have the table Emp (Empno, Ename, Sal, Job, Gender, Tel, Hire_Date, Deptno).

 When we create the table, in order to force the Gender field to be M or F, we use check
constraint:

Create table Emp3 (


Empno Number(5) ,
Ename Varchar2(30) Unique,
Sal Number(6,2) constraint Emp_Sal_nn not null,
Job Varchar2(20),
Gender Char,
Tel Number(7),
Hire_Date Date,
Deptno number(2),
CONSTRAINT Emp_Empno_pk PRIMARY KEY (EMPNO),
CONSTRAINT Emp_Deptno_fk FOREIGN KEY (DEPTNO) REFERENCES DEPT(DEPTNO),
constraint Emp_Gender_cc Check ((Gender = 'M') or (Gender = 'm') or (Gender = 'F') or
(Gender = 'f'))
);

 Unique is a constraint similar to primary key(No duplication is allowed), but unique can be null,
while primary key cannot be null.
 Not Null is a constraint that forces the user to insert a value in this field.
 To Drop the table, we write:
Drop Table Emp3;
(Delete will delete the data, while drop will delete the data AND the table itself).

If the table has a foreign key, we write:

Drop Table dept Cascade Constraints;


or we drop the other tables that refer to this table first.

 Example Insert is:


Insert into Emp Values (1, 'Ali', 'MANAGER', '' , To_Date('12/03/2013','DD/MM/YYYY'),5000,
'', 30);

Commit;

 Example Update:
Update Emp set Sal = 600 where Empno = 1;
Update Emp set Sal = 600; will make all salaries equal 600

 Example Delete:
Delete From Emp; will delete all records
Delete From Emp Where Empno = 1111;
Delete From Emp Where Deptno = 2;

1
 Alter Table Emp
Add (Education varchar2(30) );

 Alter Table Emp


Modify (Education varchar2(40) );

 Alter Table Emp


Drop Column Education;

 Select * from Emp; will retreive all data in all the columns

 Select Empno From Emp; will retrieve all data in Empno.

 Select Empno From Emp where Empno>10; will retreive Empno if it is >10.
* ==> All Rows
No Where Condition ==> All Columns
Select Distinct Deptno From Emp; will display departments without repetition

 Select * From Emp Where Empno >10 AND Sal >400;

 Select * From Emp Where Empno>10 OR Sal >400;

 Select * From Emp Where Tel is Null; will display those who do not have Tel value.

 Select * From Emp Where Tel is not Null; will display those who have Tel value.

 Select * From Emp Where Job in ('Programmer', 'DBA', 'Clerk'); will display those who work as
programmer or DBA or Clerk.

 Select * From Emp Where Sal Between 100 and 500;

 Select * from Emp Where Ename like 'a%' ; will display those whose names start with a

 Select * from Emp Where Ename like '-a%'; will display those whose names second letter is a

 Select * from Emp Where Ename like '---'; will display those whose names has exactly three
characters.
(- means exactly one character, % means zero or more characters).

 Select * from Emp order by Empno; will display records ordered according to Empno from
smaller to larger.

2
 Select * from Emp order by hire_date; will display records ordered according to Hire_Date from
older to newer.

 Select * from Emp order by Ename; will display records ordered according to Ename from A to
Z.

 Select * from Emp order by Empno DESC; will display records ordered according to Empno
from larger to smaller.

 Select * from Emp order by hire_date DESC; will display records ordered according to
Hire_Date from newer to older.

 Select * from Emp order by Ename DESC; will display records ordered according to Ename
from Z to A.

 Select Ename, Sal*0.1 From Emp; will display each employee name and his salary*0.1

 Select Upper(Ename) from Emp; will display employee names in capital letters
(There are many string functions in SQL)

 Select Ename, (Sysdate - Hire_Date)/360 from Emp; will display the employee experience in
years. Sysdate will display the current date. Date - Date will display the number of DAYS
between them.

 Select Avg(Sal) from Emp; will display the average of all salaries. Other functions are Max,
Min, Sum, Count. Example output is 455,34$.

 Select Deptno, Avg(Sal) from Emp Group By Deptno; will display the average of salaries FOR
EACH Department. Example output is
1 488$
2 233$
3 645$

 Select Deptno, Avg(Sal) from Emp Group By Deptno Having Avg(Sal)>300; will display the
average of salaries FOR EACH Department IF it is >300. Example output is
1 488$
2 645$

Assume we have
Emp (Empno, Ename, Sal, Job, Gender, Tel, Hire_Date, Deptno).
Deptnoartment(Deptnono, Loc)

To display each employee name and the location of its department, we use Join:

3
Select Emp.Ename, Department.Loc from Emp, Department Where Department.Deptnono =
Emp.Deptno;

To display the employees who work in the same department like the department of 'Ahmad' , we
use nested query:
Select * From Emp Where Job = (Select Job From Emp Where Ename = 'Ahmad');

To display the employees whose salary is the same like the salary of Ali
Select * From Emp Where Sal = (Select Sal From Emp Where Ename = 'Ali');

Note: we use = when the nested loop returns one value, we use IN when the nested loop returns
more than one value.
Example: Select * From Emp Where Sal = (Select Sal From Emp Where Deptno=1); This
statement will return an error because the inner loop will return more than one value.
Instead, we must write Select * From Emp Where Sal in (Select Sal From Emp Where
Deptno=1);

To Create a view:
Create view x as select Empno, Ename From Emp;
To display the content of the view:
Select * from x;

To Give a privilage to a user:


Grant insert on Emp to user1;
Grant All on Emp to user1;
Grant insert on Emp to public;

To revoke a privilage from a user:


Revoke insert on Emp From user1;

Privileges are: Insert, update, delete, create, alter, drop, select.

4
Objectives

After completing this lesson, you should be able to do


the following:
• Categorize the main database objects
Using DDL Statements
• Review the table structure
to Create and Manage Tables
• List the data types that are available for columns
• Create a simple table
• Understand how constraints are created at the
time of table creation
• Describe how schema objects work

Copyright © 2004, Oracle. All rights reserved. 9-2 Copyright © 2004, Oracle. All rights reserved.

Database Objects Naming Rules

Object Description Table names and column names:


Table Basic unit of storage; composed of rows • Must begin with a letter
View Logically represents subsets of data from • Must be 1–30 characters long
one or more tables
• Must contain only A–Z, a–z, 0–9, _, $, and #
Sequence Generates numeric values
• Must not duplicate the name of another object
Index Improves the performance of some owned by the same user
queries
• Must not be an Oracle server reserved word
Synonym Gives alternative names to objects

9-3 Copyright © 2004, Oracle. All rights reserved. 9-4 Copyright © 2004, Oracle. All rights reserved.

CREATE TABLE Statement Referencing Another User’s Tables

• You must have: • Tables belonging to other users are not in the
– CREATE TABLE privilege user’s schema.
– A storage area • You should use the owner’s name as a prefix to
CREATE TABLE [schema.]table those tables.
(column datatype [DEFAULT expr][, ...]);

• You specify:
– Table name
– Column name, column data type, and column size

USERA USERB
SELECT * SELECT *
FROM userB.employees; FROM userA.employees;

9-5 Copyright © 2004, Oracle. All rights reserved. 9-6 Copyright © 2004, Oracle. All rights reserved.

DEFAULT Option Creating Tables

• Specify a default value for a column during an • Create the table.


insert. CREATE TABLE dept
(deptno NUMBER(2),
... hire_date DATE DEFAULT SYSDATE, ... dname VARCHAR2(14),
loc VARCHAR2(13),
• Literal values, expressions, or SQL functions are create_date DATE DEFAULT SYSDATE);
legal values. Table created.
• Another column’s name or a pseudocolumn are
• Confirm table creation.
illegal values.
• The default data type must match the column data DESCRIBE dept
type.
CREATE TABLE hire_dates
(id NUMBER(8),
hire_date DATE DEFAULT SYSDATE);
Table created. 5
9-7 Copyright © 2004, Oracle. All rights reserved. 9-8 Copyright © 2004, Oracle. All rights reserved.
Data Types Datetime Data Types

Data Type Description


VARCHAR2(size) Variable-length character data You can use several datetime data types:
CHAR(size) Fixed-length character data
Data Type Description
NUMBER(p,s) Variable-length numeric data
TIMESTAMP Date with fractional seconds
DATE Date and time values
INTERVAL YEAR TO Stored as an interval of years
LONG Variable-length character data (up to 2 GB) MONTH and months
CLOB Character data (up to 4 GB) INTERVAL DAY TO Stored as an interval of days, hours,
RAW and LONG Raw binary data SECOND minutes, and seconds
RAW
BLOB Binary data (up to 4 GB)
BFILE Binary data stored in an external file (up to 4 GB)
ROWID A base-64 number system representing the unique
address of a row in its table

9-9 Copyright © 2004, Oracle. All rights reserved. 9-10 Copyright © 2004, Oracle. All rights reserved.

Datetime Data Types Datetime Data Types

• The TIMESTAMP data type is an extension of the • The INTERVAL YEAR TO MONTH data type stores a
DATE data type. period of time using the YEAR and MONTH datetime
• It stores the year, month, and day of the DATE data fields:
type plus hour, minute, and second values as well INTERVAL YEAR [(year_precision)] TO MONTH
as the fractional second value.
• You can optionally specify the time zone. • The INTERVAL DAY TO SECOND data type stores a
TIMESTAMP[(fractional_seconds_precision)] period of time in terms of days, hours, minutes,
and seconds:
TIMESTAMP[(fractional_seconds_precision)] INTERVAL DAY [(day_precision)]
WITH TIME ZONE TO SECOND [(fractional_seconds_precision)]

TIMESTAMP[(fractional_seconds_precision)]
WITH LOCAL TIME ZONE

9-11 Copyright © 2004, Oracle. All rights reserved. 9-12 Copyright © 2004, Oracle. All rights reserved.

Including Constraints Constraint Guidelines

• Constraints enforce rules at the table level. • You can name a constraint, or the Oracle server
• Constraints prevent the deletion of a table if there generates a name by using the SYS_Cn format.
are dependencies. • Create a constraint at either of the following times:
• The following constraint types are valid: – At the same time as the table is created
– NOT NULL – After the table has been created (Alter)
– UNIQUE • Define a constraint at the column or table level.
– PRIMARY KEY • View a constraint in the data dictionary.
– FOREIGN KEY
– CHECK

9-14 Copyright © 2004, Oracle. All rights reserved. 9-15 Copyright © 2004, Oracle. All rights reserved.

Defining Constraints Defining Constraints

• Syntax: • Column-level constraint:


CREATE TABLE [schema.]table CREATE TABLE employees(
(column datatype [DEFAULT expr] employee_id NUMBER(6)
[column_constraint], CONSTRAINT emp_emp_id_pk PRIMARY KEY, 1
... first_name VARCHAR2(20),
[table_constraint][,...]); ...);

• Column-level constraint: • Table-level constraint:


column [CONSTRAINT constraint_name] constraint_type, CREATE TABLE employees(
employee_id NUMBER(6),
• Table-level constraint: first_name VARCHAR2(20),
...
column,... job_id VARCHAR2(10) NOT NULL,
2
[CONSTRAINT constraint_name] constraint_type CONSTRAINT emp_emp_id_pk
6
(column, ...), PRIMARY KEY (EMPLOYEE_ID));

9-16 Copyright © 2004, Oracle. All rights reserved. 9-17 Copyright © 2004, Oracle. All rights reserved.
NOT NULL Constraint UNIQUE Constraint

UNIQUE constraint
Ensures that null values are not permitted for the EMPLOYEES
column:


INSERT INTO
… Allowed
Not allowed:
already exists
NOT NULL constraint NOT NULL Absence of NOT NULL
(No row can contain constraint constraint
a null value for (Any row can contain
this column.) a null value for this
column.)

9-18 Copyright © 2004, Oracle. All rights reserved. 9-19 Copyright © 2004, Oracle. All rights reserved.

UNIQUE Constraint PRIMARY KEY Constraint

Defined at either the table level or the column level: DEPARTMENTS


PRIMARY KEY
CREATE TABLE employees(
employee_id NUMBER(6),
last_name VARCHAR2(25) NOT NULL,
email VARCHAR2(25),
salary NUMBER(8,2),
commission_pct NUMBER(2,2), …
hire_date DATE NOT NULL,
... Not allowed INSERT INTO
(null value)
CONSTRAINT emp_email_uk UNIQUE(email));

Not allowed
(50 already exists)

9-20 Copyright © 2004, Oracle. All rights reserved. 9-21 Copyright © 2004, Oracle. All rights reserved.

FOREIGN KEY Constraint FOREIGN KEY Constraint


DEPARTMENTS

Defined at either the table level or the column level:


PRIMARY
KEY
… CREATE TABLE employees(
employee_id NUMBER(6),
last_name VARCHAR2(25) NOT NULL,
EMPLOYEES email VARCHAR2(25),
FOREIGN salary NUMBER(8,2),
KEY commission_pct NUMBER(2,2),
hire_date DATE NOT NULL,
...
department_id NUMBER(4),
CONSTRAINT emp_dept_fk FOREIGN KEY (department_id)
… Not allowed
REFERENCES departments(department_id),
INSERT INTO (9 does not CONSTRAINT emp_email_uk UNIQUE(email));
exist)
Allowed

9-22 Copyright © 2004, Oracle. All rights reserved. 9-23 Copyright © 2004, Oracle. All rights reserved.

FOREIGN KEY Constraint: CHECK Constraint


Keywords

• FOREIGN KEY: Defines the column in the child • Defines a condition that each row must satisfy
table at the table-constraint level • The following expressions are not allowed:
• REFERENCES: Identifies the table and column – References to CURRVAL, NEXTVAL, LEVEL, and
ROWNUM pseudocolumns
in the parent table
– Calls to SYSDATE, UID, USER, and USERENV
• ON DELETE CASCADE: Deletes the dependent functions
rows in the child table when a row in the – Queries that refer to other values in other rows
parent table is deleted
..., salary NUMBER(2)
• ON DELETE SET NULL: Converts dependent CONSTRAINT emp_salary_min
foreign key values to null CHECK (salary > 0),...

7
9-24 Copyright © 2004, Oracle. All rights reserved. 9-25 Copyright © 2004, Oracle. All rights reserved.
CREATE TABLE: Example Violating Constraints
CREATE TABLE employees
( employee_id NUMBER(6)
CONSTRAINT emp_employee_id PRIMARY KEY
, first_name VARCHAR2(20) UPDATE employees
, last_name VARCHAR2(25)
SET department_id = 55
CONSTRAINT emp_last_name_nn NOT NULL
, email VARCHAR2(25) WHERE department_id = 110;
CONSTRAINT emp_email_nn NOT NULL
CONSTRAINT emp_email_uk UNIQUE
, phone_number VARCHAR2(20) UPDATE employees
, hire_date DATE *
CONSTRAINT emp_hire_date_nn NOT NULL ERROR at line 1:
, job_id VARCHAR2(10) ORA-02291: integrity constraint (HR.EMP_DEPT_FK)
CONSTRAINT emp_job_nn NOT NULL violated - parent key not found
, salary NUMBER(8,2)
CONSTRAINT emp_salary_ck CHECK (salary>0)
, commission_pct NUMBER(2,2)
, manager_id NUMBER(6)
, department_id NUMBER(4)
CONSTRAINT emp_dept_fk REFERENCES
departments (department_id));

9-26 Copyright © 2004, Oracle. All rights reserved. 9-27 Copyright © 2004, Oracle. All rights reserved.

Violating Constraints Creating a Table


by Using a Subquery

You cannot delete a row that contains a primary key • Create a table and insert rows by combining the
that is used as a foreign key in another table. CREATE TABLE statement and the AS subquery
option.
DELETE FROM departments
WHERE department_id = 60; CREATE TABLE table
[(column, column...)]
AS subquery;

DELETE FROM departments


* • Match the number of specified columns to the
ERROR at line 1: number of subquery columns.
ORA-02292: integrity constraint (HR.EMP_DEPT_FK) • Define columns with column names and
violated - child record found
default values.

9-28 Copyright © 2004, Oracle. All rights reserved. 9-29 Copyright © 2004, Oracle. All rights reserved.

Creating a Table ALTER TABLE Statement


by Using a Subquery

CREATE TABLE dept80 Use the ALTER TABLE statement to:


AS
• Add a new column
SELECT employee_id, last_name,
salary*12 ANNSAL, • Modify an existing column
hire_date • Define a default value for the new column
FROM employees
WHERE department_id = 80; • Drop a column
Table created.

DESCRIBE dept80
Eg:
Alter table dept
Drop column dtel;
Alter table dept
add dtel number(10);

9-30 Copyright © 2004, Oracle. All rights reserved. 9-31 Copyright © 2004, Oracle. All rights reserved.

Dropping a Table Summary

• All data and structure in the table are deleted. In this lesson, you should have learned how to use the
• Any pending transactions are committed. CREATE TABLE statement to create a table and include
• All indexes are dropped. constraints.
• All constraints are dropped. • Categorize the main database objects
• You cannot roll back the DROP TABLE statement. • Review the table structure
• List the data types that are available for columns
DROP TABLE dept80;
Table dropped. • Create a simple table
• Understand how constraints are created at the
time of table creation
• Describe how schema objects work

8
9-32 Copyright © 2004, Oracle. All rights reserved. 9-33 Copyright © 2004, Oracle. All rights reserved.
Practice 9: Overview

This practice covers the following topics:


• Creating new tables
• Creating a new table by using the CREATE TABLE Manipulating Data
AS syntax
• Verifying that tables exist
• Dropping tables

9-34 Copyright © 2004, Oracle. All rights reserved. Copyright © 2004, Oracle. All rights reserved.

Objectives Data Manipulation Language (DML)

After completing this lesson, you should be able to do • A DML statement is executed when you:
the following: – Add new rows to a table
• Describe each data manipulation language (DML) – Modify existing rows in a table
statement – Remove existing rows from a table
• Insert rows into a table • A transaction consists of a collection of DML
• Update rows in a table statements that form a logical unit of work.
• Delete rows from a table
• Control transactions

8-2 Copyright © 2004, Oracle. All rights reserved. 8-3 Copyright © 2004, Oracle. All rights reserved.

Adding a New Row to a Table INSERT Statement Syntax


New
DEPARTMENTS row
• Add new rows to a table by using the INSERT
Insert new row
into the statement:
DEPARTMENTS table
INSERT INTO table [(column [, column...])]
VALUES (value [, value...]);

• With this syntax, only one row is inserted at a


time.

8-4 Copyright © 2004, Oracle. All rights reserved. 8-5 Copyright © 2004, Oracle. All rights reserved.

Inserting New Rows Inserting Rows with Null Values

• Insert a new row containing values for each • Implicit method: Omit the column from the
column. column list.
• List values in the default order of the columns in
INSERT INTO departments (department_id,
the table. department_name )
• Optionally, list the columns in the INSERT clause. VALUES (30, 'Purchasing');
1 row created.
INSERT INTO departments(department_id,
department_name, manager_id, location_id) • Explicit method: Specify the NULL keyword in the
VALUES (70, 'Public Relations', 100, 1700); VALUES clause.
1 row created.
INSERT INTO departments
• Enclose character and date values in single VALUES (100, 'Finance', NULL, NULL);
quotation marks. 1 row created.

9
8-6 Copyright © 2004, Oracle. All rights reserved. 8-7 Copyright © 2004, Oracle. All rights reserved.
Inserting Special Values Inserting Specific Date Values

The SYSDATE function records the current date and • Add a new employee.
time. INSERT INTO employees
INSERT INTO employees (employee_id, VALUES (114,
first_name, last_name, 'Den', 'Raphealy',
email, phone_number, 'DRAPHEAL', '515.127.4561',
hire_date, job_id, salary, TO_DATE('FEB 3, 1999', 'MON DD, YYYY'),
commission_pct, manager_id, 'AC_ACCOUNT', 11000, NULL, 100, 30);
department_id) 1 row created.
VALUES (113,
'Louis', 'Popp', • Verify your addition.
'LPOPP', '515.124.4567',
SYSDATE, 'AC_ACCOUNT', 6900,
NULL, 205, 100);
1 row created.

8-8 Copyright © 2004, Oracle. All rights reserved. 8-9 Copyright © 2004, Oracle. All rights reserved.

Creating a Script Copying Rows


from Another Table

• Use & substitution in a SQL statement to prompt • Write your INSERT statement with a subquery:
for values. INSERT INTO sales_reps(id, name, salary, commission_pct)
SELECT employee_id, last_name, salary, commission_pct
• & is a placeholder for the variable value. FROM employees
INSERT INTO departments WHERE job_id LIKE '%REP%';
(department_id, department_name, location_id)
4 rows created.
VALUES (&department_id, '&department_name',&location);

• Do not use the VALUES clause.


• Match the number of columns in the INSERT
clause to those in the subquery.

1 row created.

8-10 Copyright © 2004, Oracle. All rights reserved. 8-11 Copyright © 2004, Oracle. All rights reserved.

Changing Data in a Table UPDATE Statement Syntax

EMPLOYEES • Modify existing rows with the UPDATE statement:


UPDATE table
SET column = value [, column = value, ...]
[WHERE condition];

• Update more than one row at a time (if required).

Update rows in the EMPLOYEES table:

8-12 Copyright © 2004, Oracle. All rights reserved. 8-13 Copyright © 2004, Oracle. All rights reserved.

Updating Rows in a Table Updating Two Columns with a Subquery

• Specific row or rows are modified if you specify Update employee 114’s job and salary to match that of
the WHERE clause: employee 205.
UPDATE employees UPDATE employees
SET department_id = 70 SET job_id = (SELECT job_id
WHERE employee_id = 113; FROM employees
1 row updated. WHERE employee_id = 205),
salary = (SELECT salary
• All rows in the table are modified if you omit the FROM employees
WHERE clause: WHERE employee_id = 205)
UPDATE copy_emp WHERE employee_id = 114;
SET department_id = 110; 1 row updated.
22 rows updated.

10
8-14 Copyright © 2004, Oracle. All rights reserved. 8-15 Copyright © 2004, Oracle. All rights reserved.
Updating Rows Based Removing a Row from a Table
on Another Table

Use subqueries in UPDATE statements to update DEPARTMENTS


rows in a table based on values from another table:
UPDATE copy_emp
SET department_id = (SELECT department_id
FROM employees
WHERE employee_id = 100)
WHERE job_id = (SELECT job_id
FROM employees Delete a row from the DEPARTMENTS table:
WHERE employee_id = 200);
1 row updated.

8-16 Copyright © 2004, Oracle. All rights reserved. 8-17 Copyright © 2004, Oracle. All rights reserved.

DELETE Statement Deleting Rows from a Table

You can remove existing rows from a table by using • Specific rows are deleted if you specify the WHERE
the DELETE statement: clause:

DELETE [FROM] table DELETE FROM departments


[WHERE condition]; WHERE department_name = 'Finance';
1 row deleted.

• All rows in the table are deleted if you omit the


WHERE clause:
DELETE FROM copy_emp;
22 rows deleted.

8-18 Copyright © 2004, Oracle. All rights reserved. 8-19 Copyright © 2004, Oracle. All rights reserved.

Deleting Rows Based TRUNCATE Statement


on Another Table

Use subqueries in DELETE statements to remove rows • Removes all rows from a table, leaving the table
from a table based on values from another table: empty and the table structure intact
DELETE FROM employees • Is a data definition language (DDL) statement
WHERE department_id = rather than a DML statement; cannot easily be
(SELECT department_id undone
FROM departments
WHERE department_name • Syntax:
LIKE '%Public%');
TRUNCATE TABLE table_name;
1 row deleted.

• Example:
TRUNCATE TABLE copy_emp;

8-20 Copyright © 2004, Oracle. All rights reserved. 8-21 Copyright © 2004, Oracle. All rights reserved.

Using a Subquery in an INSERT Statement Using a Subquery in an INSERT Statement

INSERT INTO Verify the results:


(SELECT employee_id, last_name,
email, hire_date, job_id, salary, SELECT employee_id, last_name, email, hire_date,
department_id job_id, salary, department_id
FROM employees FROM employees
WHERE department_id = 50) WHERE department_id = 50;
VALUES (99999, 'Taylor', 'DTAYLOR',
TO_DATE('07-JUN-99', 'DD-MON-RR'),
'ST_CLERK', 5000, 50);

1 row created.

11
8-22 Copyright © 2004, Oracle. All rights reserved. 8-23 Copyright © 2004, Oracle. All rights reserved.
Database Transactions Database Transactions

A database transaction consists of one of the • Begin when the first DML SQL statement is
following: executed
• DML statements that constitute one consistent • End with one of the following events:
change to the data – A COMMIT or ROLLBACK statement is issued.
• One DDL statement – A DDL or DCL statement executes (automatic
• One data control language (DCL) statement commit).
– The user exits iSQL*Plus.
– The system crashes.

8-24 Copyright © 2004, Oracle. All rights reserved. 8-25 Copyright © 2004, Oracle. All rights reserved.

Advantages of COMMIT Controlling Transactions


and ROLLBACK Statements
Time COMMIT

With COMMIT and ROLLBACK statements, you can: Transaction


• Ensure data consistency
DELETE
• Preview data changes before making changes
permanent SAVEPOINT A
• Group logically related operations INSERT

UPDATE

SAVEPOINT B

INSERT
ROLLBACK ROLLBACK ROLLBACK
to SAVEPOINT B to SAVEPOINT A

8-26 Copyright © 2004, Oracle. All rights reserved. 8-27 Copyright © 2004, Oracle. All rights reserved.

Rolling Back Changes to a Marker Implicit Transaction Processing

• Create a marker in a current transaction by using • An automatic commit occurs under the following
the SAVEPOINT statement. circumstances:
• Roll back to that marker by using the ROLLBACK – DDL statement is issued
TO SAVEPOINT statement. – DCL statement is issued
UPDATE... – Normal exit from iSQL*Plus, without explicitly
SAVEPOINT update_done; issuing COMMIT or ROLLBACK statements
Savepoint created. • An automatic rollback occurs under an abnormal
INSERT... termination of iSQL*Plus or a system failure.
ROLLBACK TO update_done;
Rollback complete.

8-28 Copyright © 2004, Oracle. All rights reserved. 8-29 Copyright © 2004, Oracle. All rights reserved.

State of the Data State of the Data After COMMIT


Before COMMIT or ROLLBACK

• The previous state of the data can be recovered. • Data changes are made permanent in the
• The current user can review the results of the DML database.
operations by using the SELECT statement. • The previous state of the data is permanently lost.
• Other users cannot view the results of the DML • All users can view the results.
statements by the current user. • Locks on the affected rows are released; those
• The affected rows are locked; other users cannot rows are available for other users to manipulate.
change the data in the affected rows. • All savepoints are erased.

12
8-30 Copyright © 2004, Oracle. All rights reserved. 8-31 Copyright © 2004, Oracle. All rights reserved.
Committing Data State of the Data After ROLLBACK

• Make the changes: Discard all pending changes by using the ROLLBACK
DELETE FROM employees statement:
WHERE employee_id = 99999; • Data changes are undone.
1 row deleted.
• Previous state of the data is restored.
INSERT INTO departments • Locks on the affected rows are released.
VALUES (290, 'Corporate Tax', NULL, 1700);
1 row created. DELETE FROM copy_emp;
22 rows deleted.
• Commit the changes: ROLLBACK ;
Rollback complete.
COMMIT;
Commit complete.

8-32 Copyright © 2004, Oracle. All rights reserved. 8-33 Copyright © 2004, Oracle. All rights reserved.

State of the Data After ROLLBACK Statement-Level Rollback

DELETE FROM test; • If a single DML statement fails during execution,


25,000 rows deleted. only that statement is rolled back.
ROLLBACK; • The Oracle server implements an implicit
Rollback complete. savepoint.
• All other changes are retained.
DELETE FROM test WHERE id = 100;
1 row deleted. • The user should terminate transactions explicitly
by executing a COMMIT or ROLLBACK statement.
SELECT * FROM test WHERE id = 100;
No rows selected.

COMMIT;
Commit complete.

8-34 Copyright © 2004, Oracle. All rights reserved. 8-35 Copyright © 2004, Oracle. All rights reserved.

Read Consistency Implementation of Read Consistency

• Read consistency guarantees a consistent view of User A


the data at all times. UPDATE employees Data
• Changes made by one user do not conflict with SET salary = 7000 blocks
WHERE last_name = 'Goyal';
changes made by another user.
• Read consistency ensures that on the same data: Undo
segments
– Readers do not wait for writers
– Writers do not wait for readers Changed
SELECT * and
FROM userA.employees; Read- unchanged
consistent data
image Before
change
(“old” data)
User B

8-36 Copyright © 2004, Oracle. All rights reserved. 8-37 Copyright © 2004, Oracle. All rights reserved.

Summary Practice 8: Overview

In this lesson, you should have learned how to use the This practice covers the following topics:
following statements: • Inserting rows into the tables
Function Description • Updating and deleting rows in the table
INSERT Adds a new row to the table • Controlling transactions
UPDATE Modifies existing rows in the table
DELETE Removes existing rows from the table
COMMIT Makes all pending changes permanent
SAVEPOINT Is used to roll back to the savepoint marker
ROLLBACK Discards all pending data changes

13
8-38 Copyright © 2004, Oracle. All rights reserved. 8-39 Copyright © 2004, Oracle. All rights reserved.
Objectives

After completing this lesson, you should be able to do


the following:
• Create simple and complex views
Creating Other Schema Objects
• Retrieve data from views
• Create, maintain, and use sequences
• Create and maintain indexes
• Create private and public synonyms

Copyright © 2004, Oracle. All rights reserved. 10-2 Copyright © 2004, Oracle. All rights reserved.

Database Objects What Is a View?

EMPLOYEES table
Object Description

Table Basic unit of storage; composed of rows


View Logically represents subsets of data from
one or more tables
Sequence Generates numeric values
Index Improves the performance of some
queries
Synonym Gives alternative names to objects

10-3 Copyright © 2004, Oracle. All rights reserved. 10-4 Copyright © 2004, Oracle. All rights reserved.

Advantages of Views Simple Views and Complex Views

To restrict To make complex Feature Simple Views Complex Views


data access queries easy
Number of tables One One or more
Contain functions No Yes
Contain groups of data No Yes
DML operations Yes Not always
through a view

To provide To present
data different views of
independence the same data

10-5 Copyright © 2004, Oracle. All rights reserved. 10-6 Copyright © 2004, Oracle. All rights reserved.

Creating a View Creating a View

• You embed a subquery in the CREATE VIEW • Create the EMPVU80 view, which contains details
statement: of employees in department 80:
CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view CREATE VIEW empvu80
[(alias[, alias]...)] AS SELECT employee_id, last_name, salary
AS subquery FROM employees
[WITH CHECK OPTION [CONSTRAINT constraint]] WHERE department_id = 80;
[WITH READ ONLY [CONSTRAINT constraint]]; View created.
• The subquery can contain complex SELECT • Describe the structure of the view by using the
syntax. iSQL*Plus DESCRIBE command:

DESCRIBE empvu80

14
10-7 Copyright © 2004, Oracle. All rights reserved. 10-8 Copyright © 2004, Oracle. All rights reserved.
Creating a View Retrieving Data from a View

• Create a view by using column aliases in the SELECT *


subquery: FROM salvu50;

CREATE VIEW salvu50


AS SELECT employee_id ID_NUMBER, last_name NAME,
salary*12 ANN_SALARY
FROM employees
WHERE department_id = 50;
View created.

• Select the columns from this view by the given


alias names:

10-9 Copyright © 2004, Oracle. All rights reserved. 10-10 Copyright © 2004, Oracle. All rights reserved.

Modifying a View Creating a Complex View

• Modify the EMPVU80 view by using a CREATE OR Create a complex view that contains group functions
REPLACE VIEW clause. Add an alias for each to display values from two tables:
column name:
CREATE VIEW dept_sum_vu
CREATE OR REPLACE VIEW empvu80
(name, minsal, maxsal, avgsal)
(id_number, name, sal, department_id)
AS SELECT d.department_name, MIN(e.salary),
AS SELECT employee_id, first_name || ' '
MAX(e.salary),AVG(e.salary)
|| last_name, salary, department_id
FROM employees e, departments d
FROM employees
WHERE e.department_id = d.department_id
WHERE department_id = 80;
GROUP BY d.department_name;
View created.
View created.
• Column aliases in the CREATE OR REPLACE VIEW
clause are listed in the same order as the columns
in the subquery.

10-11 Copyright © 2004, Oracle. All rights reserved. 10-12 Copyright © 2004, Oracle. All rights reserved.

Rules for Performing Rules for Performing


DML Operations on a View DML Operations on a View

• You can usually perform DML operations You cannot modify data in a view if it contains:
on simple views. • Group functions
• You cannot remove a row if the view contains the • A GROUP BY clause
following: • The DISTINCT keyword
– Group functions
• The pseudocolumn ROWNUM keyword
– A GROUP BY clause
• Columns defined by expressions
– The DISTINCT keyword
– The pseudocolumn ROWNUM keyword

10-13 Copyright © 2004, Oracle. All rights reserved. 10-14 Copyright © 2004, Oracle. All rights reserved.

Rules for Performing Using the WITH CHECK OPTION Clause


DML Operations on a View

You cannot add data through a view if the view • You can ensure that DML operations performed on
includes: the view stay in the domain of the view by using
• Group functions the WITH CHECK OPTION clause:
CREATE OR REPLACE VIEW empvu20
• A GROUP BY clause
AS SELECT *
• The DISTINCT keyword FROM employees
• The pseudocolumn ROWNUM keyword WHERE department_id = 20
WITH CHECK OPTION CONSTRAINT empvu20_ck ;
• Columns defined by expressions View created.
• NOT NULL columns in the base tables that are not • Any attempt to change the department number for
selected by the view any row in the view fails because it violates the
WITH CHECK OPTION constraint.

15
10-15 Copyright © 2004, Oracle. All rights reserved. 10-16 Copyright © 2004, Oracle. All rights reserved.
Denying DML Operations Denying DML Operations

• You can ensure that no DML operations occur by CREATE OR REPLACE VIEW empvu10
adding the WITH READ ONLY option to your view (employee_number, employee_name, job_title)
AS SELECT employee_id, last_name, job_id
definition.
FROM employees
• Any attempt to perform a DML operation on any WHERE department_id = 10
row in the view results in an Oracle server error. WITH READ ONLY ;
View created.

10-17 Copyright © 2004, Oracle. All rights reserved. 10-18 Copyright © 2004, Oracle. All rights reserved.

Removing a View Practice 10: Overview of Part 1

You can remove a view without losing data because a This practice covers the following topics:
view is based on underlying tables in the database. • Creating a simple view
DROP VIEW view; • Creating a complex view
• Creating a view with a check constraint
DROP VIEW empvu80;
• Attempting to modify data in the view
View dropped.
• Removing views

10-19 Copyright © 2004, Oracle. All rights reserved. 10-20 Copyright © 2004, Oracle. All rights reserved.

Sequences Sequences

Object Description A sequence:


Table Basic unit of storage; composed of rows • Can automatically generate unique numbers
View Logically represents subsets of data from • Is a sharable object
one or more tables • Can be used to create a primary key value
Sequence Generates numeric values • Replaces application code
Index Improves the performance of some • Speeds up the efficiency of accessing sequence
queries
values when cached in memory
Synonym Gives alternative names to objects

2 4 6 8 10
1 3 5 7 9

10-21 Copyright © 2004, Oracle. All rights reserved. 10-22 Copyright © 2004, Oracle. All rights reserved.

CREATE SEQUENCE Statement: Creating a Sequence


Syntax

Define a sequence to generate sequential numbers • Create a sequence named DEPT_DEPTID_SEQ to


automatically: be used for the primary key of the DEPARTMENTS
table.
CREATE SEQUENCE sequence
[INCREMENT BY n] • Do not use the CYCLE option.
[START WITH n]
CREATE SEQUENCE dept_deptid_seq
[{MAXVALUE n | NOMAXVALUE}]
INCREMENT BY 10
[{MINVALUE n | NOMINVALUE}]
START WITH 120
[{CYCLE | NOCYCLE}]
MAXVALUE 9999
[{CACHE n | NOCACHE}];
NOCACHE
NOCYCLE;
Sequence created.

16
10-23 Copyright © 2004, Oracle. All rights reserved. 10-24 Copyright © 2004, Oracle. All rights reserved.
NEXTVAL and CURRVAL Pseudocolumns Using a Sequence

• NEXTVAL returns the next available sequence • Insert a new department named “Support” in
value. It returns a unique value every time it is location ID 2500:
referenced, even for different users.
INSERT INTO departments(department_id,
• CURRVAL obtains the current sequence value. department_name, location_id)
• NEXTVAL must be issued for that sequence before VALUES (dept_deptid_seq.NEXTVAL,
CURRVAL contains a value. 'Support', 2500);
1 row created.

• View the current value for the DEPT_DEPTID_SEQ


sequence:
SELECT dept_deptid_seq.CURRVAL
FROM dual;

10-25 Copyright © 2004, Oracle. All rights reserved. 10-26 Copyright © 2004, Oracle. All rights reserved.

Caching Sequence Values Modifying a Sequence

• Caching sequence values in memory gives faster Change the increment value, maximum value,
access to those values. minimum value, cycle option, or cache option:
• Gaps in sequence values can occur when:
ALTER SEQUENCE dept_deptid_seq
– A rollback occurs
INCREMENT BY 20
– The system crashes MAXVALUE 999999
– A sequence is used in another table NOCACHE
NOCYCLE;
Sequence altered.

10-27 Copyright © 2004, Oracle. All rights reserved. 10-28 Copyright © 2004, Oracle. All rights reserved.

Guidelines for Modifying Indexes


a Sequence

• You must be the owner or have the ALTER Object Description


privilege for the sequence.
Table Basic unit of storage; composed of rows
• Only future sequence numbers are affected.
View Logically represents subsets of data from
• The sequence must be dropped and one or more tables
re-created to restart the sequence at a different Sequence Generates numeric values
number.
Index Improves the performance of some
• Some validation is performed. queries
• To remove a sequence, use the DROP statement: Synonym Gives alternative names to objects

DROP SEQUENCE dept_deptid_seq;


Sequence dropped.

10-29 Copyright © 2004, Oracle. All rights reserved. 10-30 Copyright © 2004, Oracle. All rights reserved.

Indexes How Are Indexes Created?

An index: • Automatically: A unique index is created


• Is a schema object automatically when you define a PRIMARY KEY or
UNIQUE constraint in a table definition.
• Is used by the Oracle server to speed up the
retrieval of rows by using a pointer
• Can reduce disk I/O by using a rapid path access
method to locate data quickly
• Is independent of the table that it indexes • Manually: Users can create nonunique indexes on
• Is used and maintained automatically by the columns to speed up access to the rows.
Oracle server

17
10-31 Copyright © 2004, Oracle. All rights reserved. 10-32 Copyright © 2004, Oracle. All rights reserved.
Creating an Index Index Creation Guidelines

Create an index when:


• Create an index on one or more columns:  A column contains a wide range of values
 A column contains a large number of null values
CREATE INDEX index_name
 One or more columns are frequently used together in a WHERE
ON table (column[, column]...);
clause or a join condition
 The table is large and most queries are expected to retrieve less
• Improve the speed of query access to the than 2% to 4% of the rows in the table
LAST_NAME column in the EMPLOYEES table: Do not create an index when:
 The columns are not often used as a condition in the query
CREATE INDEX emp_last_name_idx
ON employees(last_name);  The table is small or most queries are expected to retrieve more
than 2% to 4% of the rows in the table
Index created.
 The table is updated frequently

 The indexed columns are referenced as part of an expression

10-33 Copyright © 2004, Oracle. All rights reserved. 10-34 Copyright © 2004, Oracle. All rights reserved.

Removing an Index Synonyms

• Remove an index from the data dictionary by Object Description


using the DROP INDEX command:
Table Basic unit of storage; composed of rows
DROP INDEX index; View Logically represents subsets of data from
one or more tables
• Remove the UPPER_LAST_NAME_IDX index from Sequence Generates numeric values
the data dictionary: Index Improves the performance of some
queries
DROP INDEX emp_last_name_idx;
Index dropped. Synonym Gives alternative names to objects

• To drop an index, you must be the owner of the


index or have the DROP ANY INDEX privilege.

10-35 Copyright © 2004, Oracle. All rights reserved. 10-36 Copyright © 2004, Oracle. All rights reserved.

Synonyms Creating and Removing Synonyms

Simplify access to objects by creating a synonym • Create a shortened name for the DEPT_SUM_VU
(another name for an object). With synonyms, you can: view:
• Create an easier reference to a table that is owned CREATE SYNONYM d_sum
by another user FOR dept_sum_vu;
• Shorten lengthy object names Synonym Created.

CREATE [PUBLIC] SYNONYM synonym • Drop a synonym:


FOR object;
DROP SYNONYM d_sum;
Synonym dropped.

10-37 Copyright © 2004, Oracle. All rights reserved. 10-38 Copyright © 2004, Oracle. All rights reserved.

Summary Practice 10: Overview of Part 2

In this lesson, you should have learned how to: This practice covers the following topics:
• Create, use, and remove views • Creating sequences
• Automatically generate sequence numbers by • Using sequences
using a sequence generator • Creating nonunique indexes
• Create indexes to improve query retrieval speed • Creating synonyms
• Use synonyms to provide alternative names for
objects

18
10-39 Copyright © 2004, Oracle. All rights reserved. 10-40 Copyright © 2004, Oracle. All rights reserved.
Objectives

After completing this lesson, you should be able to do


the following:
• List the capabilities of SQL SELECT statements
Retrieving Data Using
• Execute a basic SELECT statement
the SQL SELECT Statement • Differentiate between SQL statements and
iSQL*Plus commands

Copyright © 2004, Oracle. All rights reserved. 1-2 Copyright © 2004, Oracle. All rights reserved.

Capabilities of SQL SELECT Statements Basic SELECT Statement

Projection Selection SELECT *|{[DISTINCT] column|expression [alias],...}


FROM table;

• SELECT identifies the columns to be displayed


• FROM identifies the table containing those columns

Table 1 Table 1

Join

Table 1 Table 2

1-3 Copyright © 2004, Oracle. All rights reserved. 1-4 Copyright © 2004, Oracle. All rights reserved.

Selecting All Columns Selecting Specific Columns

SELECT * SELECT department_id, location_id


FROM departments; FROM departments;

1-5 Copyright © 2004, Oracle. All rights reserved. 1-6 Copyright © 2004, Oracle. All rights reserved.

Writing SQL Statements Column Heading Defaults

• SQL statements are not case-sensitive. • iSQL*Plus:


• SQL statements can be on one or more lines. – Default heading alignment: Center
• Keywords cannot be abbreviated or split – Default heading display: Uppercase
across lines. • SQL*Plus:
• Clauses are usually placed on separate lines. – Character and Date column headings are left-
aligned
• Indents are used to enhance readability.
– Number column headings are right-aligned
• In iSQL*Plus, SQL statements can optionally be
– Default heading display: Uppercase
terminated by a semicolon (;). Semicolons are
required if you execute multiple SQL statements.
• In SQL*plus, you are required to end each SQL
statement with a semicolon (;).
19
1-7 Copyright © 2004, Oracle. All rights reserved. 1-8 Copyright © 2004, Oracle. All rights reserved.
Arithmetic Expressions Using Arithmetic Operators

Create expressions with number and date data by SELECT last_name, salary, salary + 300
using arithmetic operators. FROM employees;

Operator Description
+ Add
- Subtract
* Multiply
/ Divide …

1-9 Copyright © 2004, Oracle. All rights reserved. 1-10 Copyright © 2004, Oracle. All rights reserved.

Operator Precedence Defining a Null Value

SELECT last_name, salary, 12*salary+100 • A null is a value that is unavailable, unassigned,


FROM employees; 1 unknown, or inapplicable.
• A null is not the same as a zero or a blank space.
SELECT last_name, job_id, salary, commission_pct
… FROM employees;

SELECT last_name, salary, 12*(salary+100)


FROM employees;
2

… …

1-11 Copyright © 2004, Oracle. All rights reserved. 1-12 Copyright © 2004, Oracle. All rights reserved.

Null Values Defining a Column Alias


in Arithmetic Expressions

Arithmetic expressions containing a null value A column alias:


evaluate to null. • Renames a column heading
SELECT last_name, 12*salary*commission_pct • Is useful with calculations
FROM employees; • Immediately follows the column name (There can
also be the optional AS keyword between the
column name and alias.)
… • Requires double quotation marks if it contains
spaces or special characters or if it is case-
sensitive

1-13 Copyright © 2004, Oracle. All rights reserved. 1-14 Copyright © 2004, Oracle. All rights reserved.

Using Column Aliases Concatenation Operator

SELECT last_name AS name, commission_pct comm A concatenation operator:


FROM employees;
• Links columns or character strings to other
columns
• Is represented by two vertical bars (||)
… • Creates a resultant column that is a character
expression
SELECT last_name "Name" , salary*12 "Annual Salary"
SELECT last_name||job_id AS "Employees"
FROM employees;
FROM employees;

… …
20
1-15 Copyright © 2004, Oracle. All rights reserved. 1-16 Copyright © 2004, Oracle. All rights reserved.
Literal Character Strings Using Literal Character Strings

• A literal is a character, a number, or a date that is


SELECT last_name ||' is a '||job_id
included in the SELECT statement. AS "Employee Details"
• Date and character literal values must be enclosed FROM employees;
by single quotation marks.
• Each character string is output once for each
row returned.

1-17 Copyright © 2004, Oracle. All rights reserved. 1-18 Copyright © 2004, Oracle. All rights reserved.

Alternative Quote (q) Operator Duplicate Rows

• Specify your own quotation mark delimiter The default display of queries is all rows, including
• Choose any delimiter duplicate rows.
• Increase readability and usability SELECT department_id
1
FROM employees;
SELECT department_name ||
q'[, it's assigned Manager Id: ]'
|| manager_id
AS "Department and Manager" …
FROM departments;
SELECT DISTINCT department_id
FROM employees; 2


1-19 Copyright © 2004, Oracle. All rights reserved. 1-20 Copyright © 2004, Oracle. All rights reserved.

SQL and iSQL*Plus Interaction SQL Statements Versus


iSQL*Plus Commands
SQL iSQL*Plus
• A language • An environment
SQL statements
Oracle • ANSI standard • Oracle-proprietary
server
• Keyword cannot be • Keywords can be
Internet abbreviated. abbreviated.
browser
• Statements manipulate • Commands do not allow
data and table definitions manipulation of values in
in the database. the database.
iSQL*Plus Query results
commands • Runs on a browser
• Centrally loaded; does not
Formatted report have to be implemented
Client on each machine

SQL iSQL*Plus
statements commands

1-21 Copyright © 2004, Oracle. All rights reserved. 1-22 Copyright © 2004, Oracle. All rights reserved.

Overview of iSQL*Plus Logging In to iSQL*Plus

After you log in to iSQL*Plus, you can: From your browser environment:
• Describe table structures
• Enter, execute, and edit SQL statements
• Save or append SQL statements to files
• Execute or edit statements that are stored in
saved script files

21
1-23 Copyright © 2004, Oracle. All rights reserved. 1-24 Copyright © 2004, Oracle. All rights reserved.
iSQL*Plus Environment Displaying Table Structure
8 9

Use the iSQL*Plus DESCRIBE command to display the


7 structure of a table:

DESC[RIBE] tablename

2 3 4 5

1-25 Copyright © 2004, Oracle. All rights reserved. 1-26 Copyright © 2004, Oracle. All rights reserved.

Displaying Table Structure Interacting with Script Files

DESCRIBE employees

SELECT last_name, hire_date, salary


FROM employees; 1

1-27 Copyright © 2004, Oracle. All rights reserved. 1-28 Copyright © 2004, Oracle. All rights reserved.

Interacting with Script Files Interacting with Script Files

1-29 Copyright © 2004, Oracle. All rights reserved. 1-30 Copyright © 2004, Oracle. All rights reserved.

Interacting with Script Files iSQL*Plus History Page

D:\TEMP\emp_data.sql

1
3
22
1-31 Copyright © 2004, Oracle. All rights reserved. 1-32 Copyright © 2004, Oracle. All rights reserved.
iSQL*Plus History Page Setting iSQL*Plus Preferences

3
1

2
4 3

1-33 Copyright © 2004, Oracle. All rights reserved. 1-34 Copyright © 2004, Oracle. All rights reserved.

Setting the Output Location Preference Summary


2
In this lesson, you should have learned how to:
• Write a SELECT statement that:
– Returns all rows and columns from a table
– Returns specified columns from a table
– Uses column aliases to display more descriptive
column headings
• Use the iSQL*Plus environment to write, save, and
execute SQL statements and iSQL*Plus
commands

1 SELECT *|{[DISTINCT] column|expression [alias],...}


FROM table;

1-35 Copyright © 2004, Oracle. All rights reserved. 1-36 Copyright © 2004, Oracle. All rights reserved.

Practice 1: Overview

This practice covers the following topics:


• Selecting all data from different tables
• Describing the structure of tables Restricting and Sorting Data
• Performing arithmetic calculations and specifying
column names
• Using iSQL*Plus

1-37 Copyright © 2004, Oracle. All rights reserved. Copyright © 2004, Oracle. All rights reserved.

Objectives Limiting Rows Using a Selection

After completing this lesson, you should be able to do EMPLOYEES


the following:
• Limit the rows that are retrieved by a query
• Sort the rows that are retrieved by a query
• Use ampersand substitution in iSQL*Plus to
restrict and sort output at run time …

“retrieve all
employees in
department 90”

23
2-2 Copyright © 2004, Oracle. All rights reserved. 2-3 Copyright © 2004, Oracle. All rights reserved.
Limiting the Rows That Are Selected Using the WHERE Clause

• Restrict the rows that are returned by using the SELECT employee_id, last_name, job_id, department_id
WHERE clause: FROM employees
WHERE department_id = 90 ;
SELECT *|{[DISTINCT] column|expression [alias],...}
FROM table
[WHERE condition(s)];

• The WHERE clause follows the FROM clause.

2-4 Copyright © 2004, Oracle. All rights reserved. 2-5 Copyright © 2004, Oracle. All rights reserved.

Character Strings and Dates Comparison Conditions

• Character strings and date values are enclosed by Operator Meaning


single quotation marks. = Equal to
• Character values are case-sensitive, and date > Greater than
values are format-sensitive. >= Greater than or equal to
• The default date format is DD-MON-RR. < Less than
<= Less than or equal to
SELECT last_name, job_id, department_id
<> Not equal to
FROM employees
WHERE last_name = 'Whalen' ; BETWEEN Between two values
...AND... (inclusive)
IN(set) Match any of a list of values
LIKE Match a character pattern
IS NULL Is a null value

2-6 Copyright © 2004, Oracle. All rights reserved. 2-7 Copyright © 2004, Oracle. All rights reserved.

Using Comparison Conditions Using the BETWEEN Condition

SELECT last_name, salary Use the BETWEEN condition to display rows based on a
FROM employees range of values:
WHERE salary <= 3000 ;
SELECT last_name, salary
FROM employees
WHERE salary BETWEEN 2500 AND 3500 ;

Lower limit Upper limit

2-8 Copyright © 2004, Oracle. All rights reserved. 2-9 Copyright © 2004, Oracle. All rights reserved.

Using the IN Condition Using the LIKE Condition

Use the IN membership condition to test for values in • Use the LIKE condition to perform wildcard
a list: searches of valid search string values.
SELECT employee_id, last_name, salary, manager_id • Search conditions can contain either literal
FROM employees characters or numbers:
WHERE manager_id IN (100, 101, 201) ;
– % denotes zero or many characters.
– _ denotes one character.

SELECT first_name
FROM employees
WHERE first_name LIKE 'S%' ;

24
2-10 Copyright © 2004, Oracle. All rights reserved. 2-11 Copyright © 2004, Oracle. All rights reserved.
Using the LIKE Condition Using the NULL Conditions

• You can combine pattern-matching characters: Test for nulls with the IS NULL operator.
SELECT last_name SELECT last_name, manager_id
FROM employees FROM employees
WHERE last_name LIKE '_o%' ; WHERE manager_id IS NULL ;

• You can use the ESCAPE identifier to search for the


actual % and _ symbols.

2-12 Copyright © 2004, Oracle. All rights reserved. 2-13 Copyright © 2004, Oracle. All rights reserved.

Logical Conditions Using the AND Operator

Operator Meaning AND requires both conditions to be true:


AND Returns TRUE if both component SELECT employee_id, last_name, job_id, salary
conditions are true FROM employees
OR Returns TRUE if either component WHERE salary >=10000
condition is true AND job_id LIKE '%MAN%' ;
NOT Returns TRUE if the following
condition is false

2-14 Copyright © 2004, Oracle. All rights reserved. 2-15 Copyright © 2004, Oracle. All rights reserved.

Using the OR Operator Using the NOT Operator

OR requires either condition to be true: SELECT last_name, job_id


FROM employees
SELECT employee_id, last_name, job_id, salary WHERE job_id
FROM employees NOT IN ('IT_PROG', 'ST_CLERK', 'SA_REP') ;
WHERE salary >= 10000
OR job_id LIKE '%MAN%' ;

2-16 Copyright © 2004, Oracle. All rights reserved. 2-17 Copyright © 2004, Oracle. All rights reserved.

Rules of Precedence Rules of Precedence

SELECT last_name, job_id, salary


Operator Meaning FROM employees
1 Arithmetic operators WHERE job_id = 'SA_REP' 1
OR job_id = 'AD_PRES'
2 Concatenation operator AND salary > 15000;
3 Comparison conditions
4 IS [NOT] NULL, LIKE, [NOT] IN
5 [NOT] BETWEEN
6 Not equal to
SELECT last_name, job_id, salary
7 NOT logical condition
FROM employees
8 AND logical condition WHERE (job_id = 'SA_REP' 2
OR job_id = 'AD_PRES')
9 OR logical condition
AND salary > 15000;
You can use parentheses to override rules of precedence.
25
2-18 Copyright © 2004, Oracle. All rights reserved. 2-19 Copyright © 2004, Oracle. All rights reserved.
Using the ORDER BY Clause Sorting

• Sort retrieved rows with the ORDER BY clause:


• Sorting in descending order:
– ASC: ascending order, default
SELECT last_name, job_id, department_id, hire_date
– DESC: descending order FROM employees
ORDER BY hire_date DESC ; 1
• The ORDER BY clause comes last in the SELECT
statement: • Sorting by column alias:
SELECT last_name, job_id, department_id, hire_date
SELECT employee_id, last_name, salary*12 annsal
FROM employees
FROM employees 2
ORDER BY hire_date ;
ORDER BY annsal ;

• Sorting by multiple columns:


SELECT last_name, department_id, salary
FROM employees 3
… ORDER BY department_id, salary DESC;

2-20 Copyright © 2004, Oracle. All rights reserved. 2-21 Copyright © 2004, Oracle. All rights reserved.

Substitution Variables Substitution Variables

... salary = ? … • Use iSQL*Plus substitution variables to:


… department_id = ? … – Temporarily store values with single-ampersand (&)
... last_name = ? ... and double-ampersand (&&) substitution
• Use substitution variables to supplement the
I want
to query
following:
different – WHERE conditions
values. – ORDER BY clauses
– Column expressions
– Table names
– Entire SELECT statements

2-22 Copyright © 2004, Oracle. All rights reserved. 2-23 Copyright © 2004, Oracle. All rights reserved.

Using the & Substitution Variable Using the & Substitution Variable

Use a variable prefixed with an ampersand (&) to


prompt the user for a value:
SELECT employee_id, last_name, salary, department_id
101
FROM employees
WHERE employee_id = &employee_num ;

1
2

2-24 Copyright © 2004, Oracle. All rights reserved. 2-25 Copyright © 2004, Oracle. All rights reserved.

Character and Date Values Specifying Column Names,


with Substitution Variables Expressions, and Text

Use single quotation marks for date and character SELECT employee_id, last_name, job_id,&column_name
values: FROM employees
WHERE &condition
SELECT last_name, department_id, salary*12 ORDER BY &order_column ;
FROM employees
WHERE job_id = '&job_title' ;

salary

salary > 15000

last_name

26
2-26 Copyright © 2004, Oracle. All rights reserved. 2-27 Copyright © 2004, Oracle. All rights reserved.
Using the && Substitution Variable Using the iSQL*Plus DEFINE Command

Use the double ampersand (&&) if you want to reuse • Use the iSQL*Plus DEFINE command to create and
the variable value without prompting the user each assign a value to a variable.
time: • Use the iSQL*Plus UNDEFINE command to remove
SELECT employee_id, last_name, job_id, &&column_name
a variable.
FROM employees
ORDER BY &column_name ;
DEFINE employee_num = 200

SELECT employee_id, last_name, salary, department_id


FROM employees
WHERE employee_id = &employee_num ;

UNDEFINE employee_num

2-28 Copyright © 2004, Oracle. All rights reserved. 2-29 Copyright © 2004, Oracle. All rights reserved.

Using the VERIFY Command Summary

Use the VERIFY command to toggle the display of the In this lesson, you should have learned how to:
substitution variable, both before and after iSQL*Plus • Use the WHERE clause to restrict rows of output:
replaces substitution variables with values: – Use the comparison conditions
SET VERIFY ON
– Use the BETWEEN, IN, LIKE, and NULL conditions
SELECT employee_id, last_name, salary, department_id – Apply the logical AND, OR, and NOT operators
FROM employees • Use the ORDER BY clause to sort rows of output:
WHERE employee_id = &employee_num;
SELECT *|{[DISTINCT] column|expression [alias],...}
FROM table
[WHERE condition(s)]
[ORDER BY {column, expr, alias} [ASC|DESC]] ;
old 3: WHERE employee_id = &employee_num
new 3: WHERE employee_id = 200 • Use ampersand substitution in iSQL*Plus to
restrict and sort output at run time

2-30 Copyright © 2004, Oracle. All rights reserved. 2-31 Copyright © 2004, Oracle. All rights reserved.

Practice 2: Overview

This practice covers the following topics:


• Selecting data and changing the order of
the rows that are displayed
Using Single-Row Functions to
• Restricting rows by using the WHERE clause
• Sorting rows by using the ORDER BY clause
Customize Output
• Using substitution variables to add flexibility to
your SQL SELECT statements

2-32 Copyright © 2004, Oracle. All rights reserved. Copyright © 2004, Oracle. All rights reserved.

Objectives SQL Functions

After completing this lesson, you should be able to do Input Output


the following:
Function
• Describe various types of functions that are
available in SQL
arg 1 Function performs
• Use character, number, and date functions in action
SELECT statements arg 2
• Describe the use of conversion functions Result
value

arg n

27
3-2 Copyright © 2004, Oracle. All rights reserved. 3-3 Copyright © 2004, Oracle. All rights reserved.
Two Types of SQL Functions Single-Row Functions

Single-row functions:
• Manipulate data items
Functions
• Accept arguments and return one value
• Act on each row that is returned
• Return one result per row
• May modify the data type
Single-row Multiple-row • Can be nested
functions functions
• Accept arguments that can be a column or an
Return one result Return one result expression
per row per set of rows
function_name [(arg1, arg2,...)]

3-4 Copyright © 2004, Oracle. All rights reserved. 3-5 Copyright © 2004, Oracle. All rights reserved.

Single-Row Functions Character Functions

Character Character
functions

Single-row
General Number Character-manipulation
functions Case-manipulation
functions functions

LOWER CONCAT
UPPER SUBSTR
INITCAP LENGTH
Conversion Date INSTR
LPAD | RPAD
TRIM
REPLACE

3-6 Copyright © 2004, Oracle. All rights reserved. 3-7 Copyright © 2004, Oracle. All rights reserved.

Case-Manipulation Functions Using Case-Manipulation Functions

These functions convert case for character strings: Display the employee number, name, and department
Function Result number for employee Higgins:
LOWER('SQL Course') sql course
SELECT employee_id, last_name, department_id
UPPER('SQL Course') SQL COURSE FROM employees
INITCAP('SQL Course') Sql Course WHERE last_name = 'higgins';
no rows selected

SELECT employee_id, last_name, department_id


FROM employees
WHERE LOWER(last_name) = 'higgins';

3-9 Copyright © 2004, Oracle. All rights reserved. 3-10 Copyright © 2004, Oracle. All rights reserved.

Character-Manipulation Functions Using the Character-Manipulation


Functions

These functions manipulate character strings: 1


Function Result
SELECT employee_id, CONCAT(first_name, last_name) NAME,
CONCAT('Hello', 'World') HelloWorld job_id, LENGTH (last_name), 2
SUBSTR('HelloWorld',1,5) Hello INSTR(last_name, 'a') "Contains 'a'?"
FROM employees 3
LENGTH('HelloWorld') 10 WHERE SUBSTR(job_id, 4) = 'REP';
INSTR('HelloWorld', 'W') 6
LPAD(salary,10,'*') *****24000
RPAD(salary, 10, '*') 24000*****
REPLACE BLACK and BLUE
('JACK and JUE','J','BL')
TRIM('H' FROM 'HelloWorld') elloWorld
1 2 3
28
3-11 Copyright © 2004, Oracle. All rights reserved. 3-12 Copyright © 2004, Oracle. All rights reserved.
Number Functions Using the ROUND Function

• ROUND: Rounds value to specified decimal 1 2


• TRUNC: Truncates value to specified decimal
SELECT ROUND(45.923,2), ROUND(45.923,0),
• MOD: Returns remainder of division ROUND(45.923,-1) 3
FROM DUAL;
Function Result
ROUND(45.926, 2) 45.93
TRUNC(45.926, 2) 45.92
MOD(1600, 300) 100
1 2 3
DUAL is a dummy table that you can use to view results
from functions and calculations.

3-13 Copyright © 2004, Oracle. All rights reserved. 3-14 Copyright © 2004, Oracle. All rights reserved.

Using the TRUNC Function Using the MOD Function

1 2 For all employees with job title of Sales Representative,


calculate the remainder of the salary after it is divided
SELECT TRUNC (45.923,2), TRUNC (45.923,0), by 5,000.
TRUNC(45.923,-1) 3
FROM DUAL; SELECT last_name, salary, MOD(salary, 5000)
FROM employees
WHERE job_id = 'SA_REP';

1 2 3

3-15 Copyright © 2004, Oracle. All rights reserved. 3-16 Copyright © 2004, Oracle. All rights reserved.

Working with Dates Working with Dates

• The Oracle database stores dates in an internal numeric


format: century, year, month, day, hours, minutes, and SYSDATE is a function that returns:
seconds.
• Date
• The default date display format is DD-MON-RR.
– Enables you to store 21st-century dates in the
• Time
20th century by specifying only the last two digits
of the year
– Enables you to store 20th-century dates in the
21st century in the same way

SELECT last_name, hire_date


FROM employees
WHERE hire_date < '01-FEB-88';

3-17 Copyright © 2004, Oracle. All rights reserved. 3-19 Copyright © 2004, Oracle. All rights reserved.

Arithmetic with Dates Using Arithmetic Operators


with Dates

• Add or subtract a number to or from a date for a SELECT last_name, (SYSDATE-hire_date)/7 AS WEEKS
resultant date value. FROM employees
WHERE department_id = 90;
• 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.

29
3-20 Copyright © 2004, Oracle. All rights reserved. 3-21 Copyright © 2004, Oracle. All rights reserved.
Date Functions Using Date Functions

Function Result Function Result


MONTHS_BETWEEN Number of months between two dates MONTHS_BETWEEN 19.6774194
ADD_MONTHS Add calendar months to date ('01-SEP-95','11-JAN-94')
ADD_MONTHS ('11-JAN-94',6) '11-JUL-94'
NEXT_DAY Next day of the date specified
LAST_DAY Last day of the month NEXT_DAY ('01-SEP-95','FRIDAY') '08-SEP-95'
LAST_DAY ('01-FEB-95') '28-FEB-95'
ROUND Round date
TRUNC Truncate date

3-22 Copyright © 2004, Oracle. All rights reserved. 3-23 Copyright © 2004, Oracle. All rights reserved.

Using Date Functions Practice 3: Overview of Part 1

Assume SYSDATE = '25-JUL-03': This practice covers the following topics:


Function Result • Writing a query that displays the current date
ROUND(SYSDATE,'MONTH') 01-AUG-03
• Creating queries that require the use of numeric,
ROUND(SYSDATE ,'YEAR') 01-JAN-04 character, and date functions
TRUNC(SYSDATE ,'MONTH') 01-JUL-03 • Performing calculations of years and months of
TRUNC(SYSDATE ,'YEAR') 01-JAN-03 service for an employee

3-24 Copyright © 2004, Oracle. All rights reserved. 3-25 Copyright © 2004, Oracle. All rights reserved.

Conversion Functions Implicit Data Type Conversion

Data type For assignments, the Oracle server can automatically


conversion convert the following:

From To
VARCHAR2 or CHAR NUMBER
Implicit data type Explicit data type
conversion conversion VARCHAR2 or CHAR DATE
NUMBER VARCHAR2
DATE VARCHAR2

3-26 Copyright © 2004, Oracle. All rights reserved. 3-27 Copyright © 2004, Oracle. All rights reserved.

Implicit Data Type Conversion Explicit Data Type Conversion

For expression evaluation, the Oracle Server can TO_NUMBER TO_DATE


automatically convert the following:

From To
VARCHAR2 or CHAR NUMBER
VARCHAR2 or CHAR DATE
NUMBER CHARACTER DATE

TO_CHAR TO_CHAR

30
3-28 Copyright © 2004, Oracle. All rights reserved. 3-29 Copyright © 2004, Oracle. All rights reserved.

You might also like