Structured Query Language (SQL) is the backbone of database management and one of the most in-demand skills for data analysts, backend developers, and database administrators. Whether you're a fresher preparing for your first job or an experienced professional brushing up for a technical interview, mastering SQL is crucial to your success.
In this article, we've compiled 50 of the most commonly asked SQL interview questions and answers, ranging from basic queries to advanced concepts like window functions, joins, subqueries, and performance tuning. These questions not only test your theoretical knowledge but also reflect real-world scenarios you'll encounter on the job.
1. What is SQL?
2. What is the difference between SQL and MySQL?
3. What are the different types of SQL commands?
- SELECT: Retrieve data from one or more tables.
- INSERT: Add new records to a table.
- UPDATE: Modify existing records in a table.
- DELETE: Remove records from a table.
- CREATE: Create new tables, views, or databases.
- ALTER: Modify existing database objects (e.g., adding or dropping columns).
- DROP: Delete tables, views, or databases.
- TRUNCATE: Delete all records from a table.
- GRANT: Provide specific privileges to users.
- REVOKE: Remove specific privileges from users.
- COMMIT: Save all changes made during the current transaction.
- ROLLBACK: Undo changes made during the current transaction.
- SAVEPOINT: Set a point within a transaction to which you can later roll back.
4. Difference between the DELETE and TRUNCATE commands.
| DELETE | TRUNCATE |
|---|---|
| DELETE is a DML (Data Manipulation Language) command. | TRUNCATE is a DDL (Data Definition Language) command. |
| It removes rows one at a time and logs each deletion. | It removes all rows from a table without logging individual row deletions. |
| You can use a WHERE clause with DELETE to remove specific rows. | You cannot use a WHERE clause with TRUNCATE. |
| Triggers do fire on DELETE. | Triggers do not fire on TRUNCATE. |
| Slower compared to TRUNCATE due to row-level logging. | It's faster and uses fewer system resources. |
| It can be rolled back if used within a transaction. | It can’t be rolled back in some databases if not inside a transaction. |
5. What is a primary key? How is it different from a foreign key?
- It must be unique and cannot contain NULL values.
- A table can have only one primary key.
- It ensures entity integrity.
CREATE TABLE Students ( StudentID INT PRIMARY KEY, Name VARCHAR(100) );
- It is used to establish and enforce a relationship between two tables.
- It can contain duplicates and NULLs, depending on the relationship.
- It ensures referential integrity.
CREATE TABLE Enrollments ( EnrollmentID INT PRIMARY KEY, StudentID INT, FOREIGN KEY (StudentID) REFERENCES Students(StudentID) );
6. What is a Unique Key in SQL?
- It prevents duplicate values.
- Unlike a Primary Key, a Unique Key can allow a single NULL (depending on the database system).
- A table can have multiple unique keys, but only one primary key.
CREATE TABLE Employees ( EmployeeID INT PRIMARY KEY, Email VARCHAR(100) UNIQUE );
7. What is a Composite Key?
- No single column in the composite key is sufficient to uniquely identify a row on its own.
- The combination of values in all columns must be unique.
CREATE TABLE CourseRegistrations ( StudentID INT, CourseID INT, RegistrationDate DATE, PRIMARY KEY (StudentID, CourseID) );
8. Explain the concept of normalization and denormalization.
- Reduce redundancy
- Improve data integrity
- Minimize data anomalies
-- Employee Table EmployeeID | Name | DepartmentID -- Department Table DepartmentID | DepartmentName
- Reducing the number of joins
- Storing redundant data
EmployeeID | Name | DepartmentName
- Normalization is for efficiency and consistency.
- Denormalization is for performance and simplicity when reading data.
9. How to Improve Data Integrity?
- Storing each fact only once (in the right table)
- Avoiding duplicate or conflicting data
Employee Table: ID | Name | Department 1 | Alice | HR 2 | Bob | HR 3 | Carol | H.R.
10. What are the different normal forms?
1. First Normal Form (1NF)
- All columns contain atomic (indivisible) values.
- Each column contains values of the same type.
- There are no repeating groups or arrays.
StudentID | Name | Subjects
1 | Alice | Math, Science
StudentID | Name | Subject 1 | Alice | Math 1 | Alice | Science
2. Second Normal Form (2NF)
- It is already in 1NF
- And every non-key column is fully functionally dependent on the entire primary key (i.e., no partial dependency)
(StudentID, CourseID) → InstructorName InstructorName depends only on CourseID, not the full key.
3. Third Normal Form (3NF)
- It is in 2NF
- And no transitive dependency exists (i.e., non-key columns don’t depend on other non-key columns)
EmployeeID | Name | DepartmentID | DepartmentName
Boyce-Codd Normal Form (BCNF)
- A table is in BCNF if every determinant is a candidate key.
- Fixes certain rare anomalies not handled by 3NF.
4NF – Fourth Normal Form:
- Removes multi-valued dependencies.
- A table should not have two independent multi-valued facts about an entity.
5NF – Fifth Normal Form:
- Deals with join dependencies.
- Ensures that a table cannot be broken into smaller tables without losing data.
| Normal Form | Goal | Key Rule |
|---|---|---|
| 1NF | Eliminate repeating groups | Atomic values only |
| 2NF | Eliminate partial dependencies | Full key dependency |
| 3NF | Eliminate transitive dependencies | Non-key depends only on key |
| BCNF | Stronger version of 3NF | Every determinant is a candidate key |
| 4NF | Eliminate multi-valued dependencies | One fact per table |
| 5NF | Eliminate join dependencies | Lossless join decomposition |
11. What are SQL Constraints, and why are they important?
| Constraint | Description |
|---|---|
| PRIMARY KEY | Uniquely identifies each row; cannot be NULL or duplicate. |
| FOREIGN KEY | Ensures a value matches one in another table; maintains referential integrity. |
| UNIQUE | Ensures all values in a column are unique (except NULLs). |
| NOT NULL | Prevents NULL values from being stored in a column. |
| CHECK | Validates data based on a logical expression. |
| DEFAULT | Sets a default value for a column if no value is provided. |
CREATE TABLE Employees ( ID INT PRIMARY KEY, Name VARCHAR(100) NOT NULL, Email VARCHAR(100) UNIQUE, Age INT CHECK (Age >= 18), JoinDate DATE DEFAULT GETDATE() );
- Enforce business rules at the database level
- Prevent invalid data entry
- Maintain relationships between tables
- Improve data reliability and quality
12. What is a join? Explain different types of joins.
- Returns only matching rows from both tables.
- Non-matching rows are excluded.
SELECT A.Name, B.DepartmentName FROM Employees A INNER JOIN Departments B ON A.DepartmentID = B.DepartmentID;
- Returns all rows from the left table and matched rows from the right.
- If no match, NULLs are returned for rthe ight table columns.
SELECT A.Name, B.DepartmentName FROM Employees A LEFT JOIN Departments B ON A.DepartmentID = B.DepartmentID;
- Returns all rows from the right table and matched rows from the left.
- If no match, NULLs are returned for left table columns.
SELECT A.Name, B.DepartmentName FROM Employees A RIGHT JOIN Departments B ON A.DepartmentID = B.DepartmentID;
- Returns all rows when there is a match in either the left or right table.
- Non-matching rows are filled with NULLs.
SELECT A.Name, B.DepartmentName FROM Employees A FULL OUTER JOIN Departments B ON A.DepartmentID = B.DepartmentID;
- Returns the Cartesian product of both tables.
- Each row in the first table joins with every row in the second table.
SELECT A.Name, B.DepartmentName FROM Employees A CROSS JOIN Departments B;
- A table is joined with itself to compare rows within the same table.
SELECT A.EmployeeID, A.Name, B.Name AS ManagerName FROM Employees A JOIN Employees B ON A.ManagerID = B.EmployeeID;
| Join Type | Returns |
|---|---|
| INNER JOIN | Only matching rows from both tables |
| LEFT JOIN | All rows from the left table + matched rows from the right |
| RIGHT JOIN | All rows from the right table + matched rows from the left |
| FULL JOIN | All rows from both tables, matched or not |
| CROSS JOIN | All possible combinations (Cartesian product) |
| SELF JOIN | Matches rows within the same table |
13. What is a subquery? Provide an example.
- WHERE clause
- FROM clause
- SELECT clause
SELECT Name, Salary FROM Employees WHERE Salary > ( SELECT AVG(Salary) FROM Employees );
- The inner query (SELECT AVG(Salary)) calculates the average salary.
- The outer query returns employees whose salary is greater than that value.
SELECT Name FROM Employees WHERE Salary > (SELECT AVG(Salary) FROM Employees);
SELECT e1.Name FROM Employees e1 WHERE Salary > ( SELECT AVG(Salary) FROM Employees e2 WHERE e1.Department = e2.Department );
14. What is a View? How is it different from a table?
CREATE VIEW ActiveEmployees AS SELECT Name, Department FROM Employees WHERE Status = 'Active';
SELECT * FROM ActiveEmployees;
| Feature | Table | View |
|---|---|---|
| Storage | Physically stores data | Does not store data (virtual) |
| Created by | CREATE TABLE | CREATE VIEW |
| Data Source | Independent data | Based on query from other tables |
| Performance | Faster (data is stored) | May be slower (computed at runtime) |
| Usage | For storing and managing data | For simplifying complex queries, security, and abstraction |
- To simplify complex joins
- To restrict access to certain columns or rows
- To create reusable query logic
15. Explain the use of indexes in SQL.
- Faster SELECT queries.
- Improve JOIN and WHERE performance.
- Support for ORDER BY and GROUP BY.
- Used automatically by the query optimizer.
- Indexes speed up reads but can slow down writes (INSERT, UPDATE, DELETE) because the index must be updated.
- Use indexes on columns that are frequently searched, joined, or filtered.
- Avoid indexing columns with many duplicate values (like gender or status) — it’s less effective.
In Short, Indexes are used to speed up data retrieval in SQL, especially in search-heavy or join-heavy queries, but they come with a trade-off in write performance and storage.
16. Explain Different Types of Indexes.
- Automatically created on the primary key.
- Physically orders the data in the table based on the indexed column.
- Only one clustered index per table.
CREATE CLUSTERED INDEX idx_emp_id ON Employees(EmployeeID);
- A separate structure that stores pointers to the actual rows.
- Does not change the physical order of data.
- You can have multiple non-clustered indexes on a table.
CREATE NONCLUSTERED INDEX idx_emp_name ON Employees(Name);
- Ensures that the indexed column(s) have unique values.
- Prevents duplicate entries.
- Automatically created on UNIQUE constraints.
CREATE UNIQUE INDEX idx_email ON Employees(Email);
- Index created on two or more columns.
- Useful for queries filtering or sorting on multiple fields.
CREATE INDEX idx_name_dept ON Employees(Name, DepartmentID);
- Used for text searching like CONTAINS, FREETEXT.
- Useful when dealing with large text fields or documents.
CREATE FULLTEXT INDEX ON Articles(Content) KEY INDEX PK_Articles;
- Optimized for geographic or spatial data types (e.g., geometry, geography).
- Used in location-based applications.
CREATE SPATIAL INDEX idx_location ON Locations(GeoData);
17. Difference Between Clustered Index and Non-Clustered Index.
- Physically sorts and stores the actual data rows in the table.
- A table can have only one clustered index.
- The rows are stored in the same order as the clustered index.
- Faster for range-based queries and queries that return large result sets.
- Stores a separate structure from the data.
- Contains pointers (row locators) to the actual data rows.
- A table can have multiple non-clustered indexes.
- Ideal for search/filter operations on frequently queried columns.
- A clustered index defines the physical layout of the table.
- A non-clustered index is a separate lookup structure that speeds up queries without changing data order.
18. What is the purpose of the GROUP BY clause?
- Group data based on one or more columns.
- Always used with aggregate functions.
- Returns one result per group.
- Columns in the SELECT clause must be part of the group or aggregated.
SELECT Department, COUNT(*) AS TotalEmployees FROM Employees GROUP BY Department;
19. Explain the HAVING clause and how it differs from WHERE.
| Feature | WHERE | HAVING |
|---|---|---|
| Used On | Individual rows | Groups of rows |
| When Applied | Before grouping (GROUP BY) | After grouping |
| Aggregates | Cannot use aggregate functions | Can use aggregate functions |
SELECT Department, COUNT(*) AS TotalEmployees FROM Employees GROUP BY Department HAVING COUNT(*) > 5;
SELECT Department, COUNT(*) AS TotalEmployees FROM Employees WHERE Status = 'Active' GROUP BY Department HAVING COUNT(*) > 5;
- WHERE filters rows before grouping (Status = 'Active').
- HAVING filter groups after counting employees.
20. What is an Auto Increment or Identity column in SQL Server?
CREATE TABLE Employees ( EmployeeID INT IDENTITY(1,1) PRIMARY KEY, Name VARCHAR(100) );
21. What is a Stored Procedure in SQL Server, and how is it different from a Function?
CREATE PROCEDURE GetEmployeeByDept @DeptID INT AS BEGIN SELECT * FROM Employees WHERE DepartmentID = @DeptID; END
EXEC GetEmployeeByDept @DeptID = 2;
CREATE FUNCTION GetFullName( @FirstName VARCHAR(50), @LastName VARCHAR(50) ) RETURNS VARCHAR(100) AS BEGIN RETURN @FirstName + ' ' + @LastName; END
SELECT dbo.GetFullName('John', 'Doe');
Difference Between Stored Procedure and Function.
| Feature | Stored Procedure | Function |
|---|---|---|
| Purpose | Perform actions like insert, update, delete, and select | Perform calculations or return computed values |
| Return Type | Can return zero, one, or multiple values using OUT or RETURN | Must return a single scalar value or a table |
| Usage in SQL Statements | Cannot be used directly in SELECT, WHERE, or JOIN | Can be used inside SELECT, WHERE, JOIN, etc. |
| DML Operations | Can perform INSERT, UPDATE, and DELETE | Cannot perform DML operations (read-only) |
| Transaction Control | Can manage transactions using BEGIN TRAN, COMMIT, ROLLBACK | Cannot manage transactions |
| Error Handling | Supports TRY...CATCH for error handling | Limited or no error handling support |
| Output Parameters | Supports input, output, and input-output parameters | Supports only input parameters |
| Usage Scenario | Complex business logic, batch processing, CRUD operations | Reusable calculations, formatting, data transformation |
22. What are triggers in SQL?
- AFTER Trigger: Executes after an INSERT, UPDATE, or DELETE action is completed.
- INSTEAD OF Trigger: Executes in place of the triggering action (commonly used on views).
- DDL Trigger: Fires in response to DDL events like CREATE, ALTER, and DROP.
- LOGON Trigger: Fires when a user logs into SQL Server.
23. How can you handle NULL values in SQL?
Ways to Handle NULL Values in SQL:
SELECT * FROM Employees WHERE ManagerID IS NULL;
SELECT Name, COALESCE(Email, 'No Email') AS ContactEmail FROM Employees;
SELECT ISNULL(PhoneNumber, 'Not Provided') AS Phone FROM Customers;
SELECT NULLIF(Salary, 0) AS ValidSalary FROM Employees;
SELECT Name, CASE WHEN Email IS NULL THEN 'Missing Email' ELSE Email END AS EmailStatus FROM Employees;
- Never use = or <> to compare with NULL; always use IS NULL or IS NOT NULL.
- Use COALESCE for multi-value fallback.
- Use CASE for flexible, readable control.
24. What is a CTE (Common Table Expression)?
WITH CTE_Name AS ( SELECT column1, column2 FROM SomeTable WHERE condition ) SELECT * FROM CTE_Name;
WITH ActiveEmployees AS ( SELECT EmployeeID, Name FROM Employees WHERE Status = 'Active' ) SELECT * FROM ActiveEmployees;
25. Explain the concept of window functions.
SELECT Name, Department, Salary, RANK() OVER (PARTITION BY Department ORDER BY Salary DESC) AS SalaryRank FROM Employees;
- PARTITION BY Department divides the data into groups by department.
- ORDER BY Salary DESC ranks employees from highest to lowest salary within each department.
| Name | Department | Salary | SalaryRank |
|---|---|---|---|
| Alice | HR | 80000 | 1 |
| Bob | HR | 70000 | 2 |
| Carol | IT | 95000 | 1 |
| Dave | IT | 90000 | 2 |
26. What is the difference between UNION and UNION ALL?
- Combines results and removes duplicate rows.
- Performs sorting internally to eliminate duplicates, which may impact performance.
SELECT City FROM Customers UNION SELECT City FROM Suppliers;
- Combines results and includes all rows, including duplicates.
- Faster than UNION because it doesn’t check for duplicates.
SELECT City FROM Customers UNION ALL SELECT City FROM Suppliers;
27. How do you perform error handling in SQL?
BEGIN TRY -- SQL statements that might cause an error END TRY BEGIN CATCH -- Error handling logic END CATCH
BEGIN TRY -- Attempt to divide by zero (will cause error) DECLARE @x INT = 1, @y INT = 0, @result INT; SET @result = @x / @y; END TRY BEGIN CATCH PRINT 'An error occurred:'; PRINT ERROR_MESSAGE(); -- Returns the actual error message END CATCH;
- ERROR_NUMBER() Returns the error number
- ERROR_MESSAGE() Returns the error message text
- ERROR_LINE() Returns the line number where error occurred
- ERROR_SEVERITY() Returns severity of the error
- ERROR_PROCEDURE() Returns the name of the stored proc
- Prevent application crashes due to SQL errors
- Log error details into an audit table
- Handle divide-by-zero, constraint violations, deadlocks, etc.
28. Explain ACID properties.
29. How can you optimize a slow-running query?
30. What are the different types of relationships in databases?
- Example: A User table and a UserProfile table, where each user has exactly one profile.
- Enforced By: Primary Key in both tables with a Foreign Key referencing it.
- Example: A Customer can place many Orders, but each Order is placed by only one Customer.
- Enforced By: A Foreign Key in the "many" side (Orders) referencing the Primary Key in the "one" side (Customer).
- Example: Students can enroll in multiple Courses, and each Course can have many Students. It is implemented via a third table like StudentCourses(StudentID, CourseID).
- Enforced By: Two One-to-Many relationships with a junction table in between.
31. Explain DeadLock in SQL Database.
- Transaction A locks Table1 and wants to update Table2.
- Transaction B locks Table2 and wants to update Table1.
How to Prevent Deadlocks?
- Access resources in the same order in all transactions.
- Keep transactions short and avoid long-running locks.
- Use lower isolation levels when appropriate (e.g., READ COMMITTED).
- Avoid user interaction (like manual approval) inside transactions.
32. Explain the concept of data warehousing.
33. What is the difference between CHAR and VARCHAR2 in SQL?
- CHAR is a fixed-length data type.
- When you define CHAR(n), it always uses exactly n bytes, even if the actual value is shorter.
- If you store a shorter string, Oracle pads the remaining space with spaces.
- VARCHAR2 is a variable-length data type.
- When you define VARCHAR2(n), it uses only as much space as needed, up to n.
- It does not pad with spaces, making it more efficient in most cases.
34. How to create a new table in SQL?
CREATE TABLE Employees ( ID INT PRIMARY KEY, Name VARCHAR(50), Department VARCHAR(50), Salary DECIMAL(10,2), JoinDate DATE );
35. How to insert data into a table?
INSERT INTO Employees (ID, Name, Department, Salary, JoinDate) VALUES (1, 'Alice', 'HR', 60000, '2022-01-15');
INSERT INTO Employees (ID, Name, Department, Salary, JoinDate) VALUES (2, 'Bob', 'IT', 70000, '2022-03-01'), (3, 'Carol', 'Finance', 65000, '2022-02-20');
36. How to create a Foreign Key in a table?
CREATE TABLE Departments ( DeptID INT PRIMARY KEY, DeptName VARCHAR(50) ); ALTER TABLE Employees ADD CONSTRAINT FK_Department FOREIGN KEY (Department) REFERENCES Departments(DeptName);
37. How do you select all columns from a table named employees?
SELECT * FROM employees;
38. How do you select specific columns from the employees table?
SELECT first_name, last_name FROM employees;
39. How can you count the number of records in the employees table?
SELECT COUNT(*) FROM employees;
40. How to retrieve a Unique value from a specific Column?
SELECT DISTINCT department FROM employees;
41. How to update an existing record in the table?
UPDATE employees SET salary = salary * 1.1 WHERE performance_rating = 'Excellent';
42. How to delete an existing row from the table?
DELETE FROM employees WHERE termination_date IS NOT NULL;
43. How to add a new Column in an existing table?
ALTER TABLE employees ADD COLUMN date_of_birth DATE;
44. How to perform pagination in SQL?
SELECT * FROM Employees ORDER BY ID OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY;
- OFFSET 20: Skip the first 20 rows.
- FETCH NEXT 10 ROWS ONLY: Return the next 10 rows.
- This gives you Page 3 (if Page 1 = 0–9, Page 2 = 10–19, Page 3 = 20–29).
SELECT * FROM Employees ORDER BY ID LIMIT 10 OFFSET 20;
- LIMIT 10: Return 10 rows.
- OFFSET 20: Skip the first 20 rows.
45. How do you find the second-highest salary in the employees table?
SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees);
46. How do you find employees with salaries above the average salary?
SELECT * FROM employees WHERE salary > (SELECT AVG(salary) FROM employees);
47. How can you find the highest salary in each department?
SELECT department_id, SUM(salary) FROM employees GROUP BY department_id;
48. How can you find the total number of projects each employee is working on?
SELECT employee_id, COUNT(project_id) FROM project_assignments GROUP BY employee_id;
49. What is SQL injection, and how can it be prevented?
SQL Injection is a security vulnerability that occurs when untrusted input is inserted into an SQL query without proper validation or sanitization, allowing attackers to manipulate the query and potentially access, modify, or delete database data.
1. Use Parameterized Queries / Prepared Statements
- This ensures input values are treated strictly as data, not executable code.
2. Use ORM Frameworks
- Tools like Entity Framework, Hibernate, or Sequelize automatically parameterize queries.
- Always validate and sanitize user input, especially when it’s used in dynamic SQL.
- Do not use admin-level users for database access from applications.
- Even stored procedures can be vulnerable if they concatenate user input. Always use parameters.
50. How would you implement user access control in a database?
- Follow the least privilege principle (give minimal required access).
- Use roles instead of individual permissions for scalability.
- Keep an audit trail of changes and accesses.
- Review access regularly and revoke unused or risky privileges.
- Secure administrative accounts with strong passwords and multi-factor authentication.
Conclusion.

Trends is an amazing magazine Blogger theme that is easy to customize and change to fit your needs.