25 SQL Queries Interview Questions and Answers
Prepare for your next technical interview with our comprehensive guide on SQL queries, designed to enhance your database management skills.
Prepare for your next technical interview with our comprehensive guide on SQL queries, designed to enhance your database management skills.
SQL (Structured Query Language) is a fundamental tool for managing and manipulating relational databases. It is essential for tasks such as querying data, updating records, and managing database structures. SQL’s versatility and efficiency make it a critical skill for roles in data analysis, software development, and database administration. Mastery of SQL can significantly enhance your ability to work with large datasets and optimize database performance.
This article offers a curated selection of SQL query questions designed to help you prepare for technical interviews. By working through these examples, you will gain a deeper understanding of SQL concepts and improve your problem-solving abilities, ensuring you are well-prepared to demonstrate your expertise in any interview setting.
To select all columns from a table named ’employees’, use:
SELECT * FROM employees;
This query retrieves all data from the ’employees’ table without listing each column individually.
To select employees with a salary greater than 50000, use:
SELECT * FROM employees WHERE salary > 50000;
To join ’employees’ and ‘departments’ tables on the department_id column, use:
SELECT employees.employee_id, employees.employee_name, departments.department_name FROM employees INNER JOIN departments ON employees.department_id = departments.department_id;
This query combines rows from both tables where department_id matches.
To count employees in each department, use:
SELECT department_id, COUNT(*) AS employee_count FROM employees GROUP BY department_id;
To group employees by job title and calculate the average salary, use:
SELECT job_title, AVG(salary) AS average_salary FROM employees GROUP BY job_title;
To filter groups with an average salary greater than 60000, use:
SELECT department, AVG(salary) as avg_salary FROM employees GROUP BY department HAVING AVG(salary) > 60000;
To sort employees by hire date in descending order, use:
SELECT * FROM employees ORDER BY hire_date DESC;
To find employees earning more than the average salary, use a subquery:
SELECT employee_id, employee_name, salary FROM employees WHERE salary > (SELECT AVG(salary) FROM employees);
To select distinct job titles from the ’employees’ table, use:
SELECT DISTINCT job_title FROM employees;
To concatenate the first and last names of employees, use:
SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM employees;
Or, in PostgreSQL:
SELECT first_name || ' ' || last_name AS full_name FROM employees;
To find duplicate records, use:
SELECT column1, column2, COUNT(*) FROM table_name GROUP BY column1, column2 HAVING COUNT(*) > 1;
Replace column1
and column2
with the columns to check for duplicates.
To calculate the cumulative sum of salaries within each department, use:
SELECT department_id, employee_id, salary, SUM(salary) OVER (PARTITION BY department_id ORDER BY employee_id) AS cumulative_salary FROM employees;
A foreign key is a column in one table that references a column in another table, ensuring referential integrity. For example:
CREATE TABLE Departments ( DepartmentID INT PRIMARY KEY, DepartmentName VARCHAR(50) ); CREATE TABLE Employees ( EmployeeID INT PRIMARY KEY, EmployeeName VARCHAR(50), DepartmentID INT, FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID) );
To extract the year from the hire date, use:
SELECT employee_id, hire_date, YEAR(hire_date) AS hire_year FROM employees;
To combine results from different departments, use UNION:
SELECT employee_id, employee_name, department FROM employees WHERE department = 'Sales' UNION SELECT employee_id, employee_name, department FROM employees WHERE department = 'Marketing';
An index improves query performance by allowing the database to find rows more quickly. Types include primary, unique, composite, clustered, and non-clustered indexes.
To rank employees by salary within each department, use:
SELECT employee_id, department_id, salary, RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS salary_rank FROM employees;
A Common Table Expression (CTE) simplifies complex queries. For listing employees and their managers:
WITH EmployeeCTE AS ( SELECT e.EmployeeID, e.EmployeeName, e.ManagerID, m.EmployeeName AS ManagerName FROM Employees e LEFT JOIN Employees m ON e.ManagerID = m.EmployeeID ) SELECT EmployeeID, EmployeeName, ManagerID, ManagerName FROM EmployeeCTE;
To generate a hierarchical list of employees and subordinates, use a recursive CTE:
WITH RECURSIVE EmployeeHierarchy AS ( SELECT EmployeeID, EmployeeName, ManagerID FROM Employees WHERE ManagerID IS NULL UNION ALL SELECT e.EmployeeID, e.EmployeeName, e.ManagerID FROM Employees e INNER JOIN EmployeeHierarchy eh ON e.ManagerID = eh.EmployeeID ) SELECT * FROM EmployeeHierarchy;
To log changes to the ’employees’ table, create a trigger:
CREATE TABLE employee_changes ( change_id INT AUTO_INCREMENT PRIMARY KEY, employee_id INT, change_type VARCHAR(10), change_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); DELIMITER // CREATE TRIGGER log_employee_changes AFTER UPDATE ON employees FOR EACH ROW BEGIN INSERT INTO employee_changes (employee_id, change_type) VALUES (NEW.employee_id, 'UPDATE'); END; // DELIMITER ;
To create a view showing employees and department names:
CREATE VIEW EmployeeDepartmentView AS SELECT e.employee_id, e.employee_name, d.department_name FROM employees e JOIN departments d ON e.department_id = d.department_id;
Techniques for optimizing SQL query performance include indexing, query rewriting, schema design, using EXPLAIN, partitioning, connection pooling, and caching.
Partitioning a large table divides it into smaller parts, improving query performance and manageability. Use cases include time-series data, geographical data, archival, and data warehousing.
To extract data from a JSON column in PostgreSQL:
SELECT details->>'name' AS name, details->>'email' AS email FROM users;
In MySQL:
SELECT JSON_UNQUOTE(JSON_EXTRACT(details, '$.name')) AS name, JSON_UNQUOTE(JSON_EXTRACT(details, '$.email')) AS email FROM users;
To parse and extract data from an XML column in SQL Server:
DECLARE @xmlData XML SET @xmlData = '<root><item><id>1</id><name>Item1</name></item><item><id>2</id><name>Item2</name></item></root>' SELECT x.value('(id)[1]', 'INT') AS ItemID, x.value('(name)[1]', 'VARCHAR(100)') AS ItemName FROM @xmlData.nodes('/root/item') AS T(x)