Oracle Tutorial 2003
Oracle Tutorial 2003
TRANING
Page 1 of 39
TABLE
CLASS -1
CREATING TABLE
CREATE TABLE table_name
(
column1 datatype null/not null,
column2 datatype null/not null,
...
);
EXAMPLE
CREATE TABLE suppliers
( supplier_id number(10) not null,
supplier_name varchar2(50) not null,
contact_name varchar2(50)
);
Practice Exercise #1:
Create an SQL table called customers that stores customer ID, name, and
address information. The customer ID should be the primary key for the
table.
Solution
CREATE TABLE customers
( customer_id number(10) not null,
customer_name varchar2(50) not null,
address varchar2(50),
city varchar2(50),
state varchar2(25),
zip_code varchar2(10),
CONSTRAINT customers_pk PRIMARY KEY
(customer_id)
);
Practice Exercise #2:
Based on the departments table below, create an SQL table called employees that
stores employee number, employee name, department, and salary information. The
primary key for the employees table should be the employee number. Create a
foreign key on the employees table that references the departments table based on
the department_id field.
ORACLE PL/SQL
TRANING
Page 2 of 39
Solution
CREATE TABLE departments
( department_id number(10) not null,
department_name varchar2(50) not null,
CONSTRAINT departments_pk PRIMARY KEY
(department_id)
);
The SQL CREATE TABLE statement for the employees table is:
Solution
CREATE TABLE employees
( employee_number number(10) not null,
employee_name varchar2(50) not null,
department_id number(10),
salary number(6),
CONSTRAINT employees_pk PRIMARY KEY
(employee_number),
CONSTRAINT fk_departments
FOREIGN KEY (department_id)
REFERENCES departments(department_id)
);
ALTER
To rename a table, the SQL ALTER TABLE syntax is:
ALTER TABLE table_name
RENAME TO new_table_name;
Example
ALTER TABLE suppliers
RENAME TO vendors;
SQL ALTER TABLE - Adding column(s) to a table
Syntax #1
To add a column to an existing table, the SQL ALTER TABLE syntax is:
ALTER TABLE table_name
ORACLE PL/SQL
TRANING
Page 3 of 39
Syntax #1
To rename a column in an existing table, the SQL ALTER TABLE syntax is:
ALTER TABLE table_name
RENAME COLUMN old_name to new_name;
For example:
ORACLE PL/SQL
TRANING
Page 4 of 39
Solution:
The following SQL ALTER TABLE statement would rename the departments table to depts:
Based on the employees table below, add a column called salary that is a number(6)
datatype.
Solution:
);
The following SQL ALTER TABLE statement would add a salary column to
the employees table:
Solution:
ORACLE PL/SQL
TRANING
Page 5 of 39
Solution:
);
The following SQL ALTER TABLE statement would change the datatype for
the employee_name column to varchar2(75):
Solution:
);
ORACLE PL/SQL
TRANING
Page 6 of 39
Solution:
The following SQL ALTER TABLE statement would drop the salary column from
the employees table:
(department_id)
);
Solution:
The following SQL ALTER TABLE statement would rename the department_name column
to dept_name in the departments table:
ORACLE PL/SQL
TRANING
Page 7 of 39
CLASS -2
SQL: SELECT Statement
The SQL SELECT statement allows you to retrieve records from one or more tables
in your SQL database.
The syntax for the SQL SELECT statement is:
SELECT columns
FROM tables
WHERE predicates;
SQL SELECT Statement - Select all fields from one table
example
Let's take a look at how to use the SQL SELECT statement to select all fields from a
table.
SELECT *
FROM suppliers
WHERE city = 'Newark';
In this SQL SELECT statement, we've used * to signify that we wish to view all fields
from the suppliers table where the supplier resides in Newark.
SQL SELECT Statement - Selecting individual fields from
one table example
You can also use the SQL SELECT statement to select individual fields from the table,
as opposed to all fields from the table.
For example:
SELECT name, city, state
FROM suppliers
WHERE supplier_id > 1000;
This SQL SELECT statement would return only the name, city, and state fields from
the suppliers table where the supplier_id value is greater than 1000.
SQL SELECT Statement - Select fields from multiple
tables example
You can also use the SQL SELECT statement to retrieve fields from multiple tables.
SELECT orders.order_id, suppliers.name
ORACLE PL/SQL
TRANING
Page 8 of 39
ORACLE PL/SQL
TRANING
Page 9 of 39
ORACLE PL/SQL
TRANING
Page 10 of 39
The SQL UPDATE statement allows you to update a single record or multiple records
in a table.
The syntax for the SQL UPDATE statement is:
UPDATE table
SET column = expression
WHERE predicates;
SQL UPDATE - Simple example
Let's take a look at a very simple example.
UPDATE suppliers
SET name = 'HP'
WHERE name = 'IBM';
This SQL UPDATE statement would update all supplier names in the suppliers table
from IBM to HP.
SQL UPDATE - Updating multiple columns example
Let's take a look at an SQL UPDATE example where you might want to update more
than one column with a single SQL UPDATE statement.
UPDATE suppliers
SET name = 'Apple', product = 'iPhone'
WHERE name = 'Rim';
When you wish to update multiple columns, you can do this by separating the
column/value pairs with commas.
This SQL UPDATE statement would update the supplier name to "Apple" and product
to "iPhone" where the name of the supplier is "Rim".
SQL UPDATE - Using SQL EXISTS Clause example
You can also perform more complicated updates in SQL.
You may wish to update records in one table based on values in another table.
Since you can't list more than one table in the SQL UPDATE statement, you can use
the SQL EXISTS clause.
For example:
UPDATE suppliers
SET supplier_name = (SELECT customers.name
FROM customers
WHERE customers.customer_id =
suppliers.supplier_id)
WHERE EXISTS (SELECT customers.name
FROM customers
WHERE customers.customer_id =
suppliers.supplier_id);
ORACLE PL/SQL
TRANING
Page 11 of 39
ORACLE PL/SQL
TRANING
Page 12 of 39
ORACLE PL/SQL
TRANING
Page 13 of 39
CONSTRAINT
ORACLE PL/SQL
TRANING
Page 14 of 39
(
supplier_id numeric(4),
supplier_name varchar2(50),
CONSTRAINT check_supplier_name
CHECK (supplier_name = upper(supplier_name))
);
In this second example, we've created a check constraint called
check_supplier_name. This constraint ensures that the supplier_name column
always contains uppercase characters.
Using an ALTER TABLE statement
The syntax for creating a check constraint in an ALTER TABLE statement is:
ALTER TABLE table_name
add CONSTRAINT constraint_name CHECK
(column_name condition) [DISABLE];
The DISABLE keyword is optional. If you create a check constraint using the
DISABLE keyword, the constraint will be created, but the condition will not be
enforced.
For Example
ALTER TABLE suppliers
add CONSTRAINT check_supplier_name
CHECK (supplier_name IN ('IBM', 'Microsoft', 'NVIDIA'));
In this example, we've created a check constraint on the existing suppliers table
called check_supplier_name. It ensures that the supplier_name field only contains
the following values: IBM, Microsoft, or NVIDIA.
Drop a Check Constraint
The syntax for dropping a check constraint is:
ALTER TABLE table_name
drop CONSTRAINT constraint_name;
For Example
ALTER TABLE suppliers
drop CONSTRAINT check_supplier_id;
In this example, we're dropping a check constraint on the suppliers table called
check_supplier_id.
Enable a Check Constraint
The syntax for enabling a check constraint is:
ALTER TABLE table_name
enable CONSTRAINT constraint_name;
For Example
ALTER TABLE suppliers
enable CONSTRAINT check_supplier_id;
In this example, we're enabling a check constraint on the suppliers table called
check_supplier_id.
ORACLE PL/SQL
TRANING
Page 15 of 39
ORACLE PL/SQL
TRANING
Page 16 of 39
The SQL "AND" condition requires that each condition be must be met for the record
to be included in the result set. In this case, column1 has to equal 'value1' and
column2 has to equal 'value2'.
SQL "AND" Condition - SQL SELECT Statement example
The first SQL "AND" Condition example that we'll take a look at involves an SQL
SELECT statement with 2 conditions:
SELECT *
FROM suppliers
WHERE city = 'New York'
and type = 'PC Manufacturer';
This SQL "AND" condition example would return all suppliers that reside in New York
and are PC Manufacturers. Because the * is used in the SQL SELECT statement, all
fields from the supplier table would appear in the result set.
SQL "AND" Condition - JOINING Tables example
Our next example demonstrates how the SQL "AND condition" can be used to join
multiple tables in an SQL statement.
SELECT orders.order_id, suppliers.supplier_name
FROM suppliers, orders
WHERE suppliers.supplier_id = orders.supplier_id
and suppliers.supplier_name = 'IBM';
This SQL "AND" condition example would return all rows where the supplier_name is
IBM. And the suppliers and orders tables are joined on supplier_id. You will notice
that all of the fields are prefixed with the table names (ie: orders.order_id). This is
required to eliminate any ambiguity as to which field is being referenced; as the
same field name can exist in both the suppliers and orders tables.
In this case, the result set would only display the order_id and supplier_name fields
(as listed in the first part of the select statement.).
SQL "AND" Condition - SQL INSERT Statement example
The SQL "AND" Condition can be used in the SQL INSERT statement.
For example:.
INSERT INTO suppliers
(supplier_id, supplier_name)
SELECT account_no, name
FROM customers
WHERE customer_name = 'IBM'
or city = 'New York';
This SQL "AND" Condition example would insert into the suppliers table, all
account_no and name records from the customers table whose customer_name is
IBM and reside in New York.
SQL "AND" Condition - SQL UPDATE Statement example
ORACLE PL/SQL
TRANING
Page 17 of 39
The SQL "AND" Condition can be used in the SQL UPDATE statement.
For example:.
UPDATE suppliers
SET supplier_name = 'HP'
WHERE supplier_name = 'IBM'
and state = 'California';
This SQL "AND" Condition example would update all supplier_name values in the
suppliers table to HP where the supplier_name was IBM and resides in the state of
California.
SQL "AND" Condition - SQL DELETE Statement example
The SQL "AND" Condition can be used in the SQL DELETE statement.
For example:.
DELETE FROM suppliers
WHERE supplier_name = 'IBM'
and product = 'PC computers';
This SQL "AND" Condition example would delete all suppliers from the suppliers
table whose supplier_name was IBM and product was PC computers.
SQL: LIKE Condition
The SQL LIKE condition allows you to use wildcards in the SQL WHERE clause of an
SQL statement. This allows you to perform pattern matching. The SQL LIKE
condition can be used in any valid SQL statement - SQL SELECT statement, SQL
INSERT statement, SQL UPDATE statement, or SQL DELETE statement.
The patterns that you can choose from are:
% allows you to match any string of any length (including zero length)
_ allows you to match on a single character
SQL LIKE Condition - Using % wildcard example
Let's explain how the % wildcard works in the SQL LIKE condition. We are going to
try to find all of the suppliers whose name begins with 'Hew'.
SELECT * FROM suppliers
WHERE supplier_name like 'Hew%';
You can also using the % wildcard multiple times within the same string. For
example,
SELECT * FROM suppliers
WHERE supplier_name like '%bob%';
In this SQL LIKE condition example, we are looking for all suppliers whose name
contains the characters 'bob'.
ORACLE PL/SQL
TRANING
Page 18 of 39
You could also use the SQL LIKE condition to find suppliers whose name does not
start with 'T'.
For example:
SELECT * FROM suppliers
WHERE supplier_name not like 'T%';
By placing the not keyword in front of the SQL LIKE condition, you are able to
retrieve all suppliers whose name does not start with 'T'.
SQL LIKE Condition - Using _ wildcard example
Next, let's explain how the _ wildcard works in the SQL LIKE condition. Remember
that the _ is looking for only one character.
For example:
SELECT * FROM suppliers
WHERE supplier_name like 'Sm_th';
This SQL LIKE condition example would return all suppliers whose name is 5
characters long, where the first two characters is 'Sm' and the last two characters is
'th'. For example, it could return suppliers whose name is 'Smith', 'Smyth', 'Smath',
'Smeth', etc.
Here is another example:
SELECT * FROM suppliers
WHERE account_number like '12317_';
You might find that you are looking for an account number, but you only have 5 of
the 6 digits. The example above, would retrieve potentially 10 records back (where
the missing value could equal anything from 0 to 9). For example, it could return
suppliers whose account numbers are:
123170, 123171, 123172, 123173, 123174, 123175, 123176, 123177, 123178,
123179
SQL LIKE Condition - Using Escape Characters example
Next, in Oracle, let's say you wanted to search for a % or a _ character in the SQL
LIKE condition. You can do this using an Escape character.
Please note that you can only define an escape character as a single character
(length of 1).
For example:
SELECT * FROM suppliers
WHERE supplier_name LIKE '!%' escape '!';
This SQL LIKE condition example identifies the ! character as an escape character.
This statement will return all suppliers whose name is %.
ORACLE PL/SQL
TRANING
Page 19 of 39
Here is another more complicated example using escape characters in the SQL LIKE
condition.
SELECT * FROM suppliers
WHERE supplier_name LIKE 'H%!%' escape '!';
This SQL LIKE condition example returns all suppliers whose name starts with H and
ends in %. For example, it would return a value such as 'Hello%'.
You can also use the escape character with the _ character in the SQL LIKE
condition.
For example:
SELECT * FROM suppliers
WHERE supplier_name LIKE 'H%!_' escape '!';
This SQL LIKE condition example returns all suppliers whose name starts with H and
ends in _. For example, it would return a value such as 'Hello_'.
Frequently Asked Questions
Question: How do you incorporate the Oracle upper function with the SQL LIKE
condition? I'm trying to query against a free text field for all records containing the
word "test". The problem is that it can be entered in the following ways: TEST, Test,
or test.
Answer: To answer this question, let's take a look at an example.
Let's say that we have a suppliers table with a field called supplier_name that
contains the values TEST, Test, or test.
If we wanted to find all records containing the word "test", regardless of whether it
was stored as TEST, Test, or test, we could run either of the following SQL SELECT
statements:
select * from suppliers
where upper(supplier_name) like ('TEST%');
or
select * from suppliers
where upper(supplier_name) like upper('test%')
These SQL SELECT statements use a combination of the Oracle upper function and
the SQL LIKE condition to return all of the records where the supplier_name field
contains the word "test", regardless of whether it was stored as TEST, Test, or test.
ORACLE PL/SQL
TRANING
Page 20 of 39
EMPLOYEE_NAME
ORACLE PL/SQL
TRANING
Page 21 of 39
EMPLOYEE_NAME
ORACLE PL/SQL
TRANING
Page 22 of 39
CITY
ORACLE PL/SQL
TRANING
Page 23 of 39
ORACLE PL/SQL
TRANING
Page 24 of 39
FROM suppliers
WHERE supplier_name in ('IBM', 'Hewlett Packard',
'Microsoft');
This SQL "IN" condition example would return all rows where the supplier_name is
either IBM, Hewlett Packard, or Microsoft. Because the * is used in the select, all
fields from the suppliers table would appear in the result set.
It is equivalent to the following statement:
SELECT *
FROM suppliers
WHERE supplier_name = 'IBM'
OR supplier_name = 'Hewlett Packard'
OR supplier_name = 'Microsoft';
As you can see, using the SQL "IN" condition makes the statement easier to read
and more efficient.
SQL "IN" Condition - Numeric example
You can also use the SQL "IN" condition with numeric values.
For example:
SELECT *
FROM orders
WHERE order_id in (10000, 10001, 10003, 10005);
This SQL "IN" condition example would return all orders where the order_id is either
10000, 10001, 10003, or 10005.
It is equivalent to the following statement:
SELECT *
FROM orders
WHERE order_id = 10000
OR order_id = 10001
OR order_id = 10003
OR order_id = 10005;
SQL "IN" Condition - Using the NOT operator
The SQL "IN" condition can also be combined with the SQL NOT operator.
For example,
SELECT *
FROM suppliers
WHERE supplier_name not in ( 'IBM', 'Hewlett Packard',
'Microsoft');
ORACLE PL/SQL
TRANING
Page 25 of 39
ORACLE PL/SQL
TRANING
Page 26 of 39
ORACLE PL/SQL
TRANING
Page 27 of 39
ORACLE PL/SQL
TRANING
Page 28 of 39
SELECT COUNT(expression)
FROM tables
WHERE predicates;
Note
The SQL COUNT function will only count those records in which the field in the brackets is
NOT NULL.
For example, if you have the following table called suppliers:
IBM
Microsoft
NVIDIA
CA
And if you ran the following SQL SELECT statement that uses the SQL COUNT function:
ORACLE PL/SQL
TRANING
Page 29 of 39
The simplest way to use the SQL COUNT function would be to return a single field that
returns the COUNT of something.
For example, you might wish to know how many employees have a salary that is above
$25,000 / year.
ORACLE PL/SQL
TRANING
Page 30 of 39
For example, based on the example above, the following syntax would result in better
performance:
ORACLE PL/SQL
TRANING
Page 31 of 39
Number of
employees
3
A more efficient implementation of the same solution would be the following SQL SELECT
statement:
ORACLE PL/SQL
TRANING
Page 32 of 39
Distinct
Cities
4
ORACLE PL/SQL
TRANING
Page 33 of 39
CUSTOMER_N Distinct
AME
Cities
IBM
Microsoft
NVIDIA
Red Hat
ADVERTISEMENT
The SQL UNION query allows you to combine the result sets of 2 or more SQL SELECT
statements. It removes duplicate rows between the various SELECT statements.
Each SQL SELECT statement within the UNION query must have the same number of
fields in the result sets with similar data types.
The syntax for the SQL UNION query is:
ORACLE PL/SQL
TRANING
Page 34 of 39
The following is an example of the SQL UNION query that returns one field from multiple
SELECT statements (and both fields have the same data type):
select supplier_id
from suppliers
UNION
select supplier_id
from orders;
In this SQL UNION query example, if a supplier_id appeared in both the suppliers and orders
table, it would appear once in your result set. The SQL UNION query removes duplicates. If
you do notwish to remove duplicates, try using the SQL UNION ALL query.
ORDER BY 2;
In this SQL UNION query, since the column names are different between the two SQL
SELECT statements, it is more advantageous to reference the columns in the SQL ORDER
BY clause by their position in the result set. In this example, we've sorted the results by
supplier_name / company_name in ascending order, as denoted by the "ORDER BY 2".
The supplier_name / company_name fields are in position #2 in the result set.
Question: I need to compare two dates and return the count of a field based on the date
values. For example, I have a date field in a table called last updated date. I have to check if
trunc(last_updated_date >= trunc(sysdate-13).
Answer: Since you are using the SQL COUNT function which is an aggregate function,
we'd recommend using an SQL UNION query. For example, you could try the following:
ORACLE PL/SQL
TRANING
Page 35 of 39
The SQL UNION ALL query allows you to combine the result sets of 2 or more SELECT
statements. It returns all rows from the query (even if the row exists in more than one of
the SELECT statements).
Each SQL SELECT statement within the SQL UNION ALL query must have the same
number of fields in the result sets with similar data types.
The syntax for the SQL UNION ALL query is:
The following is an example of the SQL UNION ALL query that returns one field from multiple
SELECT statements (and both fields have the same data type):
select supplier_id
from suppliers
UNION ALL
select supplier_id
from orders;
This SQL UNION ALL query would return a supplier_id multiple times in your result set if the
supplier_id appeared in both the suppliers and orders table. The SQL UNION ALL query
does not remove duplicates. If you wish to remove duplicates, try using the SQL UNION
query.
ORACLE PL/SQL
TRANING
Page 36 of 39
select supplier_id
from suppliers
INTERSECT
select supplier_id
from orders;
In this SQL INTERSECT query example, if a supplier_id appeared in both the suppliers and
orders table, it would appear in your result set.
The following is an SQL INTERSECT query that uses an SQL ORDER BY clause:
The SQL MINUS query returns all rows in the first SQL SELECT statement that are not
returned in the second SQL SELECT statement.
Each SQL SELECT statement within the SQL MINUS query must have the same number of
fields in the result sets with similar data types.
The syntax for the SQL MINUS query is:
ORACLE PL/SQL
TRANING
Page 37 of 39
The following is an example of an SQL MINUS query that has one field with the same data
type:
select supplier_id
from suppliers
MINUS
select supplier_id
from orders;
This SQL Minus query example returns all supplier_id values that are in the suppliers table
and not in the orders table. What this means is that if a supplier_id value existed in the
suppliers table and also existed in the orders table, the supplier_id value would not appear
in this result set.
SELECT SUM(expression )
FROM tables
WHERE predicates;
expression can be a numeric field or formula.
In this SQL SUM Function example, we've aliased the sum(salary) field as "Total Salary". As a
result, "Total Salary" will display as the field name when the result set is returned.
ORACLE PL/SQL
TRANING
Page 38 of 39
In some cases, you will be required to use the SQL GROUP BY clause with the SQL SUM
function.
For example, you could also use the QSL SUM function to return the name of the department
and the total sales (in the associated department).
You could also use the SQL SUM function to return the name of the department and the
total sales (in the associated department). The SQL HAVING clause will filter the results so
that only departments with sales greater than $1000 will be returned.
ORACLE PL/SQL
TRANING
Page 39 of 39