Introduction
SQL is one of the most important skills for developers, especially those working with databases and backend technologies. During SQL interviews, employers often assess your understanding of database concepts, query writing, and optimization techniques.
In this article, we'll explore 10 commonly asked SQL interview questions with clear explanations and practical examples.
1. What Is the Difference Between DELETE, TRUNCATE, and DROP?
DELETE
Removes specific rows.
Supports the
WHEREclause.Can be rolled back within a transaction (database-dependent).
DELETE FROM Employees
WHERE EmployeeId = 5;
TRUNCATE
Removes all rows from a table.
Faster than
DELETEfor removing all records.Does not support a
WHEREclause.
TRUNCATE TABLE Employees;
DROP
Deletes the entire table, including its structure and data.
DROP TABLE Employees;
Interview Tip: DROP removes both the table definition and its data, while DELETE and TRUNCATE preserve the table structure.
2. What Is the Difference Between WHERE and HAVING?
WHERE
Filters individual rows before grouping.
SELECT *
FROM Employees
WHERE Salary > 50000;
HAVING
Filters grouped results after the GROUP BY operation.
SELECT Department, COUNT(*)
FROM Employees
GROUP BY Department
HAVING COUNT(*) > 5;
3. What Is the Difference Between INNER JOIN and LEFT JOIN?
INNER JOIN
Returns only matching records from both tables.
SELECT *
FROM Orders O
INNER JOIN Customers C
ON O.CustomerId = C.CustomerId;
LEFT JOIN
Returns all rows from the left table and matching rows from the right table. If no match exists, the right-side columns contain NULL.
SELECT *
FROM Orders O
LEFT JOIN Customers C
ON O.CustomerId = C.CustomerId;
4. What Is the Difference Between UNION and UNION ALL?
UNION
Combines results from multiple queries.
Removes duplicate rows.
SELECT Name FROM Customers
UNION
SELECT Name FROM Suppliers;
UNION ALL
Combines results from multiple queries.
Keeps duplicate rows.
Generally performs faster than
UNION.
SELECT Name FROM Customers
UNION ALL
SELECT Name FROM Suppliers;
Performance Tip: Use UNION ALL when duplicate removal is unnecessary.
5. What Are Primary Key and Foreign Key?
Primary Key
Uniquely identifies each row in a table.
Cannot contain
NULLvalues.Ensures entity integrity.
Foreign Key
Creates a relationship between two tables.
Enforces referential integrity.
CREATE TABLE Orders
(
OrderId INT PRIMARY KEY,
CustomerId INT FOREIGN KEY REFERENCES Customers(CustomerId)
);
6. What Is the Difference Between CHAR and VARCHAR?
CHAR
Fixed-length data type.
Pads unused characters with spaces.
Name CHAR(20)
VARCHAR
Variable-length data type.
Stores only the actual characters entered.
Name VARCHAR(20)
Best Practice: Use VARCHAR unless a fixed-length field is specifically required.
7. What Is an Index?
An index improves query performance by allowing the database engine to locate rows more efficiently.
CREATE INDEX IX_Employee_Name
ON Employees(Name);
Join the conversation! Your thoughts help the community grow.