Question: Make sure those queries can work in sql server Q-32. Write An SQL Query To Show The Top N (Say 10) Records Of A Table.

Make sure those queries can work in sql server

Q-32. Write An SQL Query To Show The Top N (Say 10) Records Of A Table. Ans.

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;

Q-33. Write An SQL Query To Determine The Nth (Say N=5) Highest Salary From A Table. Ans.

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;

Q-34. Write An SQL Query To Determine The 5th Highest Salary Without Using TOP Or Limit Method. Ans.

The following query is using the correlated subquery to return the 5th highest salary:

SELECT Salary FROM Worker W1 WHERE 4 = ( SELECT COUNT( DISTINCT ( W2.Salary ) ) FROM Worker W2 WHERE W2.Salary >= W1.Salary ); Use the following generic method to find nth highest salary without using TOP or limit.

SELECT Salary FROM Worker W1 WHERE n-1 = ( SELECT COUNT( DISTINCT ( W2.Salary ) ) FROM Worker W2 WHERE W2.Salary >= W1.Salary );

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!