Top 50 SQL Interview Questions and Answers: Beginner to Advanced Guide with Real Examples

Sql Interview Question and Answer




Are you preparing for a SQL interview? Whether you're a beginner or brushing up your database knowledge, these 50 SQL questions with detailed answers and real-life examples will help you confidently crack any interview.

 
Question 1: What is SQL?

SQL (Structured Query Language) is a standard programming language used to manage and manipulate relational databases. It allows users to interact with databases, including inserting, updating, deleting, and retrieving data.

Question 2: What are the different types of SQL commands?

SQL commands are classified into the following types:

  • DDL (Data Definition Language): Defines the structure of the database. Examples: CREATE, ALTER, DROP.
  • DML (Data Manipulation Language): Manipulates data in the database. Examples: SELECT, INSERT, UPDATE, DELETE.
  • DCL (Data Control Language): Defines access control. Examples: GRANT, REVOKE.
  • TCL (Transaction Control Language): Manages transaction controls. Examples: COMMIT, ROLLBACK.
Question 3: What is a primary key?

A primary key is a column or a set of columns that uniquely identifies each row in a table. It cannot have NULL values and ensures that no two rows have the same value for that column.

CREATE TABLE Employees (
    EmployeeID INT PRIMARY KEY,
    Name VARCHAR(100)
);
        
Question 4: What is a foreign key?

A foreign key is a column or a set of columns in one table that links to the primary key of another table. It enforces referential integrity between the two tables.

CREATE TABLE Orders (
    OrderID INT PRIMARY KEY,
    CustomerID INT,
    FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);
        
Question 5: What is the difference between WHERE and HAVING clause?

The WHERE clause filters rows before grouping, while the HAVING clause filters rows after grouping.

SELECT Department, COUNT(*) AS TotalEmployees
FROM Employees
GROUP BY Department
HAVING COUNT(*) > 10;
        
Question 6: What is the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL JOIN?

These joins are used to combine rows from two or more tables based on a related column. The difference is in how unmatched rows are treated:

  • INNER JOIN: Returns only matching rows.
  • LEFT JOIN: Returns all rows from the left table and matching rows from the right table.
  • RIGHT JOIN: Returns all rows from the right table and matching rows from the left table.
  • FULL JOIN: Returns all rows when there is a match in either table.
Question 7: What is normalization? Explain its types.

Normalization is the process of organizing a database to reduce redundancy and dependency. There are several normal forms:

  • 1st Normal Form (1NF): Ensures that each column contains atomic values, and there are no repeating groups.
  • 2nd Normal Form (2NF): Achieves 1NF and removes partial dependency (no non-prime attribute depends on a part of a candidate key).
  • 3rd Normal Form (3NF): Achieves 2NF and removes transitive dependency (non-prime attributes depend only on candidate keys).
  • Boyce-Codd Normal Form (BCNF): Strengthens 3NF by removing any dependencies between attributes that are not candidate keys.
Question 8: What is denormalization?

Denormalization is the process of intentionally introducing redundancy into a database to improve read performance. It involves merging tables or adding redundant data to reduce the complexity of certain queries.

Question 9: What are indexes? Why are they used?

Indexes are used to speed up the retrieval of rows from a table by providing a quick lookup of data based on one or more columns. They improve query performance but may slow down INSERT, UPDATE, and DELETE operations.

CREATE INDEX idx_EmployeeName
ON Employees (Name);
        
Question 10: What is a view in SQL?

A view is a virtual table that contains the result of a query. It does not store data but provides a way to simplify complex queries, manage data security, and present data in a specific format.

CREATE VIEW EmployeeView AS
SELECT Name, Department FROM Employees WHERE Salary > 50000;
        
Question 11: What is a subquery?

A subquery is a query inside another query. It can be used to return values to be used in the main query. Subqueries can be placed in SELECT, WHERE, or FROM clauses.

SELECT Name, Salary
FROM Employees
WHERE DepartmentID = (
    SELECT DepartmentID
    FROM Departments
    WHERE DepartmentName = 'IT'
);
        
Question 12: What are aggregate functions in SQL?

Aggregate functions perform calculations on multiple rows of data to return a single value. Common aggregate functions include:

  • COUNT(): Counts the number of rows.
  • SUM(): Adds up numeric values.
  • AVG(): Calculates the average of numeric values.
  • MIN() and MAX(): Return the minimum and maximum values.
Question 13: What is a stored procedure?

A stored procedure is a precompiled collection of SQL statements that can be executed as a single unit. They help in reducing redundancy and improving performance.

CREATE PROCEDURE GetEmployeeDetails
AS
SELECT Name, Department FROM Employees;
GO
EXEC GetEmployeeDetails;
        
Question 14: What is the difference between a function and a stored procedure?

The main differences are:

  • Function: Returns a value and can be used in SELECT statements.
  • Stored Procedure: May not return a value and is executed using the EXEC keyword.
Question 15: What is a trigger in SQL?

A trigger is a special type of stored procedure that automatically executes when a specific event occurs on a table (INSERT, UPDATE, DELETE).

CREATE TRIGGER EmployeeSalaryChange
AFTER UPDATE ON Employees
FOR EACH ROW
BEGIN
    IF OLD.Salary != NEW.Salary THEN
        INSERT INTO SalaryHistory (EmployeeID, OldSalary, NewSalary)
        VALUES (NEW.EmployeeID, OLD.Salary, NEW.Salary);
    END IF;
END;
        
Question 16: What is the difference between DELETE and TRUNCATE?

The difference between DELETE and TRUNCATE is:

  • DELETE: Deletes rows one by one and can be rolled back.
  • TRUNCATE: Removes all rows from a table and cannot be rolled back (no log entries for individual rows).
Question 17: What is an alias in SQL?

An alias is a temporary name for a table or column, used to make queries easier to read. Aliases are often used in SELECT queries.

SELECT Name AS EmployeeName, Department AS Dept
FROM Employees;
        
Question 18: What is the difference between UNION and UNION ALL?

The difference between UNION and UNION ALL is:

  • UNION: Combines results from two queries, eliminating duplicates.
  • UNION ALL: Combines results from two queries, including duplicates.
Question 19: What is the purpose of the GROUP BY clause?

The GROUP BY clause is used to group rows that have the same values into summary rows, like finding the number of employees in each department.

SELECT Department, COUNT(*) AS TotalEmployees
FROM Employees
GROUP BY Department;
        
Question 20: What is the difference between CHAR and VARCHAR?

CHAR is a fixed-length string, while VARCHAR is a variable-length string. CHAR takes up the same amount of space regardless of the length of the string, whereas VARCHAR uses only as much space as needed.

Question 21: What is the difference between IN and EXISTS?

The difference between IN and EXISTS is:

  • IN: Checks if a value is present in a list of values.
  • EXISTS: Checks if a subquery returns any results. It's often used when checking for the existence of rows in a subquery.
Question 22: What is a composite key?

A composite key is a combination of two or more columns in a table that can be used to uniquely identify a row in the table. It is used when no single column can uniquely identify a row.

CREATE TABLE OrderDetails (
    OrderID INT,
    ProductID INT,
    PRIMARY KEY (OrderID, ProductID)
);
        
Question 23: What is the purpose of the DISTINCT keyword?

The DISTINCT keyword is used in a SELECT query to remove duplicate values from the result set and return only unique values.

SELECT DISTINCT Department
FROM Employees;
        
Question 24: What is the difference between a LEFT JOIN and a RIGHT JOIN?

The difference between LEFT JOIN and RIGHT JOIN is:

  • LEFT JOIN: Returns all records from the left table, and the matching records from the right table. If no match, NULL values are returned from the right table.
  • RIGHT JOIN: Returns all records from the right table, and the matching records from the left table. If no match, NULL values are returned from the left table.
Question 25: What is the purpose of the LIKE operator?

The LIKE operator is used to search for a specified pattern in a column. It is often used with wildcard characters such as % (for zero or more characters) and _ (for a single character).

SELECT Name
FROM Employees
WHERE Name LIKE 'A%';
        
Question 26: What is the purpose of the BETWEEN operator?

The BETWEEN operator is used to filter the result set within a specific range of values, including the boundary values.

SELECT Name, Salary
FROM Employees
WHERE Salary BETWEEN 30000 AND 50000;
        
Question 27: What is the purpose of the HAVING clause?

The HAVING clause is used to filter groups based on aggregate functions in a GROUP BY query. It works similarly to the WHERE clause but is used after grouping.

SELECT Department, AVG(Salary) AS AverageSalary
FROM Employees
GROUP BY Department
HAVING AVG(Salary) > 50000;
        
Question 28: What is the difference between a UNION and a JOIN?

The difference between UNION and JOIN is:

  • UNION: Combines the results of two or more SELECT queries into a single result set and removes duplicates.
  • JOIN: Combines rows from two or more tables based on a related column and returns matching rows.
Question 29: What is a self-join?

A self-join is a regular join, but the table is joined with itself. It is useful when you have hierarchical data or need to compare rows in the same table.

SELECT A.Name AS Employee, B.Name AS Manager
FROM Employees A, Employees B
WHERE A.ManagerID = B.EmployeeID;
        
Question 30: What is a materialized view?

A materialized view is a precomputed result of a query stored as a physical object. It improves performance by storing the result, allowing quick access without recalculating the data each time.

Question 31: What is the purpose of the COALESCE function in SQL?

The COALESCE function returns the first non-NULL value in a list of arguments. It's useful for handling NULL values in your queries.

SELECT COALESCE(NULL, NULL, 'Hello', 'World');
-- Returns 'Hello'
        
Question 32: What is an index in SQL, and why is it important?

An index is a database object that improves the speed of data retrieval operations on a table. Indexes are particularly useful for large tables, helping to speed up SELECT queries.

CREATE INDEX idx_name ON Employees (Name);
        
Question 33: What are the different types of JOINs in SQL?

There are four main types of joins in SQL:

  • INNER JOIN: Returns only the rows with matching values in both tables.
  • LEFT JOIN: Returns all rows from the left table and matching rows from the right table.
  • RIGHT JOIN: Returns all rows from the right table and matching rows from the left table.
  • FULL OUTER JOIN: Returns all rows when there is a match in either left or right table.
Question 34: What is the difference between TRUNCATE and DELETE?

The difference between TRUNCATE and DELETE is:

  • TRUNCATE: Removes all rows from a table and cannot be rolled back. It does not log individual row deletions.
  • DELETE: Removes rows one by one and can be rolled back. It is slower compared to TRUNCATE.
Question 35: What is a foreign key constraint?

A foreign key is a column or a set of columns in one table that references the primary key of another table. It ensures referential integrity by only allowing valid references between tables.

CREATE TABLE Orders (
    OrderID INT PRIMARY KEY,
    CustomerID INT,
    FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);
        
Question 36: What is the purpose of the RANK function in SQL?

The RANK function assigns a unique rank to each row within a partition of a result set, with ties receiving the same rank and leaving gaps between ranks.

SELECT Name, Salary, RANK() OVER (ORDER BY Salary DESC) AS Rank
FROM Employees;
        
Question 37: What is the purpose of the CASE statement in SQL?

The CASE statement allows you to perform conditional logic in SQL queries. It can be used to return different values based on conditions.

SELECT Name, 
    CASE 
        WHEN Salary > 50000 THEN 'High'
        ELSE 'Low'
    END AS SalaryCategory
FROM Employees;
        
Question 38: What is the difference between the UNION and INTERSECT operators?

The difference between UNION and INTERSECT is:

  • UNION: Combines the results of two queries and removes duplicates.
  • INTERSECT: Returns only the rows that appear in both queries, eliminating duplicates.
Question 39: What is the purpose of the ROW_NUMBER function in SQL?

The ROW_NUMBER function assigns a unique number to each row within a result set based on a specified order.

SELECT Name, Salary, ROW_NUMBER() OVER (ORDER BY Salary DESC) AS RowNum
FROM Employees;
        
Question 40: What is the difference between VARCHAR and TEXT data types?

The difference between VARCHAR and TEXT is:

  • VARCHAR: Stores variable-length strings and allows you to specify a maximum length.
  • TEXT: Used for storing large amounts of text. It has no length limit, unlike VARCHAR.
Question 41: What is a trigger in SQL?

A trigger is a special type of stored procedure that is automatically executed when an event such as INSERT, UPDATE, or DELETE occurs on a table.

CREATE TRIGGER EmployeeAfterInsert
AFTER INSERT ON Employees
FOR EACH ROW
BEGIN
    INSERT INTO AuditLog (Action, EmployeeID)
    VALUES ('Inserted', NEW.EmployeeID);
END;
        
Question 42: What is a stored procedure?

A stored procedure is a precompiled collection of one or more SQL statements stored in the database, which can be executed to perform a specific task.

CREATE PROCEDURE GetEmployeeDetails
    @EmployeeID INT
AS
BEGIN
    SELECT Name, Department
    FROM Employees
    WHERE EmployeeID = @EmployeeID;
END;
        
Question 43: What is the difference between a stored procedure and a function?

The difference between a stored procedure and a function is:

  • Stored Procedure: It performs an action (e.g., modifying data) and doesn't return a value, although it can return output parameters.
  • Function: It performs a calculation and returns a value.
Question 44: What is a subquery in SQL?

A subquery is a query nested inside another query. It can be used in the SELECT, WHERE, or FROM clauses and is typically used to retrieve values to be used by the outer query.

SELECT Name, Salary
FROM Employees
WHERE DepartmentID = (SELECT DepartmentID FROM Departments WHERE DepartmentName = 'HR');
        
Question 45: What is a window function in SQL?

A window function performs a calculation across a set of table rows that are related to the current row. It is often used to perform operations like ranking and moving averages.

SELECT Name, Salary, RANK() OVER (ORDER BY Salary DESC) AS Rank
FROM Employees;
        
Question 46: What is the difference between a UNION and a UNION ALL operator?

The difference between UNION and UNION ALL is:

  • UNION: Combines the results of two queries and removes duplicate rows.
  • UNION ALL: Combines the results of two queries and does not remove duplicates.
Question 47: What are the different types of indexes in SQL?

The different types of indexes in SQL include:

  • Unique Index: Ensures that all values in a column are unique.
  • Composite Index: An index that includes more than one column.
  • Full-text Index: Used for full-text searches.
Question 48: What is the purpose of the GROUP BY clause in SQL?

The GROUP BY clause is used to group rows that have the same values in specified columns. It is commonly used with aggregate functions like COUNT, SUM, AVG, etc., to perform calculations on each group.

SELECT Department, COUNT(*) AS EmployeeCount
FROM Employees
GROUP BY Department;
        
Question 49: What is the difference between CHAR and VARCHAR data types?

The difference between CHAR and VARCHAR is:

  • CHAR: A fixed-length string. If the string is shorter than the defined length, it is padded with spaces.
  • VARCHAR: A variable-length string. It only uses as much storage as needed, up to the maximum length.
Question 50: What is the purpose of the ISNULL function in SQL?

The ISNULL function is used to replace NULL values with a specified value. It helps handle NULL values in queries and allows for better data consistency.

SELECT Name, ISNULL(Salary, 0) AS Salary
FROM Employees;
        

Post a Comment

0 Comments