Today in this article I share the use of a Sub Query. But before explaining what a Sub Query is I want to through some light on the mechanism called Query that is used frequently by database administrators. I think that without queries DBAs would not exist. We all use this term but are we truly clear about what a Query is? Let's review what a Query is.
Query
While creating a database if we want to extract some information regarding the data in the database then we use a Query. In other words, if we want to retrieve some data from a table or some tables that we created earlier then we write/use a Query.
Example: If we write a simple Query to create a table:
- CREATE TABLE Product
- (
- Prod_Id Number Not Null,
- Prod_Name Varchar2(50),
- Quantity Varchar2(15),
- Price Number
- );
Then, the result will be as in the following.
Product Table
| Prod_id | Prod_Name | Quantity | Price |
Sub Query
If a Query that contains another Query, then the Query inside the main Query is called a Sub Query and the main Query is known as the parent Query. In Oracle the Sub Query will executed on the prior basis and the result will be available to the parent Query and then the execution of the parent/main Query takes place. Sub Queries are very useful for selecting rows from a table having a condition that depends on the data of the table itself. A Sub Query can also be called a Nested/Inner Query. These Sub Queries can be used with:
- WHERE Clause
- SELECT Clause
- FROM Clause

Syntax
- SELECT <column, ...>
- FROM <table>
- WHERE expression operator
- (
- SELECT <column, ...>
- FROM <table>
- WHERE <condition>
- );
Or
- SELECT Col_name [, Col_name]
- FROM table1 [,table2]
- WHERE Col_name OPERATOR
- (
- SELECT Col_name [,Col_name]
- FROM table1 [,table2]
- [WHERE]
- );
Now let us explain the Sub Query using all the three clauses. For that we are assuming the following tables.
STUDENT TABLE

SUBJECT TABLE

1. Sub Query using WHERE Clause
STUDENT TABLE

SUBJECT TABLE

1. Sub Query using WHERE Clause
- SELECT * FROM student
- WHERE course_id in (SELECT course_id
- FROM subject
- WHERE course_name = 'Oracle')




Gowtham RajamanickamPosted Apr 26, 2016, 3:10 AM
good article