SQL Sub Queries

Relational databases allow tables to be related to another if both have a field in common.

Customer and Order tables can be related because they both have Cid column. It is possible to extract data from one table using information of another. This can be accomplished by related the common keys of both tables.

We need to find out who has an order placed under a pending status. Notice that who is on the customer table and pending on the order table.

A sub query is a query inside another. The nested query has the information we know (pending order) and the main query has the information we are looking for (who). Sub queries have the following syntax:

Select FieldName1, FieldName2 from TableName where CommonColumnName in
(
          Select CommonColumnName from OtherTableName where ColumnName=This-Value
)

Select Cname from Customer where Cid in
(
  Select Cid from Order where Ostatus='Pending'
)