give most asked common sql queries interview
- User
give most asked common sql queries interview
- Assistant
give most asked common sql queries interview
Preparing for SQL interviews involves understanding a variety of questions that test your knowledge of database concepts, query writing, and problem-solving skills. Below is a compilation of some of the most commonly asked SQL interview questions, along with brief explanations and example queries to help you prepare effectively.
Question:
Retrieve all columns from the Employees table.
Example Query:
SELECT * FROM Employees;
Question:
Find all employees from the Employees table who are older than 30.
Example Query:
SELECT *
FROM Employees
WHERE Age > 30;
Question:
Retrieve all employees sorted by their last name in ascending order.
Example Query:
SELECT FirstName, LastName
FROM Employees
ORDER BY LastName ASC;
Question:
Find the total number of employees in each department.
Example Query:
SELECT Department, COUNT(*) AS TotalEmployees
FROM Employees
GROUP BY Department;
Question:
Find departments with more than five employees.
Example Query:
SELECT Department, COUNT(*) AS TotalEmployees
FROM Employees
GROUP BY Department
HAVING COUNT(*) > 5;
a. INNER JOIN
Question:
Retrieve a list of employees along with their corresponding department names.
Example Query:
SELECT Employees.FirstName, Employees.LastName, Departments.DepartmentName
FROM Employees
INNER JOIN Departments ON Employees.DepartmentID = Departments.ID;
b. LEFT JOIN
Question:
Find all employees and their projects, including employees who are not assigned to any project.
Example Query:
SELECT Employees.FirstName, Employees.LastName, Projects.ProjectName
FROM Employees
LEFT JOIN Projects ON Employees.ProjectID = Projects.ID;
c. RIGHT JOIN and FULL OUTER JOIN
Similarly used to include all records from the right table or both tables, respectively.
Question:
Find employees who earn more than the average salary.
Example Query:
SELECT FirstName, LastName, Salary
FROM Employees
WHERE Salary > (SELECT AVG(Salary) FROM Employees);
Question:
Retrieve a list of unique job titles from the Jobs table.
Example Query:
SELECT DISTINCT JobTitle
FROM Jobs;
Question:
Retrieve the first 10 records from the Employees table.
Example Query (MySQL/PostgreSQL):
SELECT * FROM Employees
LIMIT 10;
Example Query (SQL Server):
SELECT TOP 10 * FROM Employees;
Question:
Find the second highest salary from the Employees table.
Example Query:
SELECT MAX(Salary) AS SecondHighestSalary
FROM Employees
WHERE Salary < (SELECT MAX(Salary) FROM Employees);
Alternatively, using OFFSET:
SELECT DISTINCT Salary
FROM Employees
ORDER BY Salary DESC
OFFSET 1 ROW FETCH NEXT 1 ROW ONLY;
Question:
Retrieve all employees who do not have a manager assigned.
Example Query:
SELECT FirstName, LastName
FROM Employees
WHERE ManagerID IS NULL;
Question:
Assign a grade based on the salary: 'High' for salaries above 100,000, 'Medium' for salaries between 50,000 and 100,000, and 'Low' for salaries below 50,000.
Example Query:
SELECT FirstName, LastName, Salary,
CASE
WHEN Salary > 100000 THEN 'High'
WHEN Salary BETWEEN 50000 AND 100000 THEN 'Medium'
ELSE 'Low'
END AS SalaryGrade
FROM Employees;
Question:
Use a CTE to find all employees and their direct managers.
Example Query:
WITH ManagerCTE AS (
SELECT
EmployeeID,
FirstName,
LastName,
ManagerID
FROM Employees
)
SELECT
e.FirstName AS EmployeeFirstName,
e.LastName AS EmployeeLastName,
m.FirstName AS ManagerFirstName,
m.LastName AS ManagerLastName
FROM ManagerCTE e
LEFT JOIN ManagerCTE m ON e.ManagerID = m.EmployeeID;
Question:
Calculate the running total of salaries ordered by employee ID.
Example Query:
SELECT
EmployeeID,
Salary,
SUM(Salary) OVER (ORDER BY EmployeeID) AS RunningTotal
FROM Employees;
Question:
Explain the purpose of indexes in a database and the difference between clustered and non-clustered indexes.
Answer:
Indexes improve the speed of data retrieval operations on a database table by providing quick access to rows.
Question:
Explain what transactions are and describe the ACID properties.
Answer:
A transaction is a sequence of one or more SQL operations treated as a single unit of work.
Question:
Transform rows into columns to display the total sales per quarter for each product.
Example Query (Using CASE):
SELECT
Product,
SUM(CASE WHEN Quarter = 'Q1' THEN Sales ELSE 0 END) AS Q1_Sales,
SUM(CASE WHEN Quarter = 'Q2' THEN Sales ELSE 0 END) AS Q2_Sales,
SUM(CASE WHEN Quarter = 'Q3' THEN Sales ELSE 0 END) AS Q3_Sales,
SUM(CASE WHEN Quarter = 'Q4' THEN Sales ELSE 0 END) AS Q4_Sales
FROM Sales
GROUP BY Product;
Example Query (SQL Server PIVOT):
SELECT Product, [Q1], [Q2], [Q3], [Q4]
FROM
(SELECT Product, Quarter, Sales FROM Sales) AS SourceTable
PIVOT
(
SUM(Sales)
FOR Quarter IN ([Q1], [Q2], [Q3], [Q4])
) AS PivotTable;
Question:
How would you optimize a slow-running query?
Answer:
Question:
Explain the different normal forms and why normalization is important.
Answer:
Normalization organizes database tables to reduce data redundancy and improve data integrity.
Normalization helps in minimizing duplication, preventing update anomalies, and ensuring data consistency.
Question:
Differentiate between stored procedures and functions in SQL.
Answer:
Stored Procedures:
Functions:
Question:
Use a recursive CTE to display an employee hierarchy.
Example Query:
WITH EmployeeHierarchy AS (
SELECT EmployeeID, FirstName, LastName, ManagerID, 0 AS Level
FROM Employees
WHERE ManagerID IS NULL
UNION ALL
SELECT e.EmployeeID, e.FirstName, e.LastName, e.ManagerID, eh.Level + 1
FROM Employees e
INNER JOIN EmployeeHierarchy eh ON e.ManagerID = eh.EmployeeID
)
SELECT *
FROM EmployeeHierarchy
ORDER BY Level, ManagerID;
Question:
Explain the difference between temporary tables and table variables.
Answer:
Temporary Tables:
Table Variables:
DECLARE statement.Question:
How can you remove duplicate rows from a table?
Example Query (Using CTE and ROW_NUMBER):
WITH DuplicateRecords AS (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY Column1, Column2, Column3 ORDER BY (SELECT 0)) AS rn
FROM TableName
)
DELETE FROM DuplicateRecords
WHERE rn > 1;
Question:
Describe methods to import data into an SQL database.
Answer:
BULK INSERT command.Question:
What is SQL injection and how can you prevent it?
Answer:
SQL Injection: A security vulnerability that allows attackers to interfere with the queries an application makes to its database by injecting malicious SQL code.
Prevention Techniques:
Question:
What is an execution plan and how do you use it to optimize queries?
Answer:
An execution plan is a graphical or textual representation of how the SQL database engine executes a query. It shows the steps taken to retrieve data, such as table scans, index seeks, joins, and more.
Usage for Optimization:
In SQL Server Management Studio (SSMS), you can view the execution plan by clicking on "Display Estimated Execution Plan" or "Include Actual Execution Plan" before running the query.
Question:
Explain the differences between DELETE, TRUNCATE, and DROP commands.
Answer:
DELETE:
TRUNCATE:
DROP:
Question:
What are the advantages and disadvantages of using indexes?
Answer:
Advantages:
Disadvantages:
Question:
What is a view in SQL and when would you use it?
Answer:
A view is a virtual table based on the result set of a SELECT query. It doesn't store data physically but provides a way to simplify complex queries, enhance security by restricting access to specific data, and present data in a particular format.
Uses:
Example:
CREATE VIEW ActiveEmployees AS
SELECT FirstName, LastName, Department
FROM Employees
WHERE Status = 'Active';
Question:
Briefly explain the differences between SQL and NoSQL databases.
Answer:
SQL Databases:
NoSQL Databases:
Preparing for SQL interviews requires not only understanding these concepts but also practicing writing and optimizing queries. Make sure to work on real-world scenarios and utilize various SQL features to build a strong foundation. Good luck with your interview preparation!