Search code examples
sqlsql-servert-sqlsql-query-store

How to give priority to a single employee while sorting the employee name in sql?


I have table like TB1:

Emp_name  Dept_name  salary
Girish    BB          20000
Bhanu     AA          10000
Mahesh    CC          10000
Seema     YY          30000

The output I need is:

Emp_name  Dept_name  salary
Mahesh    CC          10000
Bhanu     AA          10000
Girish    BB          20000
Seema     YY          30000

Here what I have done is gave priority to 'Mahesh' and rest all the employees are sorted asc.

I tried this query:

SELECT *
FROM Employee
ORDER BY CASE
    WHEN Emp_name LIKE '%Mahesh%' THEN 1
    WHEN Emp_name LIKE '%' THEN 2
    ELSE 3
end;

Thank you for your time.


Solution

  • Simply use the correct ORDER BY clause:

    Sample data:

    SELECT *
    INTO Employee
    FROM (VALUES
       ('Girish', 'BB', 20000),
       ('Bhanu',  'AA', 10000),
       ('Mahesh', 'CC', 10000),
       ('Seema',  'YY', 30000)
    ) Employee (Emp_name, Dept_name, Salary)
    

    Statement:

    SELECT *
    FROM Employee
    ORDER BY 
       CASE
          WHEN Emp_name LIKE '%Mahesh%' THEN 1
          ELSE 2
       END,
       Emp_name ASC