SQL & Databases Interview Questions and Answers

Relational database fundamentals, query execution lifecycle, advanced JOINs, subqueries, window functions, indexing, ACID transactions, and query optimization.

Practise 10 random 44 peer-reviewed questions
SQL & Databases Interview Syllabus & Preparation Strategy

Whether you are preparing for entry-level SQL & Databases interview questions for freshers or senior software engineer interview questions addressing concurrency, scalability, and system architecture, this track provides peer-reviewed model answers with syntax walkthroughs, edge cases, and practical interview tips.

1 What type of language is SQL? Medium

Declarative (non-procedural). You state *what* result you want, not *how* to compute it. The database's query optimizer decides the "how" — which indexes to use, which join order is fastest, etc.

Compare with PL/SQL (Oracle) or T-SQL (SQL Server), which are procedural extensions that add loops, variables, and conditional logic.

2 Which are valid SQL keywords? Medium

SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, JOIN, INSERT, UPDATE, DELETE, CREATE, ALTER, DROP, INDEX, UNION, LIMIT, DISTINCT, AS, AND, OR, NOT, IN, BETWEEN, LIKE, IS NULL, EXISTS, CASE, WHEN, THEN, ELSE, END.

3 Which SQL statement extracts data? Medium

SELECT. Optional clauses: WHERE, GROUP BY, HAVING, ORDER BY, LIMIT, JOIN.

SELECT name AS full_name, salary * 12 AS annual_salary
FROM employees
WHERE department = 'Engineering'
ORDER BY annual_salary DESC;
4 How to select all records from table Products? Medium
SELECT * FROM products;

⚠️ *Interview tip*: Always follow up with "But in production, I list explicit columns to reduce network overhead and prevent breaking if columns are reordered or added."

5 What does the FROM clause do? Medium

The FROM clause identifies the source table(s), views, joined tables, or subqueries from which data is to be retrieved, filtered, and aggregated.

### Logical SQL Processing Order:
In SQL execution internals, FROM is the very first clause evaluated by the database engine:

  1. FROM (identifies source tables and evaluates JOIN operations)
  2. WHERE (filters individual rows)
  3. GROUP BY (aggregates rows into groups)
  4. HAVING (filters aggregated groups)
  5. SELECT (projects columns and computes expressions)
  6. DISTINCT (deduplicates rows)
  7. ORDER BY (sorts output)
  8. LIMIT / OFFSET (paginates results)

Because FROM executes first, aliases defined in the FROM clause are recognized in all subsequent clauses.

6 Correct GROUP BY syntax? Medium
SELECT name, COUNT(name) FROM customers GROUP BY name;

In standard SQL (and MySQL 5.7+ with ONLY_FULL_GROUP_BY), any non-aggregated column in SELECT must appear in GROUP BY.

7 WHERE vs HAVING? Medium

| WHERE | HAVING |
|-------|--------|
| Filters rows | Filters groups |
| Executes before GROUP BY | Executes after GROUP BY |
| Cannot use aggregates | Can use COUNT(), SUM(), etc. |
| Can reference any column | Can only reference grouped columns or aggregates |

SELECT department, AVG(salary) AS avg_sal
FROM employees
WHERE hire_date > '2020-01-01'      -- Filter rows first
GROUP BY department
HAVING AVG(salary) > 60000;         -- Then filter groups

---

8 What is JOIN used for? Medium

A JOIN clause in SQL combines rows from two or more tables based on a related column between them (typically a Foreign Key referencing a Primary Key).

### The Need for JOINs:
In relational databases, data is normalized across multiple tables to avoid data redundancy:

SELECT 
    orders.order_id,
    orders.order_date,
    customers.first_name,
    customers.email
FROM orders
JOIN customers ON orders.customer_id = customers.customer_id;

### Common Join Types:

  • INNER JOIN: Returns rows when there is a match in both tables.
  • LEFT JOIN: Returns all rows from left table, with matching rows from right table (or NULLs).
  • RIGHT JOIN: Returns all rows from right table.
  • FULL OUTER JOIN: Returns rows when there is a match in either table.
  • CROSS JOIN: Produces a Cartesian product of both tables.
9 Most common type of join? Medium

The INNER JOIN is the most widely used type of join in relational database systems.

In fact, INNER is the default join type in standard SQL—writing FROM A JOIN B ON ... is parsed by database engines as FROM A INNER JOIN B ON ....

It returns exclusively those rows where the join condition evaluates to TRUE in both tables, filtering out orphan records.

10 What are different JOINs in SQL? Medium
  1. INNER JOIN — matching rows only
  2. LEFT (OUTER) JOIN — all left + matched right
  3. RIGHT (OUTER) JOIN — all right + matched left
  4. FULL OUTER JOIN — all rows from both
  5. CROSS JOIN — Cartesian product
  6. SELF JOIN — table joined to itself
11 Which is NOT TRUE about the ON clause? Medium

The ON clause specifies the join condition. It improves readability over the old comma-syntax, supports multi-column joins (ON a.id = b.id AND a.type = b.type), and is required for outer joins. Any statement claiming otherwise is false.

12 Inner join result? Medium

An INNER JOIN returns only the subset of rows where the join predicate (ON condition) matches in both tables simultaneously:

### Visual Venn Diagram Concept:
If Table A has IDs [1, 2, 3] and Table B has IDs [2, 3, 4], the inner join on A.id = B.id returns only rows for IDs [2, 3].

SELECT e.name, d.dept_name
FROM employees e
INNER JOIN departments d ON e.dept_id = d.id;

If an employee has a NULL or non-existent dept_id, that employee will not appear in the result set.

13 Can you join 3 tables with INNER JOIN? Medium

Yes. There's no practical limit (though performance degrades with many joins).

SELECT f.name, d.name AS division, c.name AS country
FROM faculty f
INNER JOIN division d ON f.division_id = d.id
INNER JOIN country c ON f.country_id = c.id;
14 Can you join a table to itself? Medium

Yes — SELF JOIN. You must use aliases to distinguish the two instances.

SELECT a.name AS employee, b.name AS manager
FROM employees a, employees b
WHERE a.manager_id = b.id;
15 What is true about Cartesian Products? Medium

A Cartesian product occurs when tables are joined without a condition. Every row in Table A pairs with every row in Table B: m × n rows total. It's usually a bug, but CROSS JOIN is explicit and valid for combinatorial data.

16 UNION in relational algebra? Medium

In relational algebra, the UNION of two sets $A \cup B$ combines all distinct tuples from both relations into a single unified relation.

### UNION vs UNION ALL in SQL:

-- UNION removes duplicate records (performs sorting/deduplication)
SELECT city FROM customers
UNION
SELECT city FROM suppliers;

-- UNION ALL retains all rows including duplicates (much faster)
SELECT city FROM customers
UNION ALL
SELECT city FROM suppliers;

*Performance rule:* Always prefer UNION ALL unless business logic strictly requires deduplicating rows across the combined sets.

17 UNION vs UNION ALL? Medium

| UNION | UNION ALL |
|-------|-----------|
| Removes duplicates | Keeps duplicates |
| Slower (sort + dedup) | Faster |
| Use when uniqueness matters | Use when sets are already distinct or duplicates are meaningful |

18 A SELECT statement whose results are used in filtering the main query is called? Medium

A SELECT statement nested inside another SQL statement to supply values for filtering or computation is called a subquery (also known as an inner query or nested query):

SELECT product_name, price 
FROM products 
WHERE price > (
    SELECT AVG(price) FROM products
);

### Types of Subqueries:

  1. Scalar Subquery: Returns exactly one row and one column.
  2. Multi-Row Subquery: Returns a list of values, evaluated with IN, ANY, or ALL.
  3. Correlated Subquery: References columns from the outer query, re-evaluated for each outer row.
19 Subqueries can be nested in... Medium

Subqueries can be nested within virtually every major SQL clause and statement:

  1. WHERE Clause: Filtering candidate rows (WHERE id IN (SELECT ...))
  2. FROM Clause: Acting as a derived table or inline view (FROM (SELECT ...) AS sub)
  3. SELECT Projection Clause: Computing scalar values per row
  4. HAVING Clause: Filtering aggregated groups
  5. INSERT INTO Statement: Populating tables from query results
  6. UPDATE and DELETE Statements: Targeting records based on subquery criteria
20 A subquery inside a subquery is called? Medium

A subquery placed inside another subquery is called a nested subquery (or multi-level subquery):

SELECT customer_name 
FROM customers 
WHERE customer_id IN (
    SELECT customer_id 
    FROM orders 
    WHERE order_id IN (
        SELECT order_id 
        FROM order_items 
        WHERE product_id = 101
    )
);

While nested subqueries are intuitive, deeply nested subqueries can degrade execution plan efficiency. Modern optimizers often rewrite them into JOIN operations, or developers rewrite them into Common Table Expressions (CTEs) using WITH.

Showing 20 of 44 questions

Frequently Asked Questions About SQL & Databases Interviews

What do hiring managers evaluate in SQL & Databases technical rounds?

Technical interviewers look for foundational fluency, idiomatic syntax, clarity when communicating complex logic, and awareness of performance trade-offs (e.g. memory footprint, render performance, and network latency) in production environments.

What are the best interview tips for practicing SQL & Databases questions?

Use active recall: summarize each answer in your own words before revealing the model solution. Focus on explaining why a certain approach is chosen rather than just memorizing code syntax.