Joined: Thu Apr 05, 2007 9:57 pm Posts: 17 Has thanked: 0 time Have thanks: 0 time
DML Statements(Subqueries)
A) Using Subquery in WHERE Clause
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
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
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'
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ط·آ£ط¢آ¢ط£آ¢أ¢â‚¬ع‘ط¢آ¬ط£آ¢أ¢â€ڑآ¬ط¥â€™
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
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)ط·آ£ط¢آ¢ط£آ¢أ¢â‚¬ع‘ط¢آ¬ط£آ¢أ¢â€ڑآ¬ط¥â€™
Get the name , job (title) and number of orderes requested by each customer
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.
Users browsing this forum: No registered users and 1 guest
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot post attachments in this forum