Saturday, October 30, 2010

Friday, October 8, 2010

Some tricky SQL queries (Interview Questions)

1.Select nth highest salary and name from emp table
SELECT DISTINCT (a.empsalary),a.Employee_Name FROM empData A WHERE  N =(SELECT COUNT (DISTINCT (b.empsalary)) FROM empData B WHERE a.empsalary<=b.empsalary);
--where N is your number (2nd or 5th)
e.g SELECT DISTINCT (a.empsalary),a.Employee_Name FROM empData A WHERE  5 =(SELECT COUNT (DISTINCT (b.empsalary)) FROM empData B WHERE a.empsalary<=b.empsalary);

2.Select query without using "Like" operator . For eg select employee name start with 'j' and city is 'Noida' in company_name

select * from empdata where CHARINDEX('j',Employee_name)=1 and CHARINDEX('Noida',company_name)>0




3.Select query for grouping 2 coulmns in one column using Case statement

select result=case when p1 is not null then p1 when p2 is not null then p2 end from tbltest



4.Create identity like coulmn in query

select row_number () over( order by p1) as sno, result=case when p1 is not null then p1 when p2 is not null then p2 end from tbltest