✅ Basic SQL Interview Questions
1. What is SQL?
SQL (Structured Query Language) is the standard language used to manage and manipulate relational
databases. It allows you to:
Create databases and tables (CREATE)
Insert data (INSERT)
Query data (SELECT)
Update data (UPDATE)
Delete data (DELETE)
It works on databases like MySQL, PostgreSQL, SQL Server, SQLite, Oracle, etc.
2. Types of SQL Statements
SQL commands are divided into:
DDL (Data Definition Language): Defines database structure
Examples: CREATE, ALTER, DROP, TRUNCATE
DML (Data Manipulation Language): Manages data within tables
Examples: INSERT, UPDATE, DELETE
DQL (Data Query Language): Queries data
Example: SELECT
DCL (Data Control Language): Controls access to data
Examples: GRANT, REVOKE
TCL (Transaction Control Language): Controls transactions
Examples: COMMIT, ROLLBACK, SAVEPOINT
3. DELETE vs TRUNCATE vs DROP
Feature DELETE TRUNCATE DROP
Deletes data Yes (row by row) Yes (all rows at once) Yes (entire table)
Can rollback Yes (with transaction) No No
Affects schema No No Yes (removes table)
Usage DELETE FROM students WHERE id=1; TRUNCATE TABLE students; DROP TABLE
students;
4. What are Constraints?
Constraints are rules to limit the type of data in a table.
NOT NULL – Value must not be NULL
UNIQUE – All values must be unique
PRIMARY KEY – Uniquely identifies each record
FOREIGN KEY – Links one table to another
CHECK – Validates a condition (CHECK (age >= 18))
DEFAULT – Sets a default value
5. Primary Key vs Foreign Key
Primary Key: Uniquely identifies a row in a table. Only one per table. Cannot be NULL.
Foreign Key: Establishes relationship with another table's primary key.
-- Primary Key Example
CREATE TABLE students (
student_id INT PRIMARY KEY,
name VARCHAR(50)
);
-- Foreign Key Example
CREATE TABLE marks (
mark_id INT,
student_id INT,
FOREIGN KEY (student_id) REFERENCES students(student_id)
);
6. WHERE vs HAVING
WHERE: Filters rows before grouping.
HAVING: Filters groups after grouping.
-- WHERE example
SELECT * FROM employees WHERE salary > 50000;
-- HAVING example
SELECT department, AVG(salary)
FROM employees
GROUP BY department
HAVING AVG(salary) > 50000;
7. GROUP BY Clause
Groups rows by column values, often used with aggregate functions.
SELECT department, COUNT(*) as total_employees
FROM employees
GROUP BY department;
8. CHAR vs VARCHAR
Type Description Example
CHAR Fixed length (padded) CHAR(10) stores "abc" as "abc "
VARCHAR Variable length VARCHAR(10) stores "abc" as "abc"
Use VARCHAR for most flexible storage.
9. Normalization
It is the process of organizing data to reduce redundancy.
1NF: Atomic columns (no multiple values in one column)
2NF: Remove partial dependencies (non-key depends on full key)
3NF: Remove transitive dependencies (non-key depends on another non-key)
Example: A table storing customer name and city multiple times can be split into two tables:
Customers and Cities.
10. Types of Joins
Join Type Description
INNER JOIN Returns only matching rows
LEFT JOIN All rows from left + matching from right
RIGHT JOIN All rows from right + matching from left
FULL JOIN All rows from both tables
SELECT A.name, B.course
FROM students A
INNER JOIN courses B
ON A.id = B.student_id;
⚙ Intermediate SQL Interview Questions – With Detailed Answers
11. What is a Subquery?
A subquery is a query nested inside another SQL query. It can be used in SELECT, FROM, or WHERE
clauses. Example: Find employees earning more than the average salary:
SELECT name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
🔸 If a subquery depends on the outer query, it is a correlated subquery.
12. What is a View?
A view is a virtual table based on a SQL query. It does not store data but simplifies complex queries.
Example: Create a view of active employees:
CREATE VIEW active_employees AS
SELECT name, department FROM employees WHERE status = 'Active';
To use it:
SELECT * FROM active_employees;
13. What is an Index?
An index speeds up search and retrieval of records in a table.
Clustered Index: Sorts the actual data rows (only one per table)
Non-Clustered Index: Contains a pointer to the data (can be many)
🔹 Example:
CREATE INDEX idx_name ON employees(name);
🔸 Indexes slow down INSERT and UPDATE, so use wisely.
14. Find the Second Highest Salary
SELECT MAX(salary) AS Second_Highest
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
Alternative using LIMIT (MySQL):
SELECT salary FROM employees ORDER BY salary DESC LIMIT 1 OFFSET 1;
15. RANK() vs DENSE_RANK() vs ROW_NUMBER()
Let’s say you have these salaries: 7000, 6000, 6000, 5000.
Function Output
RANK() 1, 2, 2, 4
DENSE_RANK() 1, 2, 2, 3
ROW_NUMBER() 1, 2, 3, 4
SELECT name, salary,
RANK() OVER (ORDER BY salary DESC) AS rank,
DENSE_RANK() OVER (ORDER BY salary DESC) AS dense_rank,
ROW_NUMBER() OVER (ORDER BY salary DESC) AS row_num
FROM employees;
16. Aggregate Functions
Used to perform calculations on data:
SUM() – Total
AVG() – Average
COUNT() – Total number of rows
MAX() – Highest value
MIN() – Lowest value
SELECT department, AVG(salary) FROM employees GROUP BY department;
17. What is a Stored Procedure?
A stored procedure is a saved block of SQL code that can be reused.
CREATE PROCEDURE GetEmployees()
BEGIN
SELECT * FROM employees;
END;
To run:
CALL GetEmployees();
Benefits: Reusability, Performance, Security.
18. UNION vs UNION ALL
Feature UNION UNION ALL
Duplicates Removed Not removed
Performance Slower Faster
SELECT name FROM students
UNION
SELECT name FROM teachers;
19. What are ACID Properties?
Used to ensure reliable transactions in databases.
Atomicity: All steps succeed or none.
Consistency: Database remains valid before and after transaction.
Isolation: Transactions don't interfere with each other.
Durability: Changes remain even after crash.
20. How to Handle NULL Values?
IS NULL / IS NOT NULL to check
COALESCE() to replace nulls
SELECT name, COALESCE(phone, 'Not Available') FROM students;
🔍 Advanced SQL Interview Questions
21. What is a CTE (Common Table Expression)?
Temporary result set used in complex queries.
WITH DepartmentSalary AS (
SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department
SELECT * FROM DepartmentSalary WHERE avg_salary > 50000;
22. Window Functions
Perform calculations across a set of rows without collapsing them.
SELECT name, department, salary,
RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS rank
FROM employees;
🔹 PARTITION BY is like GROUP BY, but the result is still row-wise.
23. What are Triggers?
Triggers are automatic actions executed in response to events like INSERT, UPDATE, DELETE.
CREATE TRIGGER trg_salary_check
BEFORE INSERT ON employees
FOR EACH ROW
BEGIN
IF NEW.salary < 10000 THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Salary too low!';
END IF;
END;
24. Correlated vs Non-Correlated Subqueries
Correlated Subquery: Depends on outer query row
SELECT name FROM employees e
WHERE salary > (SELECT AVG(salary) FROM employees WHERE department = e.department);
Non-Correlated: Runs independently
SELECT name FROM employees WHERE salary > (SELECT AVG(salary) FROM employees);
25. How to Improve SQL Query Performance?
Use indexes on searchable columns.
Avoid SELECT *, select only required columns.
Use EXISTS instead of IN where applicable.
Use LIMIT to avoid full-table scans.
Break large queries into smaller ones.
26. What is a Transaction?
Group of SQL operations that run as one unit.
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;
Use ROLLBACK to undo if there's an error.
27. MERGE Statement
Used for UPSERT (Insert or Update in one query).
MERGE INTO employees AS target
USING new_employees AS source
ON target.id = source.id
WHEN MATCHED THEN
UPDATE SET target.salary = source.salary
WHEN NOT MATCHED THEN
INSERT (id, name, salary) VALUES (source.id, source.name, source.salary);
28. Denormalization
The process of adding redundant data to speed up reads. Use when read speed > storage efficiency.
29. How to Handle Deadlocks
Access tables in same order
Keep transactions short
Use proper indexing to reduce lock time
30. Transpose Rows to Columns
Pivoting data manually:
SELECT
name,
MAX(CASE WHEN subject = 'Math' THEN marks END) AS Math,
MAX(CASE WHEN subject = 'Science' THEN marks END) AS Science
FROM results
GROUP BY name;
✅ Accenture SQL Interview Questions – Detailed with Answers
1. Find the Second Highest Salary
Question:
Write a query to find the second highest salary from an employees table.
Answer:
SELECT MAX(salary) AS Second_Highest
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
Explanation:
First, find the highest salary.
Then, get the max salary less than the highest — this gives second highest.
2. Difference Between WHERE and HAVING
WHERE Clause:
Used before grouping.
Works on rows.
HAVING Clause:
Used after GROUP BY.
Works on groups (aggregates).
Example:
-- WHERE
SELECT * FROM employees WHERE salary > 50000;
-- HAVING
SELECT department, AVG(salary)
FROM employees
GROUP BY department
HAVING AVG(salary) > 50000;
3. What Are Joins? Types of Joins
Joins combine rows from two or more tables using related columns.
Join Type Description
INNER JOIN Only matching rows
LEFT JOIN All left rows + matching right rows
RIGHT JOIN All right rows + matching left rows
FULL OUTER All matching and non-matching rows
Example:
SELECT a.name, b.salary
FROM employees a
INNER JOIN salaries b ON a.emp_id = b.emp_id;
4. Count Employees in Each Department
Question:
Write a query to find the total number of employees per department.
Answer:
SELECT department, COUNT(*) AS total_employees
FROM employees
GROUP BY department;
5. Employees with Same Salary
Question:
Find salaries shared by more than one employee.
Answer:
SELECT salary, COUNT(*) AS num_employees
FROM employees
GROUP BY salary
HAVING COUNT(*) > 1;
6. What Are ACID Properties?
Property Meaning
Atomicity All operations complete or none do
Consistency DB remains valid before and after transactions
Isolation Transactions don't affect each other
Durability Data stays even after crash
7. What is a Foreign Key?
Definition:
A foreign key is a column that creates a relationship between two tables. It points to a primary key in
another table.
Example:
-- Table: students
student_id INT PRIMARY KEY
-- Table: marks
student_id INT,
FOREIGN KEY (student_id) REFERENCES students(student_id)
8. Difference: UNION vs UNION ALL
Feature UNION UNION ALL
Removes duplicates ✅ Yes ❌ No
Performance Slower Faster
-- UNION
SELECT name FROM students
UNION
SELECT name FROM teachers;
-- UNION ALL
SELECT name FROM students
UNION ALL
SELECT name FROM teachers;
✅ Wipro SQL Interview Questions – Detailed with Answers
1. Max Salary Per Department
Question: Get the highest salary for each department.
Answer:
SELECT department, MAX(salary) AS highest_salary
FROM employees
GROUP BY department;
2. DELETE vs TRUNCATE vs DROP
Operation Deletes Data Rollback Possible Deletes Structure
DELETE ✅ Yes ✅ Yes ❌ No
TRUNCATE ✅ Yes (all) ❌ No ❌ No
DROP ✅ Yes ❌ No ✅ Yes
3. Normalization
1NF: Atomic values (no multiple values in a cell)
2NF: No partial dependency on a composite key
3NF: No transitive dependency (non-key depending on non-key)
Example: Bad design:
| student_id | name | course1 | course2 | |------------|----------|---------|---------|
Normalized:
Students (student_id, name)
Courses (student_id, course_name)
4. NULL Check Query
SELECT COUNT(*) FROM employees WHERE salary IS NULL;
Explanation: Counts how many rows don’t have a salary value.
5. RANK() vs DENSE_RANK() vs ROW_NUMBER()
Function Use Case Example Output (for ties)
RANK() Gaps in ranks 1, 2, 2, 4
DENSE_RANK() No gaps 1, 2, 2, 3
ROW_NUMBER() No duplicate values 1, 2, 3, 4
SELECT name, salary,
RANK() OVER (ORDER BY salary DESC),
DENSE_RANK() OVER (ORDER BY salary DESC),
ROW_NUMBER() OVER (ORDER BY salary DESC)
FROM employees;
✅ Capgemini SQL Interview Questions – Detailed with Answers
1. Find Duplicate Records
SELECT name, COUNT(*)
FROM students
GROUP BY name
HAVING COUNT(*) > 1;
2. What Is a View?
A view is a virtual table built from a SELECT query.
CREATE VIEW high_salaries AS
SELECT name, salary FROM employees WHERE salary > 50000;
To use:
SELECT * FROM high_salaries;
3. What Are Constraints?
Types:
NOT NULL
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK
DEFAULT
Example:
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
salary INT CHECK (salary > 0)
);
4. What Is an Index?
Improves query speed for SELECT operations.
CREATE INDEX idx_name ON employees(name);
Too many indexes may slow down INSERT/UPDATE operations.
5. Write a Query to Get Last 5 Records
MySQL:
SELECT * FROM employees ORDER BY emp_id DESC LIMIT 5;
6. What Is a Subquery?
A query inside another query.
SELECT name
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
7. Real-World Question (Capgemini 2023):
> Table Sales: salesperson_id, sales_amount
Find the top 2 salespersons by amount
SELECT salesperson_id, sales_amount
FROM (
SELECT salesperson_id, sales_amount,
DENSE_RANK() OVER (ORDER BY sales_amount DESC) as rank
FROM Sales
) AS ranked
WHERE rank <= 2;
🎯 30-Question SQL Mock Test for Placement Interviews
🧠 Section 1: MCQs (1–10)
1. Which SQL command is used to remove a table and all its data?
a) DELETE b) TRUNCATE c) DROP d) REMOVE
✅ Answer: c) DROP
2. What does SELECT COUNT(*) return?
a) Number of columns b) Number of NULL values c) Total number of rows
✅ Answer: c) Total number of rows
3. Which keyword is used to prevent duplicate values?
a) UNIQUE b) DISTINCT
✅ Answer: b) DISTINCT
4. Which type of JOIN returns unmatched rows from the left table?
a) INNER JOIN b) FULL JOIN c) LEFT JOIN
✅ Answer: c) LEFT JOIN
5. What does NULL mean in SQL?
a) 0 b) Empty string c) Unknown or missing value
✅ Answer: c) Unknown or missing value
6. Which function returns the highest value?
a) MAX() b) HIGH() c) TOP()
✅ Answer: a) MAX()
7. What is the default sorting order in ORDER BY?
a) ASC b) DESC
✅ Answer: a) ASC
8. Which clause is used to filter grouped records?
a) WHERE b) HAVING
✅ Answer: b) HAVING
9. Which constraint ensures uniqueness and NOT NULL?
a) PRIMARY KEY b) UNIQUE
✅ Answer: a) PRIMARY KEY
10. Which of these is NOT a valid SQL command?
a) SAVE b) COMMIT
✅ Answer: a) SAVE
🧩 Section 2: Query Writing (11–20)
11. Write a query to display all employees with salary > 50000.
SELECT * FROM employees WHERE salary > 50000;
12. Write a query to find the average salary of each department.
SELECT department, AVG(salary) FROM employees GROUP BY department;
13. Display names of employees who do not have a manager (manager_id is NULL).
SELECT name FROM employees WHERE manager_id IS NULL;
14. Find total number of employees in each department having more than 5 people.
SELECT department, COUNT(*) as total
FROM employees
GROUP BY department
HAVING COUNT(*) > 5;
15. Write a query to find duplicate names in a students table.
SELECT name, COUNT(*)
FROM students
GROUP BY name
HAVING COUNT(*) > 1;
16. Display the top 3 highest paid employees.
SELECT * FROM employees ORDER BY salary DESC LIMIT 3;
17. Write a query to update salary by 10% for all employees in the ‘Sales’ department.
UPDATE employees
SET salary = salary * 1.10
WHERE department = 'Sales';
18. Write a query to delete all records from products table where stock is 0.
DELETE FROM products WHERE stock = 0;
19. Create a table for storing student results.
CREATE TABLE results (
id INT PRIMARY KEY,
name VARCHAR(50),
marks INT
);
20. Write a query to get department-wise maximum salary.
SELECT department, MAX(salary) FROM employees GROUP BY department;
🧠 Section 3: Logic & Scenario-Based (21–30)
21. Get second highest salary using subquery.
SELECT MAX(salary)
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
22. Find employees who joined in the last 6 months.
SELECT * FROM employees
WHERE joining_date >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH);
23. Get number of employees in each role in each department.
SELECT department, role, COUNT(*) FROM employees
GROUP BY department, role;
24. Write a query to show total salary only for departments with average salary > 60000.
SELECT department, SUM(salary)
FROM employees
GROUP BY department
HAVING AVG(salary) > 60000;
25. Display students and their grades:
SELECT name,
CASE
WHEN marks >= 90 THEN 'A'
WHEN marks >= 75 THEN 'B'
WHEN marks >= 60 THEN 'C'
ELSE 'F'
END AS grade
FROM students;
26. Find students who got same marks in multiple subjects.
SELECT student_id, marks, COUNT(*)
FROM marks
GROUP BY student_id, marks
HAVING COUNT(*) > 1;
27. Transpose subject rows to columns for student marks.
SELECT student_id,
MAX(CASE WHEN subject = 'Math' THEN marks END) AS Math,
MAX(CASE WHEN subject = 'Science' THEN marks END) AS Science
FROM marks
GROUP BY student_id;
28. List employee names and their rank by salary.
SELECT name, salary,
RANK() OVER (ORDER BY salary DESC) AS rank
FROM employees;
29. What will happen if you delete a row that has a foreign key reference in another table?
❌ Error unless ON DELETE CASCADE is used.
30. How to safely make sure a transaction is complete or rolled back?
BEGIN;
-- do operations
COMMIT; -- or ROLLBACK if error