SQL Query Interview Questions With Answers
SQL Query Interview Questions With Answers
SQL Query Interview Questions With Answers
Hello friends! in this post we will see some of the most commonly asked SQL queries in
interviews. The questions will start from very basic questions and then move to more
complex problems. Consider the below two tables for most of the questions asked here.
Ques.1. Write a SQL query to fetch the count of employees working in project 'P1'.
Ans. Here, we would be using aggregate function count() with the SQL where clause-
Ques.2. Write a SQL query to fetch employee names having salary greater than or
equal to 5000 and less than or equal 10000.
Ans. Here, we will use BETWEEN in the 'where' clause to return the empId of the employees
with salary satifying the required criteria and then use it as subquery to find the fullName of
the employee form EmployeeDetails table.
SELECT FullName
FROM EmployeeDetails
WHERE EmpId IN
(SELECT EmpId FROM EmpolyeeSalary
WHERE Salary BETWEEN 5000 AND 10000);
Ques.3. Write a SQL query to fetch project-wise count of employees sorted by project's
count in descending order.
Ans. The query has two requirements - first to fetch the project-wise count and then to sort
the result by that count. For project wise count, we will be using GROUPBY clause and for
sorting, we will use ORDER BY clause on the alias of the project-count.
Ques.4. Write a query to fetch only the first name(string before space) from the
FullName column of EmployeeDetails table.
Ans. In this question, we are required to first fetch the location of the space character in the
FullName field and then extract the first name out of the FullName field. For finding the
location we will use LOCATE method in mySQL and CHARINDEX in SQL SERVER and
for fetching the string before space, we will use SUBSTRING OR MID method.
Also, we can use LEFT which returns the left part of a string till specified number of
characters.
SELECT LEFT(FullName, CHARINDEX(' ',FullName) - 1) FROM EmployeeDetails;
Ques.5. Write a query to fetch employee names and salary records. Return employee
details even if the salary record is not present for the employee.
Ans. Here, we can use left join with EmployeeDetail table on the left side.
Ques.6. Write a SQL query to fetch all the Employees who are also managers from
EmployeeDetails table.
Ans. Here, we have to use Self-Join as the requirement wants us to analyze the
EmployeeDetails table as two different tables, each for Employee and manager records.
Ques.9. Write a SQL query to remove duplicates from a table without using temporary
table.
Ans. Using Group By and Having clause-
Ques.10. Write a SQL query to fetch only odd rows from table.
Ans. This can be achieved by using Row_number in SQL server-
Ques.12. Write a SQL query to create a new table with data and structure copied from
another table.
Ans. Using SELECT INTO command-
Ques.13. Write a SQL query to create an empty table with same structure as some other
table.
Ans. Using SELECT INTO command with False 'WHERE' condition-
This can also done using mySQL 'Like' command with CREATE statement-
Ques.14. Write a SQL query to fetch common records between two tables.
Ans. Using INTERSECT-
Ques.15. Write a SQL query to fetch records that are present in one table but not in
another table.
Ans. Using MINUS-
SELECT NOW();
SQL Server-
SELECT getdate();
Oracle-
Ques.17. Write a SQL query to fetch all the Employees details from EmployeeDetails
table who joined in Year 2016.
Ans. Using BETWEEN for the date range '01-01-2016' AND '31-12-2016'-
Also, we can extract year part from the joining date (using YEAR in mySQL)-
Ques.19. Write SQL query to find the nth highest salary from table.
Ans. Using Top keyword (SQL Server)-
SELECT TOP 1 Salary
FROM (
SELECT DISTINCT TOP N Salary
FROM Employee
ORDER BY Salary DESC
)
ORDER BY Salary ASC
Ques.20. Write SQL query to find the 3rd highest salary from table without using
TOP/limit keyword.
Ans. The below SQL query make use of correlated subquery wherein in order to find the 3rd
highest salary the inner query will return the count of till we find that there are two rows that
salary greater than other distinct salaries.
SELECT Salary
FROM EmployeeSalary Emp1
WHERE 2 = (
SELECT COUNT( DISTINCT ( Emp2.Salary ) )
FROM EmployeeSalary Emp2
WHERE Emp2.Salary > Emp1.Salary
)
SELECT Salary
FROM EmployeeSalary Emp1
WHERE N-1 = (
SELECT COUNT( DISTINCT ( Emp2.Salary ) )
FROM EmployeeSalary Emp2
WHERE Emp2.Salary > Emp1.Salary
Ques.1. What is a database?
Ans. A database is a structured collection of data for faster and better access, storage and
manipulation of data.
A database can also be defined as collection of tables, schema, views and other database
objects.
Ques.10. Explain DDL commands. What are the different DDL commands in SQL?
Ans. DDL refers to Data Definition Language, it is used to define or alter the structure of the
database. The different DDL commands are-
Ques.11. Explain DML commands. What are the different DML commands in SQL?
Ans. DML refers to Data Manipulation Language, it is used for managing data present in the
database. Some of the DML commands are-select, insert, update, delete etc.
Ques.12. Explain DCL commands. What are the different DCL commands in SQL?
Ans. DCL refers to Data Control Language, these commands are used to create roles, grant
permission and control access to the database objects. The three DCL commands are-
Ques.17. What is the difference between unique key and primary key?
Ans. A unique key allows null value(although only one) but a primary key doesn't allow null
values. A table can have more than one unique keys columns while there can be only one
primary key. A unique key column creates non-clustered index whereas primary key creates a
clustered index on the column.
CREATE TABLE EMP_SALARY(EmpID int NOT NULL, NAME VARCHAR (30) NOT NULL,
Salary INT CHECK (Salary > 1000), PRIMARY KEY (EmpID));
Delete command is a DML command, it removes rows from table based on the
condition specified in the where clause, being a DML statement we can rollback
changes made by delete command.
Truncate is a DDL command, it removes all the rows from table and also frees the
space held unlike delete command. It takes lock on the table while delete command
takes lock on rows of table.
Drop is a DDL command, it removes the complete data along with the table
structure(unlike truncate command that removes only the rows).
1. Inner Join - To fetch rows from two tables having matching data in the specified
columns of both the tables.
2. SELECT * FROM TABLE1 INNER JOIN TABLE2 ON TABLE1.columnA =
TABLE2.columnA;
3. Left Join - To fetch all rows from left table and matching rows of the right table
4. SELECT * FROM TABLE1 LEFT JOIN TABLE2 ON TABLE1.columnA =
TABLE2.columnA;
5. Right Join - To fetch all rows from right table and matching rows of the left table
6. SELECT * FROM TABLE1 RIGHT JOIN TABLE2 ON TABLE1.columnA =
TABLE2.columnA;
7. Full Outer Join - To fetch all rows of left table and all rows of right table
8. SELECT * FROM TABLE1 FULL OUTER JOIN TABLE2 ON TABLE1.columnA =
TABLE2.columnA;
9. Self Join - Joining a table to itself, for referencing its own data
10. SELECT * FROM TABLE1 T1, TABLE1 T2 WHERE T1.columnA = T2.columnB;
Ques.28. What is the difference between cross join and full outer join?
Ans. A cross join returns cartesian product of the two tables, so there is no condition or on
clause as each row of tabelA is joined with each row of tableB whereas a full outer join will
join the two tables on the basis of condition specified in the on clause and for the records not
satisfying the condition null value is placed in the join result.
For example - for a table with Employee and Project fields, if we want to fetch Employee
working on a particular project P2, we will use 'where' clause-
Now if we want to fetch Employees who are working on more than one project, we will first
have to group the Employee column along with count of project and than the 'having' clause
can be used to fetch relevant records-
Ques.30. What is the difference between Union and Union All command?
Ans. The fundamental difference between Union and Union All command is, Union is by
default distinct i.e. it combines the distinct result set of two or more select statements.
Whereas, Union All combines all the rows including duplicates in the result set of different
select statements.
1. Atomicity - All the operations in the transaaction are performed as a whole or not
performed at all.
2. Consistency - State of database changes only on successful committed transaction.
3. Isolation - Even with concurrent execution of the multiple transactions, the final state
of the DB would be same as if transactions got executed sequentially. In other words
each transaction is isolated from one another.
4. Durability - Even in the state of crash or power loss the state of committed transaction
remain persistent.
Count() - Returns the count of the number of rows returned by the SQL expression
Max() - Returns the max value out of the total values
Min() - Returns the min value out of the total values
Avg() - Returns the average of the total values
Sum() - Returns the sum of the values returned by the SQL expression
Ques.44. What are scalar functions in SQL?
Ans. Scalar functions are the functions that return a single value by processing a single value
in SQL. Some of the widely used SQL functions are-
CREATE PROCEDURE
procedureName
AS
Begin
Set of SQL statements
End
CREATE TRIGGER
triggerName
triggerTime{Before or After}
triggerEvent{Insert, Update or Delete}
ON tableName
FOR EACH ROW
triggerBody
DELETE PT
FROM ParentTable PT
LEFT JOIN ChildTable CT
ON PT.ID = CT.ID
WHERE PT.ID IS NULL
*Remember: Delete with joins requires name/alias before from clause in order to specify the
table of which data is to be deleted.