Total members 11895 |It is currently Sat Dec 21, 2024 5:44 pm Login / Join Codemiles

Java

C/C++

PHP

C#

HTML

CSS

ASP

Javascript

JQuery

AJAX

XSD

Python

Matlab

R Scripts

Weka





DML Statements(Subqueries)

A) Using Subquery in WHERE Clause

sql code
SELECT <column list>
FROM <table names>
WHERE expression operator
( SELECT <column list>
FROM <table names>)

Example 1:

Get the names of the customers who have ordered at least one order.

sql code
SELECT  Customers.ContactName
FROM Customers
WHERE Customers.CustomerID IN
(
SELECT Orders.CustomerID
FROM Orders
);


Example 2:

Get the supplier names of the suppliers who supply category number 3.
sql code
SELECT Suppliers.ContactName
FROM Suppliers
WHERE Suppliers.SupplierID IN
(
SELECT Products.SupplierID
FROM Products
WHERE Products.CategoryID=3
);


Example 3:

Get the books titles priced higher than the lowest priced book that has a type 'trad_cook'.


sql code
SELECT Title
FROM Titles
WHERE Price >
(
SELECT MIN(Price)
FROM Titles
WHERE Type = 'trad_cook'
);



B) Using Subquery in FROM Clause "Represents a table"

sql code
SELECT <column list>
FROM <table names>, ( SELECT <column list>
FROM <table names>)

[WHERE <condition>]


Example:

Get the names of all customers and employees living in USA , but with customers not working as Sales Agents.

sql code
SELECT C. ContactName "Cust Name", E.FirstName + ' ' + E.LastName "Emp Name" 
FROM Customers C ,
(
SELECT FirstName,LastName
FROM Employees
WHERE Country = 'USA'
) E
WHERE C.Country = 'USA'
AND C.ContactTitle <> 'Sales Agent';



C) Using Subquery in SELECT Clause "Represents column(s)"

sql code
SELECT <column list> , ( SELECT <column list>
FROM <table names>)

FROM <table names>
[WHERE <condition>]


Example:

Get the name , job (title) and number of orderes requested by each customer.

sql code
SELECT ContactName ,ContactTitle , (SELECT COUNT(*) 
FROM Orders
WHERE Customers.CustomerId = Orders.CustomerId
) AS "Number of Orders"
FROM Customers;



Note:

When using subquery in the where clause , take care when using operators ;
If the subquery returns more than one value you can't use operator such as = , but you may use the IN operator.



_________________
Recommend my post if you found it helpful.


Author:
Newbie
User avatar Posts: 15
Have thanks: 0 time
Post new topic Reply to topic  [ 1 post ] 




cron





Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
All copyrights reserved to codemiles.com 2007-2011
mileX v1.0 designed by codemiles team
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com