0% found this document useful (0 votes)
25 views

Most Asked SQL Queries In Interviews

The document provides a comprehensive list of frequently asked SQL queries in technical interviews, along with sample tables and detailed answers. It covers various topics such as retrieving employee details, handling duplicates, finding salaries, and using SQL functions. The content is aimed at helping candidates prepare for SQL-related interview questions without theoretical explanations.

Uploaded by

Harindra Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Most Asked SQL Queries In Interviews

The document provides a comprehensive list of frequently asked SQL queries in technical interviews, along with sample tables and detailed answers. It covers various topics such as retrieving employee details, handling duplicates, finding salaries, and using SQL functions. The content is aimed at helping candidates prepare for SQL-related interview questions without theoretical explanations.

Uploaded by

Harindra Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

C# Corner

Most Asked SQL Queries In Interviews


Do you wonder what the most frequently asked SQL queries are in interviews? Here is a list of most asked SQL queries in
interviews.

Tushar Dikshit Feb 26 2019

26 40 280.1k

Download Free .NET & JAVA Files API

This article is an attempt to answer the most asked essential queries in SQL Server technical interviews, based on my own
experience. No theoretical questions are included; this article is meant to be helpful in technical coding interviews.

Sample tables are listed to visualize the data and associate with query answers given.

01. ==================
02. Consider below tables
03. ==================

01. EMPLOYEE
02. empid empname managerid deptid salary DOB
03. 1 emp 1 0 1 6000 1982-08-06 00:00:00.000
04. 2 emp 2 0 5 6000 1982-07-11 00:00:00.000
05. 3 emp 3 1 1 2000 1983-11-21 00:00:00.000
06. 13 emp 13 2 5 2000 1984-03-09 00:00:00.000
07. 11 emp 11 2 1 2000 1989-07-23 00:00:00.000
08. 9 emp 9 1 5 3000 1990-09-11 00:00:00.000
09. 8 emp 8 3 1 3500 1990-05-15 00:00:00.000
10. 7 emp 7 2 5 NULL NULL
11. 3 emp 3 1 1 2000 1983-11-21 00:00:00.000
12.
13. --DEPARTMENT TABLE
14. deptid deptname
15. 1 IT
16. 2 Admin

1. Employee and Manager ID are in the same table; can you get manager names
for employees?
Answer:

With the help of Common table expressions, we can achieve this.

01. ;with empCTE as


02. (
03. select e.empid, e.empname, e.managerid,
04. CAST('' as varchar(50)) as Mname from employee e
05. where managerid = 0
06.
07. union all
08.
09. select e1.empid, e1.empname, e1.managerid,
10. CAST(c.empname as varchar(50)) as Mname from employee e1
11. inner join empCTE as C on e1.managerid=c.empid
12. where e1.managerid>0
12. where e1.managerid>0
13. ) select * from empCTE

2. Can you get employee details whose department id is not valid or department id
not present in department table?
Answer

Identifying Department IDs in employee table, which are not available in master.

There are multiple ways to do this.

Using Left JOIN

01. SELECT E.EMPID,E.EMPNAME, E.DEPTID FROM EMPLOYEE E


02. left outer join DEPARTMENT d
03. on E.DEPTID = D.DEPTID
04. WHERE D.DEPTID IS NULL

Using NOT IN

01. SELECT E.EMPID,E.EMPNAME, E.DEPTID FROM EMPLOYEE E


02. where e.deptid not in (select deptid from department)

Using NOT Exists

01. SELECT E.EMPID,E.EMPNAME, E.DEPTID FROM EMPLOYEE E


02. where NOT EXISTS (select deptid from department where e.deptid=department.deptid)

Note

"Not In" is the least recommended, considering performance. Outer join and Not Exists are preferred.

Using EXCEPT KEYWORD

if you want to list Department IDs only. INTERSECT and EXCEPT keywords have rules

01. SELECT deptid FROM EMPLOYEE


02. EXCEPT
03. SELECT DEPTID FROM DEPARTMENT

3. Can you get the list of employees with same salary?


Answer

With where clause

01. Select distinct e.empid,e.empname,e.salary


02. from employee e, employee e1
03. where e.salary =e1.salary
04. and e.empid != e1.empid

4. How can you find duplicate records in Employee table?


Answer

01. SELECT EMPID,EMPNAME, SALARY, COUNT(*) AS CNT


02. FROM EMPLOYEE
03. GROUP BY EMPID,EMPNAME, SALARY
04. HAVING COUNT(*)>1

5. How can you DELETE DUPLICATE RECORDS?


Answer
There are multiple options to perform this operation.

Using row count to restrict delete only 1 record

01. set rowcount 1


02. DELETE FROM EMPLOYEE WHERE EMPID IN (
03. SELECT EMPID
04. FROM EMPLOYEE
05. GROUP BY EMPID,EMPNAME, SALARY
06. HAVING COUNT(*)>1
07. )
08. set rowcount 0

Use auto increment primary key "add" if not available in the table, as in given example.

01. alter table employee


02. add empidpk int identity (1,1)

Now, perform query on min of auto pk id, group by duplicate check columns - this will give youlatest duplicate records

01. select * from employee where


02. empidpk not in ( select min(empidpk) from employee
03. group by EMPID,EMPNAME, SALARY )

Now, delete.

01. Delete from employee where


02. empidpk not in ( select min(empidpk) from employee
03. group by EMPID,EMPNAME, SALARY )

6. Find the second highest salary.


Answer

01. Select max(Salary) from employee


02. where Salary not in (Select max(Salary) from employee)

7. Now, can you find 3rd, 5th or 6th i.e. N'th highest Salary?
Answer

Query for 3rd highest salary

01. SELECT * FROM EMPLOYEE E


02. WHERE 2 = (SELECT COUNT(DISTINCT E1.SALARY)
03. FROM EMPLOYEE E1
04. WHERE E1.SALARY>E.SALARY)

Here, 2= 3-1 i.e. N-1 ; can be applied for any number.

8. Can you write a query to find employees with age greater than 30?
Answer

01. select * from employee


02. where datediff(year,dob, getdate()) >30

9. Write an SQL Query to print the name of the distinct employees whose DOB is
between 01/01/1960 to 31/12/1987
Answer

01. SELECT DISTINCT EmpName FROM Employee


02. WHERE DOB BETWEEN '01/01/1960' AND '12/31/1987'
10. Please write a query to get the maximum salary from each department.
Answer

01. select DeptId, max(salary) as Salary from employee group by deptid

11. What is wrong with the following query?


01. SELECT empName FROM employee WHERE salary <> 6000

Answer

The following query will not fetch record with the salary of 6000 but also will skip the record with NULL.

As per SQL Server logic, it works on 3 values in matching conditions. TRUE or FALSE and UNKNOWN. Here, NULL
implies UNKNOWN.

to fix this:

01. SELECT empName FROM


02. employee WHERE salary is NULL or salary <> 6000

12. Can you show one row twice in results from a table?
Answer

Yes. We can use union all or cross join to obtain this.

01. select deptname from department d where d.deptname='it'


02. union all
03. select deptname from department d1 where d1.deptname='it'

-- also cross join alias same table

01. select d.deptname from department d, department d1


02. where d.deptname='it'

13. Could you tell the output or result of the following SQL statements?
Answer

01. select '7'


02. -- output = 7
03. select 7
04. -- output = 7
05. select count (7)
06. -- output = 1
07. SELECT COUNT('7')
08. -- output = 1
09. SELECT COUNT(*)
10. -- output = 1

14. What is an alternative for TOP clause in SQL?


Answer

- There can be two alternatives for the top clause in SQL.

#1
-- Alternative - ROWCOUNT function

01. Set rowcount 3


02. Select * from employee order by empid desc
03. Set rowcount 0
#2
-- Alternative and WITH and ROWNUMBER function
-- between 1 and 2

01. With EMPC AS


02. ( SELECT empid, empname,salary,
03. ROW_NUMBER() OVER (order by empid desc) as RowNumber
04. FROM employee )
05. select *
06. from EMPC
07. Where RowNumber Between 1 and 7

15. Will the following statements run or give error?


Answer

NO error.

01. SELECT COUNT(*) + COUNT(*)


02. Output = 2
03. SELECT (SELECT 'c#')
04. Output = c#

16. Can you write a query to get employee names starting with a vowel?
Answer

Using like operator and expression,

01. Select empid, empname from employee where empname like '[aeiou]%'

17. Can you write a query to get employee names ending with a vowel?
Answer

01. Select empid, empname from employee where empname like '%[aeiou]'

18. Can you write a query to get employee names starting and ending with a
vowel?
Answer

Here you will get only one record of "empone".

01. select empid, empname from employee where empname like '[aeiou]%[aeiou]'

19. Write a query to get employees whos ID is even.


Answer

01. select * from employee


02. where empid %2 =0

20. Write a query to get employees whos ID is an odd number.


Answer

01. select * from employee


02. where empid %2 !=0

21. How can you get random employee record from the table?
Answer
01. select top 1 * from employee order by newid()

22.(Tricky) Below is the table data which has 1 columns and 7 rows
01. Table -TESTONE
02.
03. DATACOL
04. 10/12
05. 1a/09
06. 20/14
07. 20/1c
08. 3112
09. 11/16
10. mm/pp

Give data in a table is of format 'NN/NN', verify that the first and last two characters are numbers and that the middle
character is '/'.

Answer

Print the expression 'NUMBER' if valid, 'NOT NUM' if not valid.

This can be done using like operator and expression. Checking numbers and not characters.

01. SELECT DataCol, 'CHECK' =


02. CASE
03. WHEN datacol like '%[0-9]%[^A-Z]%/%[^A-Z]%[0-9]%' then 'NUMBER'
04. else 'NOT NUM'
05. end
06. from TestOne

23. Consider following 3 tables with one column


01. Tbl1
02. col1
03. 1
04. 1
05. 1
06.
07. Tbl2
08. col1
09. 2
10. 2
11. 2
12.
13. Tbl3
14. col1
15. 3
16. 3
17. 3

How many rows will following query return? (0, 3 or 9)

01. Select * from Tbl1 inner join tbl2 on tbl1.col1=tbl2.col1


02. Left outer join Tbl3 on Tbl3.Col1=Tbl2.Col1

Answer- 0 .

24. If all values from tbl2 are deleted. What will be the output of the following
query?
Answer

select Tbl1.* from tbl1,tbl2


Ans - 0 Rows.
25. Can you write a query to print prime numbers from 1 to 100?
Answer

For this, we have to use a loop as in other programming languages.

01. DECLARE
02.
03. @i INT,
04. @a INT,
05. @count INT,
06. @result varchar(Max)
07.
08. SET @i = 1
09. set @result=''
10.
11. WHILE (@i <= 100)
12. BEGIN
13. SET @count = 0
14. SET @a = 1
15.
16. -- logic to check prime number
17. WHILE (@a <= @i)
18. BEGIN
19. IF (@i % @a = 0)
20. SET @count = @count + 1
21.
22. SET @a = @a + 1
23. END
24.
25. IF (@count = 2)
26. set @result = @result+cast(@i as varchar(10))+' , '
27.
28. SET @i = @i + 1
29. END
30.
31. set @result = (select substring(@result, 1, (len(@result) - 1)))
32. print(@result)

26. Write query to print numbers from 1 to 100 without using loops
Answer

This can be done using Common Table Expression without using a loop.

01. ;with numcte


02. AS
03. (
04. SELECT 1 [SEQUENCE]
05.
06. UNION ALL
07.
08. SELECT [SEQUENCE] + 1 FROM numcte WHERE [SEQUENCE] <100
09. )
10.
11. SELECT * FROM numcte

27. What will be the output of following SQL?(tricky)


01. Select $
02.
03. Options -
04. a. 0.00,
05. b. $,
06. c. 0,
07. d. Syntax Error
08.
09. Answer = 0.00
28. What will be the output of following SQL queries?
01. Select select 'TD'

01. Options -
02. 1. TD,
03. 2. Syntax Error,
04. 3. select TD
05.
06. Answer - Syntax Error. (Incorrect syntax near the keyword 'select'. )
07.

01. select * from 'Employee'


02.
03. Answer - Incorrect syntax near 'Employee' .

29. What will be the outputs in the following SQL queries with aggregate
functions?
01. SELECT SUM (1+4*5)
02.
03. Options - a.21, b.25, c.Error d.10
04.
05. Answer -: 21
06.
07.
08. SELECT MAX (1,3,8)
09.
10. Options - a.8, b. 12, c.Error d.1
11.
12. Answer -: Error. Max function takes only 1 argument.
13.
14.
15. SELECT Max ('TD')
16.
17. Options - a.TD b. Error c. 1 d.0
18.
19. Answer-: TD
20.
21.
22. SELECT Max ('TD'+'AD')
23.
24. Options - a.TDAD b. Error c. T2D d.0
25. Answer-: TDAD

30. What will be the output of following queries? [Tricky involving 0]


01. SELECT 0/0
02.
03. A. Divide by 0 error, B. 0
04. C. NULL, D. Incorrect syntax error
05.
06. Answer -: Divide by 0 error
07.
08. SELECT 0/6
09.
10. A. Divide by 0 error, B. 0
11. C. 6, D. Incorrect syntax error
12.
13. Answer -: 0

31 What will be the output of given statement?


SELECT SUM (NULL)

Answer = Error. Cannot pass null type in SUM function.

Operand data type NULL is invalid for avg operator.


32. What will be the output of given statement?
SELECT
MAX (NULL)

Answer = Error. Operand data type NULL is invalid for MAX operator.

33. Will following statement give error or 0 as output?


SELECT
AVG (NULL)

Answer = Error. Operand data type NULL is invalid for Avg operator.

Note

MIN, MAX,SUM,AVG none of these function takes NULL parameter/argument. Also, these functions accept only one
argument.

34. Will the following statements execute? if yes what will be output?
SELECT NULL+1
SELECT NULL+'1'

Answer - Yes, no error. The output will be NULL. Perform any operation on NULL will get the NULL result.

35. Will following statement give Divide by Zero error?


SELECT NULL/0

Answer- No. It will execute and result will be NULL.

SQL Interview Questions SQL Queries

Tushar Dikshit
Building software applications for 12 years. Microsoft Certified in Architecting AZURE solutions. (#70534). Certified Scrum Master
leading agile projects.

703 295.5k

View Previous Comments

26 40
Type your comment here and press Enter Key (Minimum 10 characters)

Thanks for the tip, I have a great book as well, regarding the SQL coding interviews, Matthew Urban "TOP 30 SQL Interview
Coding Tasks", I bought mine on Amazon in kindle version, they also have paperback. I think it's the best when wanting to quickly
check what may be asked during the interview. https://www.amazon.com/TOP-SQL-Interview-Coding-Tasks-
ebook/dp/B07GC5RS3K
Br Conor Apr 09, 2019
1776 2 0 0 0 Reply

Thanks a lot for the qThanks a lot for the questions, really helpful for interviews and in real-time too.uestions, really helpful for
interviews and in real-time too.
mhamd abd Dec 16, 2018
1595 183 261 1 1 Reply

Thank you!
Tushar Dikshit Mar 01, 2019
703 1.7k 295.5k 0

Very helpful
Ravindar Kumar Oct 22, 2018
1720 58 0 1 1 Reply

Thank you Ravindar!


Tushar Dikshit Oct 23, 2018
703 1.7k 295.5k 0

Thanks a lot for the questions, really helpful for interviews and in real-time too.
Sanjay Singh Chouhan Sep 06, 2018
1670 108 0 2 1 Reply

Thank you Sanjay.


Tushar Dikshit Sep 07, 2018
703 1.7k 295.5k 0

sas fds For Question 7 we can write like select * from employee where salary not in (select top 2 * from employee order by salary asc)
sas fds Aug 30, 2018
1774 4 0 2 1 Reply

You can use Top clause and IN clause, also max,min functions. It is previous approach for such queries, specially
second highest, but in case you want to formulate for Nth then above approach is good.
Tushar Dikshit Sep 04, 2018
703 1.7k 295.5k 0

sas fds Will SELF JOIN wont work for your Question 1
sas fds Aug 30, 2018
1774 4 0 0 3 Reply

sas fds Select empid,empname,manageridfrom employee e,employee e1 where e.empid=e1.empid and e.managerid>0
sas fds Aug 30, 2018
1774 4 0 0

I think yes, self join works in such queries.


Tushar Dikshit Oct 10, 2018
703 1.7k 295.5k 0

Thanks for your contribution to post :)


Tushar Dikshit Oct 10, 2018
703 1.7k 295.5k 0
Thank you all for keeping this post active with reads and comments.!!!
Tushar Dikshit Aug 13, 2018
703 1.7k 295.5k 1 0 Reply

I'm just commenting alternate queries. --To find second highest salary SELECT MIN (SALARY) FROM EMPLOYEE WHERE
SALARY IN (SELECT DISTINCT TOP 2 salary FROM employee ORDER BY SALARY DESC) ---To find third highest salary
SELECT TOP 1 SALARY FROM EMPLOYEE WHERE SALARY IN (SELECT DISTINCT TOP 3 salary FROM employee ORDER
BY SALARY DESC) ORDER BY SALARY ASC --To find second highest salary using CTE WITH SecondHighestSalaryCTE AS
(SELECT DISTINCT TOP 2 SALARY FROM employee ORDER BY salary DESC) SELECT MIN(SALARY) AS [Second Highest
Salary] FROM SecondHighestSalaryCTE
Ashok Chawdry Aug 13, 2018
1758 20 0 3 0 Reply

Q1 Employee and Manager ID are in the same table; can you get manager names for employees? Answer: Self Join select
e1.empname as EmployeeName,e2.empname as ManagerName from employee e1 join employee e2 on e1.managerid = e2.empid
order by e1.empid
Ashok Chawdry Aug 10, 2018
1758 20 0 1 0 Reply

Always contributors of C# corner rockz


Sasi Rekha May 21, 2018
1328 454 16.5k 1 1 Reply

Thank you Rekha, C# corner rokz. :)


Tushar Dikshit May 22, 2018
703 1.7k 295.5k 0

About Us Contact Us Privacy Policy Terms Media Kit Sitemap Report a Bug FAQ Partners C# Tutorials
©2019 C# Corner. All contents are copyright of their authors.

You might also like