SQL Interview Questions
1 .
Write an SQL query to show the top n (say 10) records of a table.
Following MySQL query will return the top n records using the LIMIT method:
SELECT * FROM Worker ORDER BY Salary DESC LIMIT 10;​
 
Following SQL Server query will return the top n records using the TOP command:
SELECT TOP 10 * FROM Worker ORDER BY Salary DESC;​
Following Oracle query will return the top n records with the help of ROWNUM:
SELECT * FROM (SELECT * FROM Worker ORDER BY Salary DESC)
WHERE ROWNUM <= 10;
2 .
Write an SQL query to determine the nth (say n=5) highest salary from a table.
The following MySQL query returns the nth highest salary:
SELECT Salary FROM Worker ORDER BY Salary DESC LIMIT n-1,1;

The following SQL Server query returns the nth highest salary:
SELECT TOP 1 Salary
FROM (
 SELECT DISTINCT TOP n Salary
 FROM Worker 
 ORDER BY Salary DESC
 )
ORDER BY Salary ASC;
3 .
Write an SQL query to fetch the list of employees with the same salary.
The required query is:
Select distinct W.WORKER_ID, W.FIRST_NAME, W.Salary 
from Worker W, Worker W1 
where W.Salary = W1.Salary 
and W.WORKER_ID != W1.WORKER_ID;
4 .
Write an SQL query to fetch intersecting records of two tables.
The required query is:
(SELECT * FROM Worker)
INTERSECT
(SELECT * FROM WorkerClone);
5 .
Write an SQL query to fetch the first 50% records from a table.
The required query is:
SELECT * FROM WORKER
WHERE WORKER_ID <= (SELECT count(WORKER_ID)/2 from Worker);
6 .
Write an SQL query to show the last record from a table.
The following query will return the last record from the Worker table:
Select * from Worker where 
WORKER_ID = (SELECT max(WORKER_ID) from Worker);
7 .
Write an SQL query to fetch departments along with the total salaries paid for each of them.
The required query is:
 
SELECT DEPARTMENT, sum(Salary) from worker group by DEPARTMENT;