BASIC SQL QUESTIONS
1. Q: What is SQL?
A: SQL (Structured Query Language) is a language used to communicate
with and manipulate relational databases.
2. Q: What are the different types of SQL commands?
A:
o DDL (Data Definition Language): CREATE, ALTER, DROP
o DML (Data Manipulation Language): INSERT, UPDATE, DELETE
o DQL (Data Query Language): SELECT
o DCL (Data Control Language): GRANT, REVOKE
o TCL (Transaction Control Language): COMMIT, ROLLBACK, SAVEPOINT
3. Q: What is a Primary Key?
A: A column or set of columns that uniquely identifies each row in a table.
4. Q: What is a Foreign Key?
A: A key used to link two tables; it's a field in one table that refers to the
primary key in another.
5. Q: What is the difference between WHERE and HAVING?
A: WHERE filters rows before aggregation, HAVING filters after aggregation.
6. Q: How do you select unique records from a table?
A: SELECT DISTINCT column_name FROM table_name;
7. Q: What does NULL mean in SQL?
A: A NULL value represents missing or unknown data.
8. Q: How do you sort results in SQL?
A: Using ORDER BY column_name [ASC|DESC]
9. Q: How do you filter rows in SQL?
A: Using WHERE clause. Example: WHERE age > 30
10.Q: What is the default sorting order in SQL?
A: Ascending (ASC).
INTERMEDIATE SQL QUESTIONS
11.Q: How do you count the number of rows in a table?
A: SELECT COUNT(*) FROM table_name;
12.Q: How do you find the number of employees in each department?
A:
sql
CopyEdit
SELECT department, COUNT(*)
FROM employees
GROUP BY department;
13.Q: How do you get the second highest salary?
A:
sql
CopyEdit
SELECT MAX(salary)
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
14.Q: What is a JOIN? Name its types.
A: A JOIN is used to combine rows from two or more tables.
• INNER JOIN
• LEFT JOIN
• RIGHT JOIN
• FULL OUTER JOIN
• CROSS JOIN
• SELF JOIN
15.Q: Write a query to fetch employee names and their department names.
A:
sql
CopyEdit
SELECT e.name, d.department_name
FROM employees e
INNER JOIN departments d ON e.dept_id = d.id;
16.Q: What is a subquery?
A: A query inside another query.
17.Q: What is the difference between IN and EXISTS?
A: IN evaluates all values and loads them into memory. EXISTS returns true
if subquery returns any row.
18.Q: What is the difference between UNION and UNION ALL?
A: UNION removes duplicates, UNION ALL keeps them.
19.Q: What does GROUP BY do?
A: It groups rows that have the same values into summary rows.
20.Q: What is a correlated subquery?
A: A subquery that uses values from the outer query.
ADVANCED SQL QUESTIONS
21.Q: Write a query to find duplicate records in a table.
A:
sql
CopyEdit
SELECT column1, COUNT(*)
FROM table_name
GROUP BY column1
HAVING COUNT(*) > 1;
22.Q: What is a window function?
A: A function that performs a calculation across a set of rows related to the
current row. Example: ROW_NUMBER(), RANK(), LEAD(), LAG()
23.Q: Difference between RANK() and DENSE_RANK()?
A: RANK() skips numbers for ties; DENSE_RANK() doesn’t.
24.Q: How to retrieve the nth highest salary?
A:
sql
CopyEdit
SELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET n-1;
25.Q: What is normalization?
A: Organizing data to reduce redundancy. Normal forms include 1NF, 2NF,
3NF, BCNF, etc.
26.Q: How do you delete duplicate rows?
A (PostgreSQL example):
sql
CopyEdit
DELETE FROM employees a
USING employees b
WHERE a.id > b.id AND a.email = b.email;
27.Q: What is a CTE?
A: Common Table Expression; a temporary result set defined using WITH
clause.
28.Q: What is a recursive CTE?
A: A CTE that references itself for hierarchical data.
29.Q: What is the difference between DELETE and TRUNCATE?
A:
• DELETE: row-by-row, can be rolled back
• TRUNCATE: removes all rows instantly, cannot be rolled back in some DBs
30.Q: What is indexing?
A: Improves query performance by allowing faster data retrieval.
SCENARIO-BASED QUESTIONS
31.Q: Find employees who joined in the last 3 months.
A:
sql
CopyEdit
SELECT *
FROM employees
WHERE join_date >= CURRENT_DATE - INTERVAL '3 months';
32.Q: Get the top 3 products by sales.
A:
sql
CopyEdit
SELECT product_id, SUM(sales) AS total_sales
FROM orders
GROUP BY product_id
ORDER BY total_sales DESC
LIMIT 3;
33.Q: List customers who didn’t place any order.
A:
sql
CopyEdit
SELECT *
FROM customers
WHERE customer_id NOT IN (
SELECT DISTINCT customer_id
FROM orders
);
34.Q: Get monthly revenue for 2024.
A:
sql
CopyEdit
SELECT DATE_TRUNC('month', order_date) AS month, SUM(amount)
FROM orders
WHERE EXTRACT(YEAR FROM order_date) = 2024
GROUP BY 1
ORDER BY 1;
35.Q: Calculate running total of sales.
A:
sql
CopyEdit
SELECT order_id, order_date, amount,
SUM(amount) OVER (ORDER BY order_date) AS running_total
FROM orders;
36.Q: Find employees with same salary.
A:
sql
CopyEdit
SELECT salary
FROM employees
GROUP BY salary
HAVING COUNT(*) > 1;
37.Q: Show department with highest average salary.
A:
sql
CopyEdit
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
ORDER BY avg_salary DESC
LIMIT 1;
38.Q: Get employees hired in each year.
A:
sql
CopyEdit
SELECT EXTRACT(YEAR FROM hire_date) AS year, COUNT(*)
FROM employees
GROUP BY year
ORDER BY year;
39.Q: Compare sales this month vs last month.
A:
sql
CopyEdit
SELECT
DATE_TRUNC('month', order_date) AS month,
SUM(amount) AS total,
LAG(SUM(amount)) OVER (ORDER BY DATE_TRUNC('month', order_date)) AS
prev_total
FROM orders
GROUP BY 1;
40.Q: Fetch customers with 2 or more orders in the same day.
A:
sql
CopyEdit
SELECT customer_id, order_date
FROM orders
GROUP BY customer_id, order_date
HAVING COUNT(*) >= 2;
SQL CONCEPT QUESTIONS
41.Q: Can a table have multiple primary keys?
A: No. Only one primary key (can be composite).
42.Q: What is a composite key?
A: A primary key made up of two or more columns.
43.Q: Can NULL be a part of a primary key?
A: No. Primary keys must be unique and not null.
44.Q: What’s the difference between CHAR and VARCHAR?
A: CHAR is fixed-length, VARCHAR is variable-length.
45.Q: How do you handle NULLs in aggregate functions?
A: Most aggregate functions ignore NULLs except COUNT(*).
46.Q: What is the purpose of CASE statement?
A: Conditional logic within SQL queries.
47.Q: How do you pivot data in SQL?
A: Using CASE with GROUP BY, or the PIVOT clause (in some DBs).
48.Q: Can you use GROUP BY with window functions?
A: Yes, but window functions work on the full result set.
49.Q: What is the difference between a table and a view?
A: A table stores data; a view is a saved query result, doesn't store data
physically.
50.Q: What is denormalization?
A: The process of introducing redundancy into a table for faster reads.
Would you like me to turn this into a PDF or interactive quiz for easier study?
MORE SQL CONCEPT QUESTIONS
1. Q: What is the difference between a clustered and non-clustered index?
A:
o Clustered index: sorts and stores data rows physically in the table;
one per table.
o Non-clustered index: stores a pointer to the actual data; multiple
allowed per table.
2. Q: What is ACID in databases?
A:
o Atomicity: All-or-nothing operations
o Consistency: Maintains DB integrity
o Isolation: Transactions don’t interfere
o Durability: Changes persist after commit
3. Q: What is the difference between OLTP and OLAP?
A:
o OLTP: Transactional systems, normalized, fast writes
o OLAP: Analytical systems, denormalized, fast reads
4. Q: What is normalization and why is it important?
A: It removes redundancy and ensures data integrity through structured data
organization.
5. Q: What is the purpose of 1NF, 2NF, and 3NF?
A:
o 1NF: Eliminate repeating groups
o 2NF: Eliminate partial dependencies
o 3NF: Eliminate transitive dependencies
6. Q: What is a surrogate key?
A: An artificial key (e.g., auto-increment ID) used as the primary key
instead of natural data.
7. Q: What is a natural key?
A: A key formed from real data attributes (e.g., SSN, email).
8. Q: What is referential integrity?
A: Ensures foreign keys in one table match primary keys in another.
9. Q: What is a constraint in SQL?
A: A rule enforced on data in a table, e.g., NOT NULL, UNIQUE, CHECK,
PRIMARY KEY, FOREIGN KEY.
10.Q: What is a schema in SQL?
A: A logical container for database objects like tables, views, procedures.
ADVANCED CONCEPTS
11.Q: What is a materialized view?
A: A view that stores the result set physically and can be refreshed
periodically.
12.Q: What are the disadvantages of indexing?
A: Slows down inserts/updates/deletes; consumes disk space.
13.Q: What is the difference between DELETE, DROP, and TRUNCATE?
A:
• DELETE: removes rows, can filter, can be rolled back
• TRUNCATE: removes all rows quickly, no rollback
• DROP: deletes the entire table structure
14.Q: What is data integrity?
A: Accuracy and consistency of data over its lifecycle.
15.Q: What is an anomaly in SQL?
A: Undesired side effect like insertion, deletion, or update anomalies caused
by poor schema design.
16.Q: What is a composite primary key?
A: A primary key made up of two or more columns.
17.Q: What is an alias in SQL?
A: A temporary name for a column or table using AS.
18.Q: Can a table have multiple foreign keys?
A: Yes.
19.Q: What is the default value of NULL + 100?
A: NULL — any arithmetic with NULL yields NULL.
20.Q: Can you use ORDER BY in a view?
A: You can, but the ordering is not guaranteed when selecting from the view
unless explicitly specified in the outer query.
SQL DESIGN & PRACTICES
21.Q: When should you use INDEX?
A: On columns frequently used in WHERE, JOIN, GROUP BY, or ORDER
BY clauses.
22.Q: When should you avoid using indexes?
A: On columns with low cardinality (e.g., boolean), or when insert/update
speed is more critical.
23.Q: What is a covering index?
A: An index that includes all columns needed by a query (no need to access
the table).
24.Q: What is the difference between TEMPORARY TABLE and CTE?
A:
• Temporary table: physical, exists during session
• CTE: logical, exists only for the query
25.Q: What are scalar vs aggregate functions?
A:
• Scalar: return single value per row (e.g., UPPER())
• Aggregate: return single value per group (e.g., SUM())
26.Q: What is the use of COALESCE()?
A: Returns the first non-NULL value in a list.
27.Q: How do NULLs affect DISTINCT?
A: NULLs are treated as equal, so duplicates are removed.
28.Q: What is a transaction?
A: A sequence of operations performed as a single logical unit of work.
29.Q: What is a deadlock?
A: A situation where two transactions wait for each other to release locks,
causing a cycle.
30.Q: What is the purpose of ISOLATION LEVEL in SQL transactions?
A: Controls visibility of changes made in one transaction to other
transactions.