0% found this document useful (0 votes)
3 views19 pages

SQL Top 100 Interview Questions

The document contains a comprehensive list of the top 100 interview questions related to SQL, covering fundamental concepts such as SQL commands, keys, joins, and data manipulation. It also addresses advanced topics like normalization, views, and transactions, providing definitions and examples for each concept. This resource serves as a guide for individuals preparing for SQL-related job interviews.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views19 pages

SQL Top 100 Interview Questions

The document contains a comprehensive list of the top 100 interview questions related to SQL, covering fundamental concepts such as SQL commands, keys, joins, and data manipulation. It also addresses advanced topics like normalization, views, and transactions, providing definitions and examples for each concept. This resource serves as a guide for individuals preparing for SQL-related job interviews.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Top 100 Interview Questions

1. What is SQL?
SQL (Structured Query Language) is a standard programming language used to
manage and manipulate relational databases. It allows users to query data,
insert new records, update existing ones, and delete unwanted records.

2. What are the types of SQL commands?


SQL commands are categorized into:

DDL (Data Definition Language) – CREATE , DROP , ALTER

DML (Data Manipulation Language) – INSERT , UPDATE , DELETE

DQL (Data Query Language) – SELECT

TCL (Transaction Control Language) – COMMIT , ROLLBACK

DCL (Data Control Language) – GRANT , REVOKE

3. What is a primary key?


A primary key uniquely identifies each record in a table. It must contain unique
values and cannot contain NULL .

Top 100 Interview Questions 1


CREATE TABLE Students (
StudentID INT PRIMARY KEY,
Name VARCHAR(50)
);

4. What is a foreign key?


A foreign key links two tables together. It is a field in one table that refers to the
primary key in another.

FOREIGN KEY (CityID) REFERENCES Cities(CityID)

5. What is the difference between WHERE and HAVING?


WHERE filters rows before grouping.

HAVING filters after grouping with aggregate functions.

6. What is the use of the SELECT statement?


SELECT is used to retrieve data from a database.

SELECT * FROM Employees;

7. What is the difference between DELETE and TRUNCATE?


DELETE removes rows one at a time (can have a WHERE clause).

TRUNCATE removes all rows quickly and cannot be rolled back.

8. What does the DISTINCT keyword do?


It removes duplicate values in the result set.

SELECT DISTINCT Country FROM Customers;

9. What are SQL constraints?

Top 100 Interview Questions 2


Constraints enforce rules on data in tables. Examples: NOT NULL , UNIQUE , PRIMARY

KEY , FOREIGN KEY , CHECK , DEFAULT .

10. What is a JOIN?


A JOIN combines rows from two or more tables based on related columns.

11. What is the difference between INNER JOIN and LEFT JOIN?
INNER JOIN returns only matching rows.

LEFT JOIN returns all rows from the left table and matched rows from the
right.

12. What is the purpose of the ORDER BY clause?


It sorts the result set by one or more columns.

SELECT * FROM Products ORDER BY Price DESC;

13. How do you use the LIMIT clause?


It restricts the number of records returned.

SELECT * FROM Customers LIMIT 5;

14. What are aggregate functions in SQL?


Functions like SUM() , AVG() , MAX() , MIN() , COUNT() that operate on a set of values.

15. What is the use of the GROUP BY clause?


It groups rows sharing a property so aggregate functions can be applied.

SELECT Country, COUNT(*) FROM Customers GROUP BY Country;

16. What is the difference between UNION and UNION ALL?


UNION removes duplicates.

UNION ALL includes duplicates.

Top 100 Interview Questions 3


17. What is a subquery?
A query within another query. Used to filter, compute values, or define virtual
tables.

SELECT Name FROM Employees WHERE DepartmentID = (SELECT ID FRO


M Departments WHERE Name = 'HR');

18. What is a CASE statement?


Used for conditional logic inside queries.

SELECT Name,
CASE
WHEN Marks >= 50 THEN 'Pass'
ELSE 'Fail'
END AS Status
FROM Students;

19. What are NULL values?


NULL represents missing or unknown data. It is different from 0 or empty
string.

20. How to handle NULLs in SQL?


Use IS NULL , IS NOT NULL , or functions like COALESCE() and NVL() .

SELECT COALESCE(Phone, 'Not Provided') FROM Customers;

21. What is normalization in SQL?


Normalization is the process of organizing data to reduce redundancy and
improve data integrity. It breaks large tables into smaller, related ones.

Normal forms include:

1NF – Eliminate repeating groups

Top 100 Interview Questions 4


2NF – Remove partial dependencies

3NF – Remove transitive dependencies

22. What is denormalization?


Denormalization is the process of combining tables to improve read
performance. It may introduce some redundancy.

Used in reporting or analytics to speed up queries.

23. What is a VIEW?


A view is a virtual table based on a query result.

CREATE VIEW TopStudents AS


SELECT Name, Marks FROM Students WHERE Marks > 90;

24. What is the difference between a View and a Table?


A Table stores data physically.

A View is just a saved SQL query (virtual table) and doesn't store data.

25. What is a Common Table Expression (CTE)?


A CTE is a temporary result set used within a WITH clause.

WITH TopEmployees AS (
SELECT * FROM Employees WHERE Salary > 50000
)
SELECT * FROM TopEmployees;

26. What is a recursive CTE?


A recursive CTE calls itself to solve hierarchical problems.
Example: Fetch all employees and their managers.

27. What is a stored procedure?

Top 100 Interview Questions 5


A stored procedure is a saved set of SQL statements that can be executed
repeatedly.

CREATE PROCEDURE GetTopSales()


BEGIN
SELECT * FROM Sales ORDER BY Amount DESC LIMIT 10;
END;

28. What is a function in SQL?


A function returns a single value and is often used in SELECT statements.

Example:

CREATE FUNCTION GetTotal(a INT, b INT) RETURNS INT


RETURN a + b;

29. What are transactions in SQL?


A transaction is a group of SQL operations executed as a single unit.

BEGIN;
UPDATE Accounts SET Balance = Balance - 100 WHERE ID = 1;
UPDATE Accounts SET Balance = Balance + 100 WHERE ID = 2;
COMMIT;

30. What are ACID properties?


ACID ensures reliable transactions:

Atomicity – All or nothing

Consistency – DB remains valid

Isolation – No interference

Durability – Changes persist

31. What is a cursor?


A cursor allows row-by-row processing of query results.

Top 100 Interview Questions 6


Used in procedures when looping through records is required.

32. What is the difference between CHAR and VARCHAR?


CHAR(n) – Fixed length

VARCHAR(n) – Variable length

CHAR(10) will always use 10 bytes, VARCHAR(10) uses only what's needed.

33. What are indexes?


Indexes speed up search operations. Like a book index, they help locate rows
quickly.

CREATE INDEX idx_name ON Employees(Name);

34. What are the types of indexes?


Clustered index – Alters the table’s physical order

Non-clustered index – Creates a separate structure for lookup

35. What is the difference between RANK() and


DENSE_RANK()?
RANK() – Leaves gaps in ranks

DENSE_RANK() – No gaps

Example:

SELECT Name, Salary, RANK() OVER(ORDER BY Salary DESC) FROM Emplo


yees;

36. What is the COALESCE() function?


It returns the first non-null value from the list.

SELECT COALESCE(Address, 'Not Available') FROM Customers;

Top 100 Interview Questions 7


37. What are string functions in SQL?
Functions to manipulate strings:

CONCAT() , UPPER() , LOWER() , SUBSTRING() , LENGTH()

Example:

SELECT UPPER(Name), LENGTH(Name) FROM Students;

38. What is the purpose of EXISTS?


EXISTS checks if a subquery returns any rows.

SELECT Name FROM Customers


WHERE EXISTS (SELECT 1 FROM Orders WHERE Customers.ID = Orders.C
ustomerID);

39. What is the IN operator?


Used to match a value against multiple values.

SELECT * FROM Students WHERE City IN ('Mumbai', 'Delhi');

40. What is the BETWEEN operator?


Filters a range of values.

SELECT * FROM Products WHERE Price BETWEEN 100 AND 500;

41. What is the difference between DELETE and TRUNCATE?


DELETE – Deletes specific rows, can use WHERE clause, logs each row
(slower).

TRUNCATE – Deletes all rows, no WHERE, faster, cannot be rolled back


easily.

Top 100 Interview Questions 8


DELETE FROM Employees WHERE Department = 'HR';
TRUNCATE TABLE Employees;

42. What is the difference between UNION and UNION ALL?


UNION – Combines results and removes duplicates.

UNION ALL – Combines results including duplicates (faster).

SELECT City FROM Customers


UNION
SELECT City FROM Suppliers;

43. What is the CASE statement?


It allows conditional logic in SQL.

SELECT Name,
CASE
WHEN Marks >= 90 THEN 'A'
WHEN Marks >= 75 THEN 'B'
ELSE 'C'
END AS Grade
FROM Students;

44. What is a composite key?


A primary key made up of two or more columns.

PRIMARY KEY (StudentID, CourseID)

45. What is a surrogate key?


An artificial key (like an ID) added to a table, often auto-incremented, not
derived from data.

46. What is the difference between HAVING and WHERE?

Top 100 Interview Questions 9


WHERE – Filters rows before aggregation.

HAVING – Filters after aggregation (works with GROUP BY).

SELECT Department, COUNT(*)


FROM Employees
GROUP BY Department
HAVING COUNT(*) > 5;

47. What is a self join?


Joining a table to itself using aliases.

SELECT A.Name, B.Name


FROM Employees A
JOIN Employees B ON A.ManagerID = B.ID;

48. What are window functions?


Perform calculations across a set of rows related to the current row without
grouping.
Examples: RANK() , ROW_NUMBER() , SUM() OVER()

49. Difference between GROUP BY and PARTITION BY?


GROUP BY – Aggregates data into groups, returns one row per group.

PARTITION BY – Used with window functions, does not reduce row count.

50. What is the use of ROW_NUMBER()?


Assigns a unique row number to each row in a result set.

SELECT Name, ROW_NUMBER() OVER(ORDER BY Marks DESC) AS Rank


FROM Students;

51. What is a NULL value in SQL?


Represents unknown or missing data. It is not the same as 0 or empty string.

Top 100 Interview Questions 10


52. How are NULLs handled in SQL comparisons?
Use IS NULL or IS NOT NULL , not = NULL .

SELECT * FROM Employees WHERE Address IS NULL;

53. What is NVL or COALESCE?


Both return the first non-null value.

SELECT NVL(Salary, 0) FROM Employees;


SELECT COALESCE(Salary, Bonus, 0) FROM Employees;

54. What is a constraint?


Rules enforced on data columns: NOT NULL , UNIQUE , PRIMARY KEY , FOREIGN KEY ,
CHECK , DEFAULT

55. What is the CHECK constraint?


Limits values in a column.

CHECK (Age >= 18)

56. What is the DEFAULT constraint?


Sets a default value if none is provided.

Age INT DEFAULT 18

57. What is a foreign key?


Establishes a relationship between two tables. It references a primary key in
another table.

FOREIGN KEY (CityID) REFERENCES Cities(ID)

58. Difference between primary key and unique key?

Top 100 Interview Questions 11


Primary key – Uniqueness + NOT NULL (only one per table)

Unique key – Only uniqueness (can have multiple)

59. What is the purpose of the EXISTS clause?


Used to test if a subquery returns results. Good for checking relationships.

60. What is scalar subquery?


A subquery that returns a single value.

SELECT Name,
(SELECT MAX(Marks) FROM Students) AS MaxMarks
FROM Students;

61. What is the purpose of the COALESCE() function?


COALESCE() returns the first non-null value from a list of expressions.
Example:

SELECT COALESCE(NULL, NULL, 'Default', 'Another') AS Result; -- Output:


'Default'

62. What is the difference between COALESCE() and ISNULL()?


COALESCE() supports multiple arguments and is ANSI standard.

is specific to some databases (like SQL Server) and accepts only


ISNULL()

two arguments.

63. What are the different ways to handle NULL values in SQL?
Use IS NULL / IS NOT NULL in conditions.

Use COALESCE() or IFNULL() for replacement.

Use CASE to create logic around NULLs.

64. What is the difference between WHERE and ON in JOINs?

Top 100 Interview Questions 12


ON is used to define the condition for the JOIN between two tables.

WHERE is used to filter the result after the JOIN has been performed.

65. How to find the second highest salary in a table?

SELECT MAX(Salary)
FROM Employees
WHERE Salary < (SELECT MAX(Salary) FROM Employees);

66. What is a CROSS JOIN?


A CROSS JOIN returns the Cartesian product of two tables — every row of the
first table is paired with every row of the second.

67. What is a SELF JOIN?


A SELF JOIN is a regular join where a table is joined with itself.
Example:

SELECT A.Name, B.Name AS Manager


FROM Employees A
JOIN Employees B ON A.ManagerID = B.EmployeeID;

68. What is an Index?


An index is a performance-tuning method that allows faster retrieval of records
from the table.

69. What are the types of Indexes?


Clustered Index

Non-clustered Index

Unique Index

Full-text Index

Spatial Index

Top 100 Interview Questions 13


70. What is the difference between clustered and non-
clustered index?
Clustered Index: Alters the physical order of the table; only one allowed per
table.

Non-Clustered Index: Separate from table data; multiple allowed.

71. What is a View in SQL?


A View is a virtual table based on the result-set of an SQL query. It doesn’t
store data but shows real-time results.

72. How to create a View?

CREATE VIEW HighSalary AS


SELECT Name, Salary FROM Employees WHERE Salary > 100000;

73. What is the difference between a View and a Table?


A table stores data physically.

A view is a saved query; it shows data but doesn't store it.

74. Can we insert or update data through a View?


Yes, but only if the view is based on a single table without any aggregate
functions, GROUP BY, etc.

75. What is a Temporary Table?


A temporary table is created to store data temporarily during a session.
Syntax:

CREATE TEMPORARY TABLE temp_data (


id INT,
name VARCHAR(100)
);

76. Difference between Local and Global Temporary Tables?

Top 100 Interview Questions 14


Local Temp Table ( #temp ): Exists only for the session.

Global Temp Table ( ##temp ): Accessible to all sessions until the last one
closes.

77. What is the difference between DELETE and TRUNCATE?


DELETE: Removes rows one by one, logs each delete.

TRUNCATE: Removes all rows instantly; cannot use WHERE clause.

78. What is Normalization?


Normalization is the process of organizing data to reduce redundancy and
improve data integrity.

79. What are different Normal Forms?


1NF – Atomic columns

2NF – No partial dependency

3NF – No transitive dependency

BCNF – Advanced 3NF

80. What is Denormalization?


Denormalization is the process of combining tables to improve read
performance at the cost of redundancy.

81. What is a Transaction in SQL?


A transaction is a sequence of SQL operations performed as a single logical
unit of work. It must be:

Atomic

Consistent

Isolated

Durable (ACID)

82. What are ACID properties?

Top 100 Interview Questions 15


Atomicity – All steps succeed or none do.

Consistency – Maintains valid data state.

Isolation – Transactions don’t interfere.

Durability – Once committed, changes remain even after system crash.

83. How do you start and end a transaction?

BEGIN TRANSACTION;
-- SQL statements
COMMIT; -- To save
-- or
ROLLBACK; -- To undo

84. What is the purpose of COMMIT and ROLLBACK?


COMMIT saves changes.

ROLLBACK undoes all changes since the last COMMIT.

85. What is Error Handling in SQL?


Error handling ensures the database remains consistent if errors occur. For
example, in SQL Server, use:

BEGIN TRY
-- SQL code
END TRY
BEGIN CATCH
-- Error handler
END CATCH

86. What is a User-Defined Function (UDF)?


A function created by the user to return a value or table. It can take input and
return a result like a method in programming.

Top 100 Interview Questions 16


CREATE FUNCTION GetDiscount (@price INT)
RETURNS INT
AS
BEGIN
RETURN @price * 0.1;
END

87. What are the types of UDFs?


Scalar Function – Returns a single value.

Table-Valued Function (TVF) – Returns a table.

88. What is a Cursor in SQL?


A cursor allows row-by-row processing of results from a SELECT statement.

89. Steps to use a Cursor?


1. Declare the cursor.

2. Open the cursor.

3. Fetch rows.

4. Close the cursor.

5. Deallocate the cursor.

90. When to use a Cursor?


Use it when row-by-row operations are required — e.g., calculating ranks
manually (though window functions are better now).

91. What are GRANT and REVOKE in SQL?


GRANT gives users access rights.

REVOKE removes access rights.

GRANT SELECT, INSERT ON Employees TO user1;


REVOKE INSERT ON Employees FROM user1;

Top 100 Interview Questions 17


92. What are Roles in SQL?
Roles are a way to group permissions. Instead of assigning privileges to users
one by one, assign them a role.

93. What is Sharding?


Sharding is splitting large databases into smaller, faster, more manageable
parts (shards), often across multiple servers.

94. What is Partitioning in SQL?


Breaking a large table into smaller pieces (partitions) for performance.

Horizontal – Row-wise

Vertical – Column-wise

95. Difference between Sharding and Partitioning?


Sharding distributes across multiple machines.

Partitioning is within the same database/table, internally.

96. What is a Composite Key?


A key formed by combining two or more columns to uniquely identify a record.

97. Can a table have multiple foreign keys?


Yes, a table can have many foreign keys, each referencing different parent
tables.

98. What is a Surrogate Key?


An artificially created key (like an auto-increment ID) used instead of a natural
key.

99. What is a Natural Key?


A key that naturally exists in the data and uniquely identifies records (like email,
SSN, etc.).

Top 100 Interview Questions 18


100. How do you prepare for SQL interviews?
Focus on real-time query writing

Master Joins, Window Functions, Subqueries

Be confident in Normalization, Indexing, Transactions

Practice queries on dummy datasets

Review 100 interview Q&A like these 😄


✅ This completes the 100 SQL Interview Questions series.
Complied by Khaja Noman Ahmed.

Top 100 Interview Questions 19

You might also like