Basic SQL Interview Questions
- What is SQL, and what is it used for?
- What are the different types of SQL commands?
- Discuss DDL, DML, DCL, TCL, and DQL with examples.
- What is the difference between
DELETE
andTRUNCATE
? - Explain the concept of a primary key and a foreign key.
- What are joins? Name and explain different types of joins.
- E.g., INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL OUTER JOIN, CROSS JOIN.
- What is a constraint in SQL?
- Explain common constraints like
NOT NULL
,UNIQUE
,PRIMARY KEY
,FOREIGN KEY
,CHECK
, andDEFAULT
.
- Explain common constraints like
- What are indexes? Why are they used?
- Explain normalization and the normal forms.
- What is a view? Why are views used?
- How do
GROUP BY
andHAVING
clauses work?
Intermediate SQL Interview Questions
- What is the difference between
WHERE
andHAVING
clauses? - Explain the concept of a subquery.
- Differentiate between correlated and non-correlated subqueries.
- How does
UNION
differ fromUNION ALL
? - What are aggregate functions in SQL?
- Discuss functions like
SUM
,COUNT
,AVG
,MAX
, andMIN
.
- Discuss functions like
- What are window functions?
- Discuss functions like
ROW_NUMBER
,RANK
,DENSE_RANK
,NTILE
, and how they work withPARTITION BY
.
- Discuss functions like
- What is a stored procedure? Why are they used?
- Explain transactions and ACID properties.
- What is a self-join, and when would you use it?
- How would you find duplicate records in a table?
- What is a
CROSS APPLY
andOUTER APPLY
?
Advanced SQL Interview Questions
- Explain CTE (Common Table Expressions) and recursive CTE.
- What is a temporary table, and how does it differ from a CTE?
- How do you optimize a slow query?
- Discuss using indexes, analyzing query execution plans, and avoiding unnecessary subqueries.
- What is a materialized view, and how does it differ from a regular view?
- Explain database partitioning and its types.
- What are JSON and XML data types in SQL, and how can you query them?
- How would you handle data migration between two databases?
- Describe the difference between horizontal and vertical scaling in databases.
- What is sharding in SQL databases, and how does it work?
- What are OLTP and OLAP systems? How do they differ?
Scenario-Based SQL Questions
- How would you write a query to find the second-highest salary in an employee table?
- If you have a table with employee data and you want to get each department's highest-paid employee, how would you do it?
- Write a query to retrieve records where a column value is within a specific range.
- How would you find the employees who have not submitted a report for a particular month?
- How would you design a database schema for an e-commerce system?
SQL Query Practice
- Given a table of orders, write a query to count the number of orders placed by each customer.
- Write a query to find customers who made purchases in both January and February.
- How would you retrieve the top 3 highest scores for each student in an exam table?
- Write a query to convert rows to columns (or vice versa) using SQL.
- How would you handle duplicate data entry in a production database?
Answers
Basic SQL Interview Questions
1. What is SQL, and what is it used for?
- Answer: SQL (Structured Query Language) is a programming language used to manage and manipulate relational databases. It allows users to insert, update, delete, and retrieve data stored in a database.
2. What are the different types of SQL commands?
- Answer: SQL commands are categorized as:
- DDL (Data Definition Language): Commands like
CREATE
,ALTER
,DROP
,TRUNCATE
for defining database structures. - DML (Data Manipulation Language): Commands like
INSERT
,UPDATE
,DELETE
to manipulate data. - DCL (Data Control Language): Commands like
GRANT
,REVOKE
to control access. - TCL (Transaction Control Language): Commands like
COMMIT
,ROLLBACK
,SAVEPOINT
to manage transactions. - DQL (Data Query Language): Commands like
SELECT
to query data.
- DDL (Data Definition Language): Commands like
3. What is the difference between DELETE
and TRUNCATE
?
- Answer:
DELETE
removes rows one at a time and can include aWHERE
clause.TRUNCATE
removes all rows in a table instantly and is generally faster but cannot be rolled back in some databases.
4. Explain the concept of a primary key and a foreign key.
- Answer: A primary key uniquely identifies each record in a table, while a foreign key links two tables, referring to the primary key in another table.
5. What are joins? Name and explain different types of joins.
- Answer: Joins combine rows from two or more tables based on a related column. Types:
- INNER JOIN: Only returns rows with matching values in both tables.
- LEFT JOIN: Returns all rows from the left table and matching rows from the right.
- RIGHT JOIN: Returns all rows from the right table and matching rows from the left.
- FULL OUTER JOIN: Returns all rows when there’s a match in either table.
6. What is a constraint in SQL?
- Answer: Constraints enforce rules on columns. Common constraints include:
NOT NULL
- Ensures a column cannot contain null values.UNIQUE
- Ensures all values in a column are unique.PRIMARY KEY
- Uniquely identifies each row in a table.FOREIGN KEY
- Links rows in two tables.CHECK
- Validates values in a column based on a condition.DEFAULT
- Assigns a default value if no value is specified.
7. What are indexes? Why are they used?
- Answer: Indexes are database objects that improve data retrieval speed. They work like pointers to data and are especially useful on frequently queried columns.
8. Explain normalization and the normal forms.
- Answer: Normalization organizes data to reduce redundancy. The normal forms are:
- 1NF: Each cell holds a single value.
- 2NF: 1NF + Every non-key column depends on the whole primary key.
- 3NF: 2NF + No transitive dependencies between columns.
9. What is a view? Why are views used?
- Answer: A view is a virtual table based on a query. It simplifies complex queries, improves security, and enhances maintainability.
10. How do GROUP BY
and HAVING
clauses work?
- Answer:
GROUP BY
groups rows sharing a column value, allowing aggregate functions on groups.HAVING
filters results of groups afterGROUP BY
.
Intermediate SQL Interview Questions
1. What is the difference between WHERE
and HAVING
clauses?
- Answer:
WHERE
filters rows before grouping;HAVING
filters groups after grouping.
2. Explain the concept of a subquery.
- Answer: A subquery is a query within a query. It can be used in conditions like
IN
,EXISTS
, and as a source of data.
3. How does UNION
differ from UNION ALL
?
- Answer:
UNION
removes duplicates, whileUNION ALL
keeps all records, including duplicates.
4. What are aggregate functions in SQL?
- Answer: Aggregate functions perform calculations on sets of rows. Common functions include:
SUM
,COUNT
,AVG
,MAX
,MIN
.
5. What are window functions?
- Answer: Window functions compute values across a set of rows related to the current row. Examples include
ROW_NUMBER
,RANK
,DENSE_RANK
, andNTILE
.
6. What is a stored procedure? Why are they used?
- Answer: A stored procedure is a saved SQL code block that can be reused. It encapsulates logic, reducing repetitive code and enhancing security.
7. Explain transactions and ACID properties.
- Answer: Transactions are units of work ensuring data integrity. ACID properties:
- Atomicity, Consistency, Isolation, Durability.
8. What is a self-join, and when would you use it?
- Answer: A self-join joins a table to itself. Useful for finding hierarchical or related data within the same table.
9. How would you find duplicate records in a table?
- Answer: Use
GROUP BY
withHAVING
to filter duplicates.
10. What is a CROSS APPLY
and OUTER APPLY
?
- Answer: These are used with table-valued functions in SQL Server:
CROSS APPLY
works likeINNER JOIN
, returning rows where the function has results.OUTER APPLY
works likeLEFT JOIN
, returning all rows from the outer table.
Advanced SQL Interview Questions
1. Explain CTE (Common Table Expressions) and recursive CTE.
- Answer: A CTE simplifies complex queries by defining a temporary result set. Recursive CTEs allow queries that reference themselves.
2. What is a temporary table, and how does it differ from a CTE?
- Answer: Temporary tables exist in a session; CTEs are only available within a single query execution.
3. How do you optimize a slow query?
- Answer: Key steps:
- Add indexes.
- Use
EXPLAIN
to understand the query plan. - Avoid unnecessary subqueries and calculations in
WHERE
.
4. What is a materialized view, and how does it differ from a regular view?
- Answer: A materialized view stores query results, updating periodically, unlike a regular view, which recalculates on each query.
5. Explain database partitioning and its types.
- Answer: Partitioning divides tables into parts for faster access. Types include range, list, hash, and composite.
6. What are JSON and XML data types in SQL, and how can you query them?
- Answer: JSON/XML types store semi-structured data, queryable with functions like
JSON_VALUE
.
Scenario-Based SQL Questions
1. Find the second-highest salary:
2. Find highest-paid employee in each department: