SQL Tutorial
SQL is a standard language for storing, manipulating and retrieving data
in databases.
Our SQL tutorial will teach you how to use SQL in: MySQL, SQL Server,
MS Access, Oracle, Sybase, Informix, Postgres, and other database
systems.
SQL Query Interview Questions with Answers
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-
SELECT COUNT(*) FROM EmployeeSalary WHERE Project = 'P1';
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.
SELECT Project, count(EmpId) EmpProjectCount
FROM EmployeeSalary
GROUP BY Project
ORDER BY EmpProjectCount DESC;
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.
mySQL- Using MID
SELECT MID(FullName, 0, LOCATE(' ',FullName)) FROM EmployeeDetails;
SQL Server-Using SUBSTRING
SELECT SUBSTRING(FullName, 0, CHARINDEX(' ',FullName)) FROM EmployeeDetails;
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.
SELECT E.FullName, S.Salary
FROM EmployeeDetails E LEFT JOIN EmployeeSalary S
ON E.EmpId = S.EmpId;