Home > Back-end >  How to give priority to a single employee while sorting the employee name in sql?
How to give priority to a single employee while sorting the employee name in sql?

Time:11-08

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 :)

CodePudding user response:

Simply use the correct ORDER BY clause:

SELECT *
FROM (VALUES
   ('Girish', 'BB', 20000),
   ('Bhanu',  'AA', 10000),
   ('Mahesh', 'CC', 10000),
   ('Seema',  'YY', 30000)
) Employee (Emp_name, Dept_name, Salary)
ORDER BY 
   CASE
      WHEN Emp_name LIKE '%Mahesh%' THEN 1
      ELSE 2
   END,
   Emp_name ASC

CodePudding user response:

My solution :

   SELECT Emp_name, Dept_name, Salary FROM (
select T.*,
       CASE
         WHEN Emp_name = 'Mahesh' THEN
          0
         ELSE
          1
       END SORT1
  from (VALUES
   ('Girish', 'BB', 20000),
   ('Bhanu',  'AA', 10000),
   ('Mahesh', 'CC', 10000),
   ('Seema',  'YY', 30000)
) T (Emp_name, Dept_name, Salary)) TT
  ORDER BY TT.SORT1,TT.Emp_name
  • Related