Subquery
In Oracle, a subquery is a query within a query. You can create
subqueries within your SQL statements. These subqueries can
reside in the WHERE clause, the FROM clause, or the SELECT
clause.
You can place the subquery in a number of SQL clauses, including the
following:
• WHERE clause
• HAVING clause
• FROM clause
1
Applying Subqueries in DML
• You can use the INSERT statement to add rows to a table where the
values are derived from existing tables. In place of the VALUES
clause, you use a subquery.
• Syntax
• In the syntax:
table is the table name
column is the name of the column in the table to
populate
subquery is the subquery that returns rows into the
table
• Example:
2
Do not use the VALUES clause.
• You can use a subquery in place of the table name in the INTO
clause of the INSERT statement.
• The select list of this subquery must have the same number of
columns as the column list of the VALUES clause.
• Example:
INSERT INTO
(SELECT EMPLOYEE_ID,LASTNAME,JOB_ID,SALARY
FROM EMPLOYEES
WHERE SALARY >= 10000)
VALUES(10,'CRUZ','IT_MGR',25000);
Example:
UPDATE COPY_EMPLOYEES
SET JOB_ID=
(SELECT JOB_ID
FROM EMPLOYEES
WHERE EMPLOYEE_ID = 104)
WHERE ID=174;
Example:
3
UPDATE COPY_EMPLOYEES
SET LASTNAME = (SELECT LASTNAME
FROM EMPLOYEES
WHERE LASTNAME='REYES')
WHERE ID=205;
You can use subqueries to delete rows from a table based on values
from another table
Example:
Syntax: Subquery
SELECT COLUMN_LIST
FROM TABLE
WHERE CONDITION
SELECT COLUMN_LIST
FROM TABLE
Types of Subqueries
4
Single-Row Subqueries
Multiple-Row Subqueries
5
LESSON SUMMARY:
6
Activities/Exercises
• Download the Laboratory Exercise 6: Applying Subqueries
• Copy and paste the three (3) table EMPLOYEES,
DEPARTMENTS and LOCATIONS
• Perform the PL/SQL needed per number in order for you to
answer the questions in eacg number. Write the excat
answer
Glossary
ALL - must be preceded by comparison operator. Returns true if at
least oe element exist in the result.
7
References
Textbook:
• Oracle Database 11g 2nd Edition K Gopalakrishnan ( 2012)
References:
• Carlos, Peter (2009). Database Systems
• Connoly, Thomas & Begg, Carolyn (2010). Database
Systems : A practical approach to design,
implementation and management
• Sciore, Edward (2009). Database Design and Implementation
• Bulusu, Lakshman (2008). Oracle PL/SQL : Expert
Techniques for Developers and Database Administrators
• Loshin, David (2008). Master Data Management