Technical Article

CASE IN ORDER BY

,

Sample Table:

SELECT * FROM COUNTRY

NAME
CANADA
ENGLAND
INDIA
IRAN
MISR
PAKISTAN
SHAAM

For the above shown table i want the result in such a way that a particular country should be listed first and then the remaining countries should be sorted in ascending order.

As for example I want "SHAMM" to be listed first and the remaining countries should be sorted in ascending order.

SELECT * FROM COUNTRY
ORDER BY CASE WHEN NAME = 'SHAAM' THEN 1 ELSE 2 END,NAME ASC

NAME
SHAAM
CANADA
ENGLAND
INDIA
IRAN
MISR
PAKISTAN
In the above query we have highlighted the use of case statement in order by.
SELECT * FROM COUNTRY
ORDER BY CASE WHEN NAME = 'SHAAM' THEN 1 ELSE 2 END,NAME ASC

Rate

4 (1)

You rated this post out of 5. Change rating

Share

Share

Rate

4 (1)

You rated this post out of 5. Change rating