SELECT Count(OrderID), ProductID, AVG(Quantity) from OrderDetails
group by ProductID Having SUM(Quantity)>60 The above query is simply a pivot table. 2. Useful inner join query: shows the customername and their orders. SELECT OrderID, Customername from (Orders INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID) the above query is simply a VLOOKUP which can be breaken down in to two steps: 1. find the join of 2 tables 2. pick all the columns you like from that joined table. Step 1 query would be like: SELECT * from Orders INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID Step 2 would be like: Select Customername, OrderId from (SELECT * from Orders INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID ) 3. Useless query: shows the customers who have ordered any order. SELECT Customers.CustomerName, Orders.OrderID FROM Customers INNER JOIN Orders ON Customers.CustomerID=Orders.CustomerID ORDER BY Customers.CustomerName; 4. SELF JOIN select e1.ename junior, e2.ename senior from (emp e1 inner join emp e2 on e1.mgr=e2.empno); 5. SEE HOW MANY STAFF UNDER EACH MGR select count(e1.ename) junior_count, e2.ename senior from (emp e1 inner join emp e2 on e1.mgr=e2.empno) group by e2.ename; 6. SELECT THE TOP 5 ROWS from table sorted by ENAME: SELECT ename FROM EMp o WHERE ((SELECT count(*) FROM EMP i WHERE i.ename < o.ename) < 5) order by ename 7. FIND OUT HOW MANY TIMES TEAM IN TEAM1 COLUMN Became winners select count(ipl1.team1) from (ipl ipl1 inner join ipl ipl2 on ipl1.team1=ipl2.winner) group by ipl1.team1 8. TEAM with 3 WINS in IPL select winning_team from ( select count(*) wins, ipl1.team1 winning_team from ipl ipl1 where ipl1.team1=ipl1.winner group by ipl1.team1)ipl_extension where wins=3 9. Find MAX salary without using max function select sal from emp i where ((select count(*) from emp o where i.sal<o.sal)<1) 10. Find the Nth max salary Just extend the previous query for that. 11. Queries on this link: http://www.programmerinterview.com/index.php/database- sql/advanced-sql-interview-questions-and-answers 11.1 WRONG QUERY: SELECT Name FROM Orders inner join Salesperson on Orders.salesperson_id = Salesperson.ID GROUP BY salesperson_id Why so? well SQL would not know if it should return the count, max, min or avg o f the column name. Simple! RIGHT QUERY: SELECT Name FROM Orders inner join Salesperson on Orders.salesperson_id = Salesperson.ID GROUP BY salesperson_id,name does same work as: Select name from Salesperson where Id IN (select Distinct salesperson_id from Or ders) 11.2 12. Cartesian product: select * from emp,ipl