Interview Questions

1) What is SQL?


SQL (Structured Query Language) is a standard programming language used to manage and manipulate relational databases. SQL is used for tasks like querying data, inserting records, updating existing records, and deleting records.

2) What is the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL JOIN?


  • INNER JOIN: Returns records that have matching values in both tables.
  • LEFT JOIN: Returns all records from the left table and the matching records from the right table. If no match is found, NULL values are returned for columns from the right table.
  • RIGHT JOIN: Returns all records from the right table and the matching records from the left table. If no match is found, NULL values are returned for columns from the left table.
  • FULL JOIN: Returns records when there is a match in one of the tables. It returns all records from both tables, with NULLs in place where there is no match.

Example:

-- INNER JOIN
SELECT students.name, courses.name 
FROM students
INNER JOIN courses ON students.course_id = courses.id;

-- LEFT JOIN
SELECT students.name, courses.name 
FROM students
LEFT JOIN courses ON students.course_id = courses.id;

-- RIGHT JOIN
SELECT students.name, courses.name 
FROM students
RIGHT JOIN courses ON students.course_id = courses.id;

-- FULL JOIN
SELECT students.name, courses.name 
FROM students
FULL OUTER JOIN courses ON students.course_id = courses.id;

 

3) What are the different types of joins in SQL?


  • INNER JOIN: Only returns rows that have matching values in both tables.
  • LEFT JOIN: Returns all rows from the left table and matched rows from the right table.
  • RIGHT JOIN: Returns all rows from the right table and matched rows from the left table.
  • FULL JOIN: Returns all rows when there is a match in one of the tables.
  • CROSS JOIN: Returns the Cartesian product of both tables. It pairs each row from the first table with each row from the second table.

4) What is normalization in SQL?


Normalization is the process of organizing the data in a database to reduce redundancy and improve data integrity. It involves dividing large tables into smaller, manageable ones while ensuring relationships between the tables are maintained.

  • 1st Normal Form (1NF): Ensures each column contains atomic values, and each record is unique.
  • 2nd Normal Form (2NF): Achieved by meeting 1NF and ensuring all non-key attributes are fully functionally dependent on the primary key.
  • 3rd Normal Form (3NF): Achieved by meeting 2NF and ensuring no transitive dependency (non-key attributes depend only on the primary key).

Example:

1NF:

| StudentID | Name     | Courses      |
|-----------|----------|--------------|
| 1         | John     | Math, Science|
| 2         | Alice    | English, Art |

After normalization into 2NF:

-- Students Table
| StudentID | Name     |
|-----------|----------|
| 1         | John     |
| 2         | Alice    |

-- Courses Table
| StudentID | Course   |
|-----------|----------|
| 1         | Math     |
| 1         | Science  |
| 2         | English  |
| 2         | Art      |

 

5) What is the difference between WHERE and HAVING clause in SQL?


  • WHERE: Filters records before any groupings are made (used with SELECT, UPDATE, DELETE).
  • HAVING: Filters records after groupings are made (used with GROUP BY clause).

Example:

-- Using WHERE
SELECT name, age 
FROM employees 
WHERE age > 30;

-- Using HAVING
SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department
HAVING AVG(salary) > 50000;

 

6) What is a subquery in SQL?


A subquery is a query within another query. It can be used in SELECT, INSERT, UPDATE, or DELETE statements.

Types of subqueries:

  • Single-row subquery: Returns a single value.
  • Multi-row subquery: Returns multiple rows.
  • Correlated subquery: References a column from the outer query.

Example:

-- Single-row subquery
SELECT name 
FROM employees 
WHERE department_id = (SELECT department_id FROM departments WHERE name = 'HR');

-- Correlated subquery
SELECT name, salary 
FROM employees e
WHERE salary > (SELECT AVG(salary) FROM employees WHERE department_id = e.department_id);

 

7) What are the ACID properties in SQL?


ACID stands for the properties of a transaction in a database:

  • Atomicity: A transaction is all or nothing; it either completes fully or does not happen at all.
  • Consistency: Ensures the database moves from one valid state to another.
  • Isolation: Ensures that transactions do not interfere with each other.
  • Durability: Once a transaction is committed, it will remain in the database, even in the event of a failure.

8) What is the difference between DELETE, TRUNCATE, and DROP?


  • DELETE: Removes rows from a table based on a condition. It can be rolled back.
  • TRUNCATE: Removes all rows from a table. It is faster than DELETE and cannot be rolled back.
  • DROP: Deletes a table or database structure entirely, including its schema.

Example:

-- DELETE
DELETE FROM employees WHERE id = 5;

-- TRUNCATE
TRUNCATE TABLE employees;

-- DROP
DROP TABLE employees;

 

9) What is a primary key and a foreign key in SQL?


  • Primary Key: A column or a combination of columns that uniquely identifies each row in a table. It cannot contain NULL values.
  • Foreign Key: A column that establishes a link between two tables. It refers to the primary key in another table, ensuring referential integrity.

Example:

-- Primary key example
CREATE TABLE employees (
  id INT PRIMARY KEY,
  name VARCHAR(50)
);

-- Foreign key example
CREATE TABLE orders (
  order_id INT PRIMARY KEY,
  employee_id INT,
  FOREIGN KEY (employee_id) REFERENCES employees(id)
);

 

10) What are the differences between UNION and UNION ALL?


  • UNION: Combines the result sets of two or more SELECT queries, removing duplicate rows.
  • UNION ALL: Combines the result sets of two or more SELECT queries, including all duplicates.

Example:

-- Using UNION
SELECT name FROM employees
UNION
SELECT name FROM customers;

-- Using UNION ALL
SELECT name FROM employees
UNION ALL
SELECT name FROM customers;

 

11) 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 into summary rows, typically used with aggregate functions like COUNT(), SUM(), AVG(), MAX(), and MIN().

Example:

SELECT department, COUNT(*) AS employee_count
FROM employees
GROUP BY department;

 

12) What are aggregate functions in SQL?


Aggregate functions are functions that perform a calculation on a set of values and return a single value. Common aggregate functions include:

  • COUNT(): Returns the number of rows.
  • SUM(): Returns the sum of a numeric column.
  • AVG(): Returns the average value of a numeric column.
  • MIN(): Returns the minimum value.
  • MAX(): Returns the maximum value.

Example:

SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department;

 

13) What is the DISTINCT keyword in SQL?


The DISTINCT keyword is used to remove duplicate rows from the result set. It is typically used in a SELECT statement to return only unique values.

Example:

SELECT DISTINCT department FROM employees;

 

14) What is a VIEW in SQL?


A VIEW is a virtual table that consists of a stored query. It doesn't physically store data but presents data derived from one or more tables. Views simplify complex queries and can provide a level of abstraction.

Example:

CREATE VIEW employee_view AS
SELECT id, name, department
FROM employees
WHERE salary > 50000;

-- Querying the view
SELECT * FROM employee_view;

 

15) What is a trigger in SQL?


A trigger is a database object that automatically executes a specified action when certain events occur on a table or view. The events could be INSERT, UPDATE, or DELETE.

Example:

CREATE TRIGGER after_employee_insert
AFTER INSERT ON employees
FOR EACH ROW
BEGIN
  INSERT INTO audit_log (action, table_name, action_time)
  VALUES ('INSERT', 'employees', NOW());
END;

 

16) What is the difference between CHAR and VARCHAR?


  • CHAR: A fixed-length character string. It always takes the same amount of space regardless of the actual string length, padding with spaces if needed.
  • VARCHAR: A variable-length character string. It only takes the amount of space needed to store the data.

Example:

CREATE TABLE users (
  username VARCHAR(50),
  password CHAR(20)
);

 

17) What is the BETWEEN operator in SQL?


The BETWEEN operator is used to filter the result set within a certain range of values. The range can be numeric, date-based, or alphabetic.

Example:

SELECT name, salary
FROM employees
WHERE salary BETWEEN 40000 AND 60000;

 

18) What is a NULL value in SQL?


A NULL value represents missing or undefined data. It is different from an empty string or zero. You must use IS NULL or IS NOT NULL to check for NULL values, as NULL is not equal to any value, even itself.

Example:

SELECT name
FROM employees
WHERE salary IS NULL;

 

19) What are transaction controls in SQL?


20. What are transaction controls in SQL?

Transactions in SQL ensure that a series of operations are completed successfully and consistently. The common transaction control commands are:

  • BEGIN TRANSACTION: Marks the beginning of a transaction.
  • COMMIT: Saves all changes made during the transaction.
  • ROLLBACK: Undoes all changes made during the transaction if an error occurs.

Example:

BEGIN TRANSACTION;

UPDATE employees
SET salary = salary * 1.1
WHERE department = 'HR';

COMMIT;

 

20) What is the LIKE operator in SQL?


The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. It is often used with wildcard characters:

  • %: Represents zero or more characters.
  • _: Represents a single character.

Example:

SELECT name
FROM employees
WHERE name LIKE 'A%';  -- Names starting with 'A'

SELECT name
FROM employees
WHERE name LIKE '_n';  -- Names ending with 'n'

 

21) What is the IN operator in SQL?


The IN operator is used to check if a value matches any value in a list or subquery. It simplifies the use of multiple OR conditions.

Example:

SELECT name
FROM employees
WHERE department IN ('HR', 'IT', 'Finance');

 

22) What is the CASE statement in SQL?


The CASE statement is used to create conditional logic in SQL queries. It works like an IF-THEN-ELSE statement.

Example:

SELECT name, salary,
  CASE
    WHEN salary > 60000 THEN 'High'
    WHEN salary BETWEEN 40000 AND 60000 THEN 'Medium'
    ELSE 'Low'
  END AS salary_range
FROM employees;

 

23) What is the difference between WHERE and HAVING in SQL?


  • WHERE: Filters records before any grouping is applied (used to filter individual rows).
  • HAVING: Filters records after grouping has been applied (used to filter grouped rows).

Example:

-- Using WHERE
SELECT department, COUNT(*) AS employee_count
FROM employees
WHERE salary > 50000
GROUP BY department;

-- Using HAVING
SELECT department, COUNT(*) AS employee_count
FROM employees
GROUP BY department
HAVING COUNT(*) > 10;

 

24) What are stored procedures and functions in SQL?


  • Stored Procedure: A set of SQL statements that can be executed as a unit. It may accept parameters and return results but does not always return a value.
  • Function: Similar to a stored procedure, but it must return a value.

Example:

-- Stored Procedure
CREATE PROCEDURE GetEmployeeById (IN emp_id INT)
BEGIN
  SELECT * FROM employees WHERE id = emp_id;
END;

-- Function
CREATE FUNCTION GetEmployeeSalary (emp_id INT) RETURNS DECIMAL(10, 2)
BEGIN
  DECLARE salary DECIMAL(10, 2);
  SELECT salary INTO salary FROM employees WHERE id = emp_id;
  RETURN salary;
END;

 

25) What is a self-join in SQL?


A self-join is a join where a table is joined with itself. It is useful for finding relationships within the same table, such as hierarchical or comparative data.

Example:

-- Find employees who have the same manager
SELECT A.name AS Employee, B.name AS Manager
FROM employees A
JOIN employees B ON A.manager_id = B.id;

 

26) What is a composite key in SQL?


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

Example:

CREATE TABLE order_items (
  order_id INT,
  product_id INT,
  quantity INT,
  PRIMARY KEY (order_id, product_id)
);

 

27) What is the difference between a clustered index and a non-clustered index?


  • Clustered Index: The rows of the table are physically sorted according to the index. A table can have only one clustered index.
  • Non-Clustered Index: Creates a separate structure to store pointers to the data in the table. A table can have multiple non-clustered indexes.

Example:

-- Clustered Index
CREATE CLUSTERED INDEX idx_employee_id ON employees(id);

-- Non-Clustered Index
CREATE NONCLUSTERED INDEX idx_employee_name ON employees(name);

 

28) What is a cursor in SQL?


A cursor is a database object used to retrieve, manipulate, and iterate over rows in a result set one at a time. It is commonly used for row-by-row processing.

Example:

DECLARE cursor_employee CURSOR FOR
SELECT name, salary FROM employees;

OPEN cursor_employee;

FETCH NEXT FROM cursor_employee INTO @name, @salary;

-- Process rows here

CLOSE cursor_employee;
DEALLOCATE cursor_employee;

 

29) What is the difference between RANK(), DENSE_RANK(), and ROW_NUMBER()?


  • RANK(): Assigns a rank to rows, but skips ranks when there are ties.
  • DENSE_RANK(): Similar to RANK, but does not skip ranks for ties.
  • ROW_NUMBER(): Assigns a unique sequential number to rows, regardless of ties.

Example:

SELECT name, department, salary,
  RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS rank,
  DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS dense_rank,
  ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS row_number
FROM employees;

 

30) What is the difference between EXISTS and IN?


  • EXISTS: Checks the existence of rows in a subquery. Returns TRUE if the subquery returns any rows.
  • IN: Checks if a value matches any value in a list or subquery.

Example:

-- Using EXISTS
SELECT name FROM employees
WHERE EXISTS (SELECT 1 FROM departments WHERE departments.id = employees.department_id);

-- Using IN
SELECT name FROM employees
WHERE department_id IN (SELECT id FROM departments);

 

31) What is the difference between CAST() and CONVERT()?


Both are used to convert data types, but they have some differences:

  • CAST(): Standard SQL function and easier to read.
  • CONVERT(): SQL Server-specific function with additional formatting options.

Example:

-- Using CAST
SELECT CAST(123.45 AS INT);

-- Using CONVERT
SELECT CONVERT(INT, 123.45);

 

32) What is the purpose of the COALESCE() function in SQL?


The COALESCE() function returns the first non-NULL value in a list of arguments.

Example:

SELECT COALESCE(NULL, NULL, 'Default Value') AS result;

 

33) What is the difference between DELETE and TRUNCATE in SQL?


  • DELETE: Removes specific rows based on a condition. It can be rolled back and triggers are activated.
  • TRUNCATE: Removes all rows from a table without logging individual row deletions. It is faster but cannot be rolled back and does not activate triggers.

Example:

DELETE FROM employees WHERE department = 'HR';
TRUNCATE TABLE employees;

 

34) What is a partition in SQL?


Partitioning divides a large table into smaller, more manageable pieces, improving performance. It can be applied based on range, list, or hash.

Example:

CREATE TABLE sales (
  id INT,
  sale_date DATE,
  amount DECIMAL(10, 2)
)
PARTITION BY RANGE (YEAR(sale_date)) (
  PARTITION p_2023 VALUES LESS THAN (2024),
  PARTITION p_2024 VALUES LESS THAN (2025)
);

 

35) What is the MERGE statement in SQL?


The MERGE statement allows you to perform INSERT, UPDATE, or DELETE operations in a single statement based on specific conditions.

Example:

MERGE INTO employees AS target
USING new_employees AS source
ON target.id = source.id
WHEN MATCHED THEN
  UPDATE SET target.salary = source.salary
WHEN NOT MATCHED THEN
  INSERT (id, name, salary) VALUES (source.id, source.name, source.salary);

 

36) What is the purpose of the INDEX in SQL?


An index improves the speed of data retrieval by providing quick access to rows in a table. However, indexes can slow down INSERT, UPDATE, and DELETE operations due to the overhead of updating the index.

Example:

CREATE INDEX idx_salary ON employees(salary);

 

37) What is database sharding?


Sharding is a method of partitioning where data is distributed across multiple databases or servers to improve scalability and performance. Each shard holds a subset of the data.

38) What is the difference between LOGICAL and PHYSICAL data independence?


  • Logical Data Independence: The ability to change the conceptual schema without altering external schema or application programs.
  • Physical Data Independence: The ability to change the internal schema without altering the conceptual schema.

39) How would you find duplicate rows in a table?


To identify duplicates, use the GROUP BY and HAVING clauses.

Example:

SELECT name, COUNT(*) AS duplicate_count
FROM employees
GROUP BY name
HAVING COUNT(*) > 1;

 

40) What is the difference between OLTP and OLAP?


  • OLTP (Online Transaction Processing): Focuses on transaction-oriented tasks like inserting, updating, and deleting records.
  • OLAP (Online Analytical Processing): Focuses on analytical tasks like complex queries for reporting and decision-making.

41) What are the common constraints in SQL?


  • NOT NULL: Ensures a column cannot have a NULL value.
  • UNIQUE: Ensures all values in a column are unique.
  • PRIMARY KEY: Combines NOT NULL and UNIQUE to uniquely identify rows.
  • FOREIGN KEY: Ensures referential integrity between tables.
  • CHECK: Ensures that all values in a column meet a specific condition.
  • DEFAULT: Sets a default value for a column if no value is specified.

Example:

CREATE TABLE employees (
  id INT PRIMARY KEY,
  name VARCHAR(50) NOT NULL,
  age INT CHECK (age > 18),
  department_id INT UNIQUE
);

 

42) What is an index in SQL?


An index is a database object used to improve the speed of data retrieval operations on a table. It is created on columns that are frequently used in queries, such as in the WHERE clause or in JOIN conditions.

Example:

CREATE INDEX idx_employee_name ON employees(name);