Programming Blog

This blog is about technical and programming questions and there solutions. I also cover programs that were asked in various interviews, it will help you to crack the coding round of various interviews

Monday 8 January 2018

Find second largest value with subquery

 The way to approach this is to first find the largest value (easy to do with MAX), exclude that value from the data set being evaluated, and then find the largest value in the resulting set. In SQL, we use the subquery construct to accomplish this as follows:
SELECT MAX(COLUMN_NAME) FROM TABLE_NAME
WHERE COLUMN_NAME <
(SELECT MAX(COLUMN_NAME) FROM TABLE_NAME);
Please note that the SQL above will find the second largest *distinct* value. Let’s say, for example, if the table consists of the following numbers:
25
10
8
12
25
In this case, the result we get using the above SQL is 12, even though in reality 12 is the 3rd largest number. This is because the top 2 numbers are both 25, and thus both would be excluded in the WHERE clause.

No comments:

Post a Comment