Professional Documents
Culture Documents
SQL 1 30
SQL 1 30
When we create the table, in order to force the Gender field to be M or F, we use check
constraint:
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).
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) );
Select * from Emp; will retreive all data in all the columns
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 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 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;
4
Objectives
Copyright © 2004, Oracle. All rights reserved. 9-2 Copyright © 2004, Oracle. All rights reserved.
9-3 Copyright © 2004, Oracle. All rights reserved. 9-4 Copyright © 2004, Oracle. All rights reserved.
• 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.
9-9 Copyright © 2004, Oracle. All rights reserved. 9-10 Copyright © 2004, Oracle. All rights reserved.
• 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.
• 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.
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.
Not allowed
(50 already exists)
9-20 Copyright © 2004, Oracle. All rights reserved. 9-21 Copyright © 2004, Oracle. All rights reserved.
9-22 Copyright © 2004, Oracle. All rights reserved. 9-23 Copyright © 2004, Oracle. All rights reserved.
• 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.
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;
9-28 Copyright © 2004, Oracle. All rights reserved. 9-29 Copyright © 2004, Oracle. All rights reserved.
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.
• 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
9-34 Copyright © 2004, Oracle. All rights reserved. Copyright © 2004, Oracle. All rights reserved.
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.
8-4 Copyright © 2004, Oracle. All rights reserved. 8-5 Copyright © 2004, Oracle. All rights reserved.
• 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.
• 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);
1 row created.
8-10 Copyright © 2004, Oracle. All rights reserved. 8-11 Copyright © 2004, Oracle. All rights reserved.
8-12 Copyright © 2004, Oracle. All rights reserved. 8-13 Copyright © 2004, Oracle. All rights reserved.
• 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
8-16 Copyright © 2004, Oracle. All rights reserved. 8-17 Copyright © 2004, Oracle. All rights reserved.
You can remove existing rows from a table by using • Specific rows are deleted if you specify the WHERE
the DELETE statement: clause:
8-18 Copyright © 2004, Oracle. All rights reserved. 8-19 Copyright © 2004, Oracle. All rights reserved.
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.
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.
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.
• 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.
• 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.
COMMIT;
Commit complete.
8-34 Copyright © 2004, Oracle. All rights reserved. 8-35 Copyright © 2004, Oracle. All rights reserved.
8-36 Copyright © 2004, Oracle. All rights reserved. 8-37 Copyright © 2004, Oracle. All rights reserved.
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
Copyright © 2004, Oracle. All rights reserved. 10-2 Copyright © 2004, Oracle. All rights reserved.
EMPLOYEES table
Object Description
10-3 Copyright © 2004, Oracle. All rights reserved. 10-4 Copyright © 2004, Oracle. All rights reserved.
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.
• 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
10-9 Copyright © 2004, Oracle. All rights reserved. 10-10 Copyright © 2004, Oracle. All rights reserved.
• 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.
• 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.
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.
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
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.
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.
10-25 Copyright © 2004, Oracle. All rights reserved. 10-26 Copyright © 2004, Oracle. All rights reserved.
• 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.
10-29 Copyright © 2004, Oracle. All rights reserved. 10-30 Copyright © 2004, Oracle. All rights reserved.
17
10-31 Copyright © 2004, Oracle. All rights reserved. 10-32 Copyright © 2004, Oracle. All rights reserved.
Creating an Index Index Creation Guidelines
10-33 Copyright © 2004, Oracle. All rights reserved. 10-34 Copyright © 2004, Oracle. All rights reserved.
10-35 Copyright © 2004, Oracle. All rights reserved. 10-36 Copyright © 2004, Oracle. All rights reserved.
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.
10-37 Copyright © 2004, Oracle. All rights reserved. 10-38 Copyright © 2004, Oracle. All rights reserved.
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
Copyright © 2004, Oracle. All rights reserved. 1-2 Copyright © 2004, Oracle. All rights reserved.
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.
1-5 Copyright © 2004, Oracle. All rights reserved. 1-6 Copyright © 2004, Oracle. All rights reserved.
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.
… …
1-11 Copyright © 2004, Oracle. All rights reserved. 1-12 Copyright © 2004, Oracle. All rights reserved.
1-13 Copyright © 2004, Oracle. All rights reserved. 1-14 Copyright © 2004, Oracle. All rights reserved.
… …
20
1-15 Copyright © 2004, Oracle. All rights reserved. 1-16 Copyright © 2004, Oracle. All rights reserved.
Literal Character Strings Using Literal Character Strings
1-17 Copyright © 2004, Oracle. All rights reserved. 1-18 Copyright © 2004, Oracle. All rights reserved.
• 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 iSQL*Plus
statements commands
1-21 Copyright © 2004, Oracle. All rights reserved. 1-22 Copyright © 2004, Oracle. All rights reserved.
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
DESC[RIBE] tablename
2 3 4 5
1-25 Copyright © 2004, Oracle. All rights reserved. 1-26 Copyright © 2004, Oracle. All rights reserved.
DESCRIBE employees
1-27 Copyright © 2004, Oracle. All rights reserved. 1-28 Copyright © 2004, Oracle. All rights reserved.
1-29 Copyright © 2004, Oracle. All rights reserved. 1-30 Copyright © 2004, Oracle. All rights reserved.
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.
1-35 Copyright © 2004, Oracle. All rights reserved. 1-36 Copyright © 2004, Oracle. All rights reserved.
Practice 1: Overview
1-37 Copyright © 2004, Oracle. All rights reserved. Copyright © 2004, Oracle. All rights reserved.
“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)];
2-4 Copyright © 2004, Oracle. All rights reserved. 2-5 Copyright © 2004, Oracle. All rights reserved.
2-6 Copyright © 2004, Oracle. All rights reserved. 2-7 Copyright © 2004, Oracle. All rights reserved.
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 ;
2-8 Copyright © 2004, Oracle. All rights reserved. 2-9 Copyright © 2004, Oracle. All rights reserved.
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 ;
2-12 Copyright © 2004, Oracle. All rights reserved. 2-13 Copyright © 2004, Oracle. All rights reserved.
2-14 Copyright © 2004, Oracle. All rights reserved. 2-15 Copyright © 2004, Oracle. All rights reserved.
2-16 Copyright © 2004, Oracle. All rights reserved. 2-17 Copyright © 2004, Oracle. All rights reserved.
2-20 Copyright © 2004, Oracle. All rights reserved. 2-21 Copyright © 2004, Oracle. All rights reserved.
2-22 Copyright © 2004, Oracle. All rights reserved. 2-23 Copyright © 2004, Oracle. All rights reserved.
Using the & Substitution Variable Using the & Substitution Variable
1
2
2-24 Copyright © 2004, Oracle. All rights reserved. 2-25 Copyright © 2004, Oracle. All rights reserved.
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
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
UNDEFINE employee_num
2-28 Copyright © 2004, Oracle. All rights reserved. 2-29 Copyright © 2004, Oracle. All rights reserved.
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
2-32 Copyright © 2004, Oracle. All rights reserved. Copyright © 2004, Oracle. All rights reserved.
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.
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.
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
3-9 Copyright © 2004, Oracle. All rights reserved. 3-10 Copyright © 2004, Oracle. All rights reserved.
3-13 Copyright © 2004, Oracle. All rights reserved. 3-14 Copyright © 2004, Oracle. All rights reserved.
1 2 3
3-15 Copyright © 2004, Oracle. All rights reserved. 3-16 Copyright © 2004, Oracle. All rights reserved.
3-17 Copyright © 2004, Oracle. All rights reserved. 3-19 Copyright © 2004, Oracle. All rights reserved.
• 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
3-22 Copyright © 2004, Oracle. All rights reserved. 3-23 Copyright © 2004, Oracle. All rights reserved.
3-24 Copyright © 2004, Oracle. All rights reserved. 3-25 Copyright © 2004, Oracle. All rights reserved.
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.
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.