Blog / Interview Prep
Interview Prep

150+ SQL Interview Questions for Freshers (2026 Guide)

150+ SQL interview questions for freshers — joins, GROUP BY, subqueries, CTEs, window functions, 50 coding problems, and a 30-day prep plan.

If you've sat through even one technical round for a Data Analyst, Business Analyst, or junior developer role, you already know: the interviewer doesn't care whether you can define what a JOIN is. They care whether you can look at two unfamiliar tables and actually pull the right answer out of them, live, while explaining your thinking as you go. That's the real skill being tested in every SQL interview — and it's exactly what this guide is built to prepare you for.

SQL interview questions for freshers show up in almost every data and software role today because SQL itself is unavoidable — nearly every company's operational and analytical data lives in a relational database, and someone has to be able to query it correctly. Unlike a framework or a specific programming language, SQL doesn't go out of fashion; it's been the standard for talking to structured data for over four decades, and every serious analytics or engineering role in 2026 still expects it on day one.

That's also exactly why SQL interviews eliminate so many candidates. It's deceptively easy to feel like you know SQL after watching a few tutorials — the syntax reads almost like English — but there's a wide gap between recognizing SELECT ... FROM ... WHERE and being able to construct a multi-table query with a subquery and a window function under time pressure, with no autocomplete and someone watching. Most candidates who fail don't fail because SQL is inherently hard; they fail because they practiced reading queries instead of writing them from scratch.

This guide is built to close that gap completely. It's organized the way a real interview process actually unfolds: why SQL matters and how companies test it, then 150+ questions grouped by topic (joins, subqueries, CTEs, window functions, and more) with real explanations — not definitions to memorize — followed by 50 hands-on coding problems, real company interview patterns, industry-specific scenario questions, a 25-exercise practical test, a complete cheat sheet, the mistakes that quietly sink otherwise-strong candidates, and a 30-day day-by-day plan to get from "I've heard of SQL" to genuinely interview-ready.

Who this guide is for: freshers and college students with zero SQL background, career switchers moving into analytics, and working professionals — Data Analysts, Business Analysts, Software Engineers, and Database Administrators — who want a single, comprehensive reference to prepare from. Use the table of contents above to jump straight to what you need.

Why SQL Is Important in 2026

Job demand. SQL appears in the requirements section of a larger share of Data Analyst, Business Analyst, and even Software Engineer job postings in India than any single programming language — because regardless of what front-end or BI tool a company uses, the data underneath almost always sits in a relational database that someone needs to query directly.

Salary impact. SQL is one of the highest-leverage individual skills for salary growth in analytics roles. Candidates with strong SQL (joins, subqueries, window functions, basic optimization) typically command a meaningful premium over candidates who only know basic SELECT/WHERE-level queries, because SQL fluency directly determines how independently you can work — without SQL, you're dependent on someone else to pull every number you need. See the full breakdown in the Data Analyst Salary in India guide.

Industries. Banking and financial services, e-commerce, retail, healthcare, telecom, SaaS, and IT services companies all run core parts of their operations and reporting through relational databases — SQL isn't a "nice to have" niche skill in any of them, it's foundational infrastructure knowledge.

Companies hiring SQL professionals. From IT services giants (TCS, Infosys, Wipro, Cognizant, Capgemini) to Big 4 consulting firms (Deloitte, EY, KPMG) to product companies and Big Tech (Amazon, Flipkart, Microsoft, Google), SQL proficiency is tested at some stage of the hiring process for nearly every data-adjacent role — the depth of testing varies by company type, but its presence almost never does.

Future demand. Even as AI tools and natural-language-to-SQL interfaces improve, someone still has to validate that generated queries are correct, understand why a query returns what it does, and design the underlying data structures in the first place — SQL fluency remains the skill that lets you verify and trust what a tool produces, not just accept it blindly. That verification layer is becoming more valuable, not less, as more people rely on AI-assisted querying without understanding the fundamentals.

📋 Not sure how your current SQL level compares to what interviews actually expect? The Data Analyst Roadmap 2026 lays out exactly what "interview-ready" SQL looks like at each stage.

How SQL Interviews Are Conducted

Knowing the format you'll face matters as much as knowing the answers — a candidate who's only rehearsed spoken definitions can freeze the first time they're handed a live query editor. Here's what to expect, roughly in the order companies tend to use them.

Online assessments (MCQs). Common in high-volume campus hiring (TCS, Infosys, Wipro, Cognizant) as an early filter — multiple-choice questions on SQL syntax, JOIN behavior, and output prediction, usually timed and auto-scored on a platform like HackerRank or a company's own test portal.

SQL query writing (live, on paper or a shared doc). A conversational round where you're asked to write a specific query — "find the second-highest salary," "get total sales by region" — either typed live or handwritten/whiteboarded, testing correctness and whether you can explain your reasoning.

Live coding (real query editor). Increasingly the standard at product companies and Big Tech — you solve real problems in an actual SQL editor (HackerRank, CoderPad, LeetCode-style interfaces) against a real or simulated dataset, often screen-shared with an interviewer watching and asking follow-up questions as you type.

Database design questions. More common for Software Engineer and Database Administrator roles — designing a schema for a given scenario (e.g., "design tables for a ride-sharing app"), testing understanding of normalization, keys, and relationships rather than query-writing itself.

Scenario questions. A business situation framed in plain English ("marketing wants to know which campaign drove the most repeat purchases") that you must translate into the right query approach — testing whether you can bridge business language and SQL logic, not just syntax recall.

Case studies. More common at Big 4 firms (Deloitte, EY, KPMG) and consulting-style companies — a business problem requiring structured reasoning, sometimes with a SQL component, sometimes purely conceptual.

Optimization questions. Common in senior or Database Administrator interviews — "this query is slow, how would you speed it up?" — testing understanding of indexes, execution plans, and query structure, not just correctness.

Hands-on SQL tests (timed take-home or in-person). A full practical assessment — multiple queries against a provided schema within a time limit, closely mirroring what the 25-exercise practical test later in this guide is designed to simulate.

🎯 The single biggest prep mistake: reading queries instead of writing them. Every question below includes a real, typeable example — practice typing it yourself, not just reading the answer.

SQL Interview Questions: The Complete Guide (150+)

Throughout this section, examples reuse a small set of realistic tables so you can focus on the logic, not re-learning a new schema every time:

employees(employee_id, first_name, last_name, department_id, manager_id, salary, hire_date, city)
departments(department_id, department_name)
orders(order_id, customer_id, order_date, amount, status)
customers(customer_id, customer_name, city, signup_date)
products(product_id, product_name, category, price)

SQL Basics & Database Concepts

1. What is SQL, and why is it called a "declarative" language? Beginner

Answer: SQL (Structured Query Language) is the standard language for creating, querying, and managing data in a relational database. It's declarative because you describe what result you want (e.g., "give me all customers from Delhi"), not how to retrieve it step by step — the database engine decides the actual retrieval path internally.

Why it matters: This distinction is why two structurally different queries can return the identical result, and why the database's internal optimizer (not your query's literal wording) ultimately determines performance.

2. What is a relational database? Beginner

Answer: A relational database organizes data into tables (rows and columns) that can be linked to each other through shared key values — the "relational" part refers to these relationships between tables, not to any real-world relationship in the data itself.

Common mistake: Assuming "relational" means the data is naturally connected in a business sense — it actually refers to the structural model (tables linked via keys), which the database designer defines deliberately.

3. What is the difference between SQL and MySQL/PostgreSQL/SQL Server? Beginner

Answer: SQL is the language/standard itself. MySQL, PostgreSQL, and SQL Server are specific database management systems (DBMS) that implement SQL, each with small syntax differences and extensions on top of the ANSI SQL standard.

Real interview use case: A common early question to check whether you understand SQL as portable knowledge, not tied to one specific tool — most of what you learn transfers directly between MySQL, PostgreSQL, and SQL Server with only minor syntax adjustments.

4. What is a table, a row, and a column? Beginner

Answer: A table stores a collection of related data as a grid; a row (or record) represents one single entry in that table; a column (or field) represents one specific attribute shared by every row, like salary or hire_date.

5. What is the difference between a database and a schema? Beginner

Answer: A database is the overall container holding all your data, tables, and objects. A schema is a logical grouping/namespace within a database (e.g., sales.orders vs hr.employees) — used to organize related tables and control access, especially in larger systems with many tables.

6. What is a query, and what is a result set? Beginner

Answer: A query is a request written in SQL asking the database to perform an operation (usually retrieve data). A result set is the table of rows returned by a SELECT query — it isn't stored permanently unless you explicitly save it (e.g., into a new table or a view).

More SQL basics questions to be ready for:

Question Quick Answer
What is a database management system (DBMS)? Software that manages databases — storing, retrieving, and securing data — examples include MySQL, PostgreSQL, Oracle, and SQL Server.
What is an RDBMS? A DBMS specifically built around the relational model — tables linked via keys — as opposed to NoSQL systems using other data models.
What is the SELECT statement used for? Retrieving data from one or more tables — the most frequently used SQL statement.
What does the semicolon do at the end of a SQL statement? Terminates the statement, especially important when running multiple statements together in one script.
What is a SQL client/IDE? A tool (like MySQL Workbench, pgAdmin, or DBeaver) used to write and run SQL queries against a database with a visual interface.
Is SQL case-sensitive? SQL keywords aren't case-sensitive (SELECT and select work identically), but table/column names can be, depending on the database and its configuration.

DDL, DML, DCL & TCL Commands

1. What is the difference between DDL, DML, DCL, and TCL? Beginner

Answer: DDL (Data Definition Language) defines structure — CREATE, ALTER, DROP, TRUNCATE. DML (Data Manipulation Language) manages data within that structure — SELECT, INSERT, UPDATE, DELETE. DCL (Data Control Language) manages permissions — GRANT, REVOKE. TCL (Transaction Control Language) manages transactions — COMMIT, ROLLBACK, SAVEPOINT.

Why it matters: This categorization comes up constantly as a rapid-fire early question — being able to place any SQL command into the correct category signals real conceptual understanding, not just memorized syntax.

2. What is the difference between DELETE, TRUNCATE, and DROP? Beginner

Example:

DELETE FROM orders WHERE status = 'Cancelled';  -- removes specific rows, can be rolled back
TRUNCATE TABLE orders;                           -- removes ALL rows instantly, resets identity
DROP TABLE orders;                               -- removes the entire table structure permanently

Why it matters: DELETE is a DML command (logged row-by-row, roll-back-able within a transaction, supports WHERE); TRUNCATE and DROP are DDL commands (typically faster, not filterable by row, and in most databases can't be rolled back once committed).

Common mistake: Using TRUNCATE when you only meant to delete a filtered subset of rows — TRUNCATE always removes everything and cannot take a WHERE clause.

3. What is the difference between CREATE, ALTER, and DROP? Beginner

Example:

CREATE TABLE products (product_id INT PRIMARY KEY, product_name VARCHAR(100), price DECIMAL(10,2));
ALTER TABLE products ADD COLUMN category VARCHAR(50);
DROP TABLE products;

Why it matters: CREATE defines a new object, ALTER modifies an existing object's structure (adding/removing columns, changing data types), and DROP removes the object entirely — all three are DDL and typically auto-commit immediately in most databases.

4. What is the difference between INSERT, UPDATE, and DELETE? Beginner

Example:

INSERT INTO customers (customer_id, customer_name, city) VALUES (101, 'Priya Sharma', 'Mumbai');
UPDATE customers SET city = 'Pune' WHERE customer_id = 101;
DELETE FROM customers WHERE customer_id = 101;

Common mistake: Running an UPDATE or DELETE without a WHERE clause, which affects every row in the table — always double-check the WHERE clause before executing either, especially against a production database.

5. What is the difference between GRANT and REVOKE? Intermediate

Example:

GRANT SELECT, INSERT ON orders TO analyst_role;
REVOKE INSERT ON orders FROM analyst_role;

Why it matters: These DCL commands control who can do what — GRANT assigns permissions, REVOKE removes them. Rarely tested deeply for fresher roles, but knowing they exist and their basic syntax signals full-picture database awareness.

6. What is the difference between COMMIT and ROLLBACK? Intermediate

Example:

BEGIN TRANSACTION;
UPDATE accounts SET balance = balance - 5000 WHERE account_id = 1;
UPDATE accounts SET balance = balance + 5000 WHERE account_id = 2;
COMMIT;  -- makes both changes permanent
-- or ROLLBACK; to undo both if something went wrong

Real interview use case: Explaining a bank transfer scenario — both the debit and credit must succeed together, or neither should happen; COMMIT/ROLLBACK is exactly how that all-or-nothing guarantee is enforced.

More DDL/DML/DCL/TCL questions to be ready for:

Question Quick Answer
What does the ALTER TABLE ... RENAME COLUMN do? Renames an existing column without affecting its data or data type.
What is a SAVEPOINT? A named point within a transaction that you can roll back to, without undoing the entire transaction.
Can DDL statements be rolled back? In most databases (MySQL, for example), DDL auto-commits and cannot be rolled back; PostgreSQL is a notable exception that supports transactional DDL.
What is the difference between INSERT INTO ... VALUES and INSERT INTO ... SELECT? VALUES inserts specific literal values you provide; SELECT inserts the result of a query, useful for copying data from one table into another.
What does ALTER TABLE ... DROP COLUMN do? Permanently removes a column and its data from a table structure.

Constraints, Keys & NULL Handling

1. What is a Primary Key? Beginner

Example: CREATE TABLE employees (employee_id INT PRIMARY KEY, first_name VARCHAR(50));

Answer: A Primary Key uniquely identifies each row in a table — it must contain unique values and cannot be NULL. A table can have only one Primary Key, though that key can span multiple columns (a composite key).

2. What is a Foreign Key, and what does it enforce? Beginner

Example: employees.department_id references departments.department_id as a Foreign Key.

Answer: A Foreign Key is a column (or set of columns) in one table that references a Primary Key in another table, enforcing referential integrity — you can't insert an employee with a department_id that doesn't exist in the departments table, and by default you can't delete a department that still has employees referencing it.

Real interview use case: "What happens if you try to insert a row with a foreign key value that doesn't exist in the parent table?" — Answer: the database rejects the insert with a constraint violation error, unless the foreign key allows NULL.

3. What is the difference between a Primary Key and a Unique Key? Intermediate

Answer: Both enforce uniqueness, but a table can have only one Primary Key (which also cannot be NULL) while it can have multiple Unique Key constraints, and Unique Key columns can allow one NULL value (behavior varies slightly by database).

4. What is a composite key? Intermediate

Example: PRIMARY KEY (order_id, product_id) in an order_details table, where neither column alone is unique, but the combination is.

Real interview use case: Common in many-to-many relationship tables — like an order_details table linking orders and products, where each row represents one product within one order.

5. What does NOT NULL, UNIQUE, CHECK, and DEFAULT do? Beginner

Example:

CREATE TABLE employees (
  employee_id INT PRIMARY KEY,
  email VARCHAR(100) UNIQUE NOT NULL,
  salary DECIMAL(10,2) CHECK (salary > 0),
  hire_date DATE DEFAULT CURRENT_DATE
);

Answer: NOT NULL requires a value; UNIQUE disallows duplicate values; CHECK enforces a custom validation rule; DEFAULT supplies an automatic value when none is provided.

6. What does NULL actually mean in SQL, and why can't you compare it with =? Intermediate

Example: WHERE manager_id = NULL never returns any rows — the correct syntax is WHERE manager_id IS NULL.

Why it matters: NULL represents "unknown" or "absent," not zero or empty string — and any comparison against an unknown value (NULL = NULL, NULL = 5) itself evaluates to unknown (NULL), not TRUE or FALSE. This is one of the most consistently tested "gotcha" concepts in SQL interviews.

Common mistake: Writing WHERE column != NULL expecting it to catch non-null values — it must be WHERE column IS NOT NULL.

7. How does NULL affect aggregate functions like COUNT, SUM, and AVG? Intermediate

Example: SELECT AVG(bonus) FROM employees; — if 3 out of 10 employees have a NULL bonus, AVG divides by 7, not 10, since NULLs are excluded from the calculation entirely, not treated as zero.

Real interview use case: A very common trap question — "why doesn't this average match what I expected?" — testing whether you understand that NULLs are silently skipped by SUM/AVG/COUNT(column), not counted as zero.

More keys, constraints & NULL questions to be ready for:

Question Quick Answer
Can a Foreign Key be NULL? Yes, unless explicitly constrained with NOT NULL — this represents "no related parent record," which is valid in many designs (e.g., an employee with no assigned manager).
What happens on DELETE if a Foreign Key constraint exists? Depends on the ON DELETE rule defined: RESTRICT (block the delete), CASCADE (delete child rows too), SET NULL (set the foreign key to NULL), or NO ACTION.
What is a surrogate key vs a natural key? A surrogate key is an artificial, system-generated identifier (like an auto-increment ID) with no business meaning; a natural key is derived from real business data (like an email or SSN) that could theoretically change.
What does the CHECK constraint enforce that NOT NULL doesn't? A custom condition beyond just "must have a value" — e.g., ensuring salary is always greater than zero.
Can two NULL values be considered "equal" for a UNIQUE constraint? Behavior varies by database — most (including MySQL and PostgreSQL) treat NULLs as distinct from each other, allowing multiple NULLs in a UNIQUE column; SQL Server treats them as duplicates by default in older versions.

Normalization & Database Design

1. What is normalization, and why does it matter? Intermediate

Answer: Normalization is the process of organizing tables to reduce data redundancy and improve data integrity, typically by splitting a single flat table into multiple related tables connected via keys — reducing the risk of inconsistent data (e.g., a customer's city spelled two different ways in two different rows).

2. What is First Normal Form (1NF)? Intermediate

Answer: A table is in 1NF if every column holds a single (atomic) value — no repeating groups or comma-separated lists within one cell, and each row is uniquely identifiable.

Example (violates 1NF): A phone_numbers column containing "9876543210, 9123456780" in one cell — this should be split into a separate row per phone number, or a related child table.

3. What is Second Normal Form (2NF)? Advanced

Answer: A table is in 2NF if it's already in 1NF, and every non-key column depends on the entire primary key, not just part of it — relevant specifically for tables with a composite primary key.

Example (violates 2NF): In an order_details table with a composite key (order_id, product_id), a column like product_name depends only on product_id, not the full composite key — it should live in the products table instead.

4. What is Third Normal Form (3NF)? Advanced

Answer: A table is in 3NF if it's already in 2NF, and no non-key column depends on another non-key column (no transitive dependency).

Example (violates 3NF): An employees table storing both department_id and department_name — department_name depends on department_id, not directly on employee_id, so it should be moved to a separate departments table.

Why it matters: 3NF is the practical target for most transactional database designs — it's the level most interviewers expect you to explain confidently, even if you don't recall the exact formal definitions of BCNF or higher normal forms.

5. What is denormalization, and when is it actually the right choice? Advanced

Answer: Denormalization intentionally combines normalized tables back together (accepting some redundancy) to reduce the number of joins needed and improve read performance — commonly used in reporting/analytics systems (data warehouses) where read speed matters more than write efficiency or storage savings.

Real interview use case: "Why might a data warehouse use a denormalized star schema instead of a fully normalized transactional design?" — Answer: analytical queries run faster with fewer joins, and reporting systems are read-heavy, not write-heavy, so the usual redundancy trade-off flips in favor of denormalization.

More normalization & database design questions to be ready for:

Question Quick Answer
What is a star schema? A denormalized design with one central fact table connected to multiple dimension tables — common in data warehouses and BI tools like Power BI.
What is a snowflake schema? A star schema where dimension tables are further normalized into sub-dimensions — reduces redundancy further, at the cost of more joins.
What is an entity-relationship (ER) diagram? A visual representation of tables, their columns, and the relationships between them — used to plan database structure before building it.
What is a one-to-many relationship? One row in a table (e.g., departments) can relate to many rows in another (e.g., employees) — the most common relationship type in relational design.
What is a many-to-many relationship, and how is it implemented? A relationship where many rows in one table relate to many rows in another (e.g., students and courses) — implemented using a junction/bridge table with foreign keys to both.
What is referential integrity? The guarantee that relationships between tables (via foreign keys) always remain valid — no orphaned rows referencing a non-existent parent.

🗄️ Fundamentals like these come up as rapid warm-up questions in almost every SQL round — practicing them until you can answer without hesitation frees up mental space for the harder query-writing questions later. Practice free on SQLabHub.com.

SQL Joins (INNER, LEFT, RIGHT, FULL, SELF, CROSS)

Joins are the single most heavily tested SQL topic in interviews — expect at least one join question in nearly every round, fresher or experienced.

1. What is an INNER JOIN? Beginner

Example:

SELECT o.order_id, c.customer_name
FROM orders o
INNER JOIN customers c ON o.customer_id = c.customer_id;

Output example: Only orders that have a matching customer record are returned — any order with a customer_id not present in customers is excluded entirely.

Explanation: INNER JOIN returns only rows where the join condition matches in both tables — it's the most restrictive and most commonly used join type.

2. What is a LEFT JOIN (LEFT OUTER JOIN)? Beginner

Example:

SELECT o.order_id, c.customer_name
FROM orders o
LEFT JOIN customers c ON o.customer_id = c.customer_id;

Output example: Every order appears, even if its customer_id has no matching row in customers — in that case, customer_name shows as NULL.

Real interview use case: LEFT JOIN is used specifically to keep every row from the "main" table even when related data might be missing — extremely common for finding orphaned records or data-quality gaps, e.g., "find all orders with no matching customer record" by adding WHERE c.customer_id IS NULL.

3. What is a RIGHT JOIN, and why is it rarely used in practice? Beginner

Example:

SELECT o.order_id, c.customer_name
FROM orders o
RIGHT JOIN customers c ON o.customer_id = c.customer_id;

Why it matters: RIGHT JOIN returns all rows from the right table plus matches from the left — functionally identical to swapping the table order and using LEFT JOIN. Most SQL style guides prefer LEFT JOIN for readability (main table always listed first), which is why RIGHT JOIN appears far less often in real codebases despite being fully valid SQL.

4. What is a FULL OUTER JOIN? Intermediate

Example:

SELECT o.order_id, c.customer_name
FROM orders o
FULL OUTER JOIN customers c ON o.customer_id = c.customer_id;

Output example: Returns every order (matched or not) and every customer (matched or not) — unmatched rows on either side show NULL for the other table's columns.

Common mistake: MySQL doesn't support FULL OUTER JOIN natively — it must be simulated with a LEFT JOIN UNION RIGHT JOIN combination. Mentioning this shows awareness of real cross-database differences, not just textbook syntax.

5. What is a SELF JOIN, and what's a real use case? Intermediate

Example:

SELECT e.first_name AS employee, m.first_name AS manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.employee_id;

Explanation: A self join joins a table to itself, using table aliases (e and m) to treat it as two logical tables — here, finding each employee's manager, since both employees and managers live in the same employees table.

Real interview use case: Building an org-chart-style report, or finding employees who earn more than their own manager: add WHERE e.salary > m.salary.

6. What is a CROSS JOIN? Intermediate

Example:

SELECT p.product_name, s.size_label
FROM products p
CROSS JOIN sizes s;

Explanation: A CROSS JOIN returns the Cartesian product — every row from the first table paired with every row from the second, with no join condition. If products has 10 rows and sizes has 4, the result has 40 rows.

Real interview use case: Generating all possible product-size combinations for an inventory template, before actual stock data exists for each combination.

Common mistake: Accidentally producing a CROSS JOIN by forgetting the ON condition in a regular JOIN — this is one of the most common causes of an unexpectedly huge, duplicated result set in real query-writing.

7. What is the difference between UNION and UNION ALL? Beginner

Example:

SELECT customer_id FROM online_orders
UNION
SELECT customer_id FROM store_orders;

Explanation: UNION combines results from two queries and removes duplicate rows (requires the same number and compatible types of columns in both queries); UNION ALL keeps every row including duplicates, and is faster since it skips the deduplication step.

Real interview use case: Combining online and in-store customer lists into one unified list, using UNION specifically to avoid double-counting the same customer who appears in both.

8. Can you JOIN more than two tables in a single query? Beginner

Example:

SELECT o.order_id, c.customer_name, p.product_name
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id
JOIN order_details od ON o.order_id = od.order_id
JOIN products p ON od.product_id = p.product_id;

Explanation: Yes — each additional JOIN clause adds another table, and there's no fixed limit beyond performance considerations. Multi-table joins like this are extremely common in real reporting queries.

More join questions to be ready for:

Question Quick Answer
What is the difference between JOIN and JOIN ON vs WHERE-based joins (old-style)? Modern explicit JOIN ... ON syntax is preferred over listing tables in FROM separated by commas with join conditions in WHERE — the explicit syntax is clearer and separates join logic from filtering logic.
Can you JOIN on a condition other than equality? Yes — a non-equi join uses operators like >, <, or BETWEEN instead of =, e.g., joining a sales table to a date-range table for time-bucketed reporting.
What happens if you JOIN two tables without any ON condition and don't use CROSS JOIN explicitly? In most databases, an implicit comma join with no WHERE filter also produces a Cartesian product — the same risk as an accidental CROSS JOIN.
How do you find rows that exist in one table but not another using a JOIN? A LEFT JOIN combined with WHERE right_table.key IS NULL — often called an "anti-join" pattern.
Is a LEFT JOIN always slower than an INNER JOIN? Not inherently — performance depends more on indexing and table size than the join type itself, though LEFT JOIN's guarantee to keep unmatched rows can sometimes prevent certain optimizations.

🔗 Joins are the topic most worth over-practicing. Draw out what INNER, LEFT, and FULL OUTER actually keep and discard using two small sample tables until it's automatic — that repetition is exactly what closes the gap between "I understand joins" and "I can write one instantly."

GROUP BY, HAVING, ORDER BY, DISTINCT & Aggregate Functions

1. What is the difference between WHERE and HAVING? Beginner

Example:

SELECT department_id, AVG(salary) AS avg_salary
FROM employees
WHERE hire_date >= '2023-01-01'
GROUP BY department_id
HAVING AVG(salary) > 60000;

Explanation: WHERE filters individual rows before grouping happens (here, only employees hired since 2023); HAVING filters entire groups after aggregation (here, only departments whose average salary exceeds 60000). You can't use AVG(salary) > 60000 inside WHERE because aggregation hasn't happened yet at that point in query execution.

Common mistake: Trying to filter on an aggregate result using WHERE instead of HAVING, which throws an error in most databases.

2. What does GROUP BY actually do, mechanically? Beginner

Example:

SELECT region, SUM(order_amount) AS total_revenue
FROM orders
GROUP BY region;

Explanation: GROUP BY collapses all rows sharing the same value in the grouped column(s) into a single output row per group, so aggregate functions can calculate one result per group instead of per individual row.

Common mistake: Including a non-aggregated column in SELECT that isn't also in the GROUP BY clause — most databases either throw an error or (in MySQL's more permissive mode) return an arbitrary, unpredictable value for that column.

3. What are the main aggregate functions, and what does each do? Beginner

Example:

SELECT COUNT(*), SUM(salary), AVG(salary), MAX(salary), MIN(salary)
FROM employees;

Explanation: COUNT counts rows, SUM totals a numeric column, AVG averages it, MAX/MIN find the highest/lowest value — each collapses many rows into one summary value.

4. What is the difference between ORDER BY ASC and DESC, and what's the default? Beginner

Example: ORDER BY salary DESC sorts highest to lowest; ORDER BY salary ASC (or just ORDER BY salary, since ascending is the default) sorts lowest to highest.

Common mistake: Forgetting DESC when the intent was "highest first" — a very common source of a technically-correct-but-wrong-order live-test answer.

5. What does DISTINCT do, and how is it different from GROUP BY? Beginner

Example: SELECT DISTINCT city FROM customers; returns each unique city once.

Why it matters: DISTINCT and a GROUP BY on the same column with no aggregate function produce the same result — but GROUP BY is generally preferred when you also need an aggregate calculated per group, since that's what it's actually designed for; DISTINCT is meant purely for deduplication.

6. What does LIMIT (or TOP/FETCH FIRST) do, and how does the syntax differ across databases? Beginner

Example:

-- MySQL / PostgreSQL
SELECT * FROM orders ORDER BY amount DESC LIMIT 5;

-- SQL Server
SELECT TOP 5 * FROM orders ORDER BY amount DESC;

-- ANSI SQL Standard / Oracle / SQL Server (modern)
SELECT * FROM orders ORDER BY amount DESC FETCH FIRST 5 ROWS ONLY;

Why it matters: All three achieve the same goal — restricting the result to a specific number of rows — but the exact syntax differs by database. Knowing this cross-database difference is a strong E-E-A-T signal in an interview: it shows real, hands-on experience rather than knowledge from a single tutorial.

7. How would you find the top N records per group (e.g., top 3 highest-paid employees per department)? Advanced

Example:

SELECT * FROM (
  SELECT employee_id, department_id, salary,
    ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rn
  FROM employees
) ranked
WHERE rn <= 3;

Explanation: ROW_NUMBER() OVER (PARTITION BY ...) numbers rows within each department separately, restarting at 1 for each new department — filtering rn <= 3 then keeps only the top 3 per group. This is a very common "next level up" question after basic GROUP BY, since GROUP BY alone can't return more than one row per group.

More GROUP BY, HAVING & aggregate questions to be ready for:

Question Quick Answer
Can you GROUP BY multiple columns? Yes — GROUP BY region, product_category creates one group for each unique combination of the two columns.
Can you use HAVING without GROUP BY? Yes, though unusual — it treats the entire result set as a single group, functionally similar to a WHERE clause applied after an aggregate calculated over everything.
Does GROUP BY automatically sort results? No — GROUP BY only groups; if you want sorted output, you must add an explicit ORDER BY.
What is the difference between COUNT(column) and COUNT(DISTINCT column)? COUNT(column) counts all non-null values including duplicates; COUNT(DISTINCT column) counts only unique non-null values.
Can aggregate functions be nested directly, like SUM(AVG(x))? No — SQL doesn't allow directly nesting aggregate functions in the same SELECT; you'd need a subquery to calculate the inner aggregate first.

CASE WHEN & Conditional Logic

1. How does CASE WHEN work in SQL? Beginner

Example:

SELECT customer_id,
  CASE
    WHEN total_spent > 50000 THEN 'High Value'
    WHEN total_spent BETWEEN 10000 AND 50000 THEN 'Mid Value'
    ELSE 'Low Value'
  END AS customer_segment
FROM customer_totals;

Explanation: CASE WHEN works like an IF-ELSE chain inside SQL — it evaluates conditions top to bottom and returns the value tied to the first matching condition, falling back to ELSE if none match.

Common mistake: Forgetting that condition order matters — since CASE WHEN stops at the first TRUE match, a broader condition placed before a narrower one can silently swallow rows meant for the narrower branch.

2. Can CASE WHEN be used inside an aggregate function? Intermediate

Example:

SELECT
  SUM(CASE WHEN status = 'Completed' THEN amount ELSE 0 END) AS completed_revenue,
  SUM(CASE WHEN status = 'Cancelled' THEN amount ELSE 0 END) AS cancelled_revenue
FROM orders;

Why it matters: This is one of the most useful, frequently tested SQL patterns — conditional aggregation lets you calculate multiple filtered totals in a single query pass, instead of writing separate queries or relying on multiple SUMIFS-style calls the way you might in Excel.

Real interview use case: Building a single-row summary report ("pivoted" by status) without needing a full PIVOT operation, which many databases don't support natively.

3. What is the difference between a simple CASE and a searched CASE? Advanced

Example:

-- Simple CASE (compares one expression to values)
SELECT CASE department_id WHEN 1 THEN 'Sales' WHEN 2 THEN 'HR' ELSE 'Other' END FROM employees;

-- Searched CASE (evaluates independent conditions)
SELECT CASE WHEN salary > 100000 THEN 'Senior' WHEN salary > 50000 THEN 'Mid' ELSE 'Junior' END FROM employees;

Explanation: A simple CASE compares one expression against a list of exact values; a searched CASE evaluates independent boolean conditions, which can each reference different columns — searched CASE is more flexible and far more commonly used in practice.

More CASE WHEN questions to be ready for:

Question Quick Answer
Can you use CASE WHEN inside a WHERE clause? Yes, though it's often cleaner to rewrite the logic as OR conditions — CASE in WHERE is valid but sometimes signals the query could be simplified.
Can CASE WHEN be used inside ORDER BY? Yes — useful for custom sort orders that don't follow simple alphabetical or numeric order (e.g., sorting "High," "Medium," "Low" in that specific priority order).
What does COALESCE do differently from CASE WHEN column IS NULL? COALESCE is a more concise, purpose-built function for the specific "return the first non-null value" pattern, though a CASE statement can achieve the same result.

Subqueries & Correlated Subqueries

1. What is a subquery, and where can it be used? Beginner

Example:

SELECT customer_id, total_spent
FROM customer_totals
WHERE total_spent > (SELECT AVG(total_spent) FROM customer_totals);

Explanation: A subquery is a query nested inside another query, used to compute an intermediate result. Subqueries can appear in the SELECT list, FROM clause, or WHERE/HAVING clause, depending on what you need.

Real interview use case: Flagging above-average spenders for a retention campaign — the subquery calculates the overall average first, and the outer query compares each customer's total against it.

2. What is the difference between a subquery and a JOIN, and when would you prefer one over the other? Intermediate

Answer: A subquery computes a separate, often single-value result used for filtering or comparison; a JOIN combines rows from two tables based on a matching condition, returning combined columns from both. When you need columns from both tables in the final output, JOIN is usually the right tool; when you only need to filter based on a condition from another table (like "above the average"), a subquery is often simpler and clearer.

3. What is a correlated subquery, and how is it different from a regular subquery? Advanced

Example:

SELECT e1.employee_id, e1.salary, e1.department_id
FROM employees e1
WHERE e1.salary > (
  SELECT AVG(e2.salary) FROM employees e2 WHERE e2.department_id = e1.department_id
);

Explanation: A correlated subquery references a column from the outer query (e1.department_id) and is re-evaluated once for every row the outer query processes — unlike a regular subquery, which runs once and reuses the same result for the whole outer query. This example finds employees earning above their own department's average, not the company-wide average.

Why it matters: This is a genuinely important distinction interviewers probe specifically — understanding why the subquery re-runs per row (and the performance implications of that) signals real depth beyond copy-pasted syntax.

Common mistake: Confusing a correlated subquery's per-row re-evaluation with a regular subquery's one-time execution, leading to wrong assumptions about what the query actually computes or how it performs on large tables.

4. What is the difference between IN and EXISTS with a subquery? Advanced

Example:

-- Using IN
SELECT * FROM customers WHERE customer_id IN (SELECT customer_id FROM orders WHERE amount > 5000);

-- Using EXISTS
SELECT * FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id AND o.amount > 5000);

Explanation: IN checks if a value matches any value in a subquery's result list; EXISTS checks only whether the correlated subquery returns any row at all, stopping as soon as it finds one match. EXISTS is often faster on large datasets specifically because it can short-circuit, while IN typically needs the full list materialized first.

5. What is a scalar subquery, and where is it commonly used? Intermediate

Example:

SELECT employee_id, salary, (SELECT AVG(salary) FROM employees) AS company_avg
FROM employees;

Explanation: A scalar subquery returns exactly one single value (one row, one column) and can be used anywhere a single value is expected — including directly inside the SELECT list, as shown here, to compare each row against a company-wide figure.

More subquery questions to be ready for:

Question Quick Answer
Can a subquery return multiple columns? Yes, when used in the FROM clause (as a derived table) — but subqueries used with =, IN comparisons against a single column must return only one column.
What is a derived table? A subquery used in the FROM clause, treated as a temporary, named table for the duration of that query.
Can you use ORDER BY inside a subquery? Generally not meaningful unless paired with LIMIT/TOP inside the subquery itself, since the outer query's own ordering otherwise takes precedence on the final result.
What is the difference between ANY, ALL, and IN with subqueries? IN checks for any exact match; ANY/SOME returns TRUE if the condition holds for at least one subquery row; ALL requires the condition to hold for every subquery row.
Can a subquery reference the outer query's table without being correlated? No — if it references an outer-query column, it is by definition a correlated subquery.

CTEs (Common Table Expressions)

1. What is a CTE, and why use it instead of a subquery? Intermediate

Example:

WITH customer_totals AS (
  SELECT customer_id, SUM(order_amount) AS total_spent
  FROM orders
  GROUP BY customer_id
)
SELECT * FROM customer_totals
WHERE total_spent > (SELECT AVG(total_spent) FROM customer_totals);

Explanation: A CTE (defined with WITH ... AS) creates a named, temporary result set that can be referenced multiple times within the same query — as shown here, customer_totals is used twice without needing to repeat the underlying aggregation logic, which a plain nested subquery would require.

Why it matters: CTEs dramatically improve readability for multi-step logic, letting you name each intermediate step clearly instead of building deeply nested, hard-to-read subqueries — a strong signal of writing production-quality, maintainable SQL.

2. What is a recursive CTE, and what's a real use case? Advanced

Example:

WITH RECURSIVE org_chart AS (
  SELECT employee_id, first_name, manager_id, 1 AS level
  FROM employees WHERE manager_id IS NULL

  UNION ALL

  SELECT e.employee_id, e.first_name, e.manager_id, oc.level + 1
  FROM employees e
  JOIN org_chart oc ON e.manager_id = oc.employee_id
)
SELECT * FROM org_chart;

Explanation: A recursive CTE references itself, repeatedly building on its own previous result — the base case (top-level employees with no manager) starts it, and the recursive part joins back to find each next level down, until no more matches are found.

Real interview use case: Traversing a hierarchical structure like an org chart, a category tree, or a bill-of-materials — any data where each row can have a "parent" pointing to another row in the same table, at unknown depth.

3. Can you define multiple CTEs in a single query? Intermediate

Example:

WITH monthly_sales AS (
  SELECT DATE_TRUNC('month', order_date) AS month, SUM(amount) AS total
  FROM orders GROUP BY 1
),
avg_monthly AS (
  SELECT AVG(total) AS avg_total FROM monthly_sales
)
SELECT * FROM monthly_sales, avg_monthly WHERE monthly_sales.total > avg_monthly.avg_total;

Explanation: Yes — multiple CTEs are separated by commas within one WITH clause, and later CTEs can reference earlier ones, letting you build a clean, sequential pipeline of intermediate steps.

More CTE questions to be ready for:

Question Quick Answer
Is a CTE stored permanently like a table? No — a CTE exists only for the duration of the single query it's defined in and isn't stored or reusable across separate queries.
Do CTEs improve query performance? Not inherently — they primarily improve readability; some databases materialize CTEs (compute once, reuse), others may re-evaluate them, so performance impact varies by database engine.
What's the difference between a CTE and a temporary table? A CTE is scoped to a single query and discarded after; a temporary table persists for the duration of a session (or transaction) and can be queried multiple times across separate statements.
Can a CTE call another CTE defined after it in the same WITH clause? No — CTEs can only reference CTEs defined earlier in the same WITH clause, not ones defined later.

Window Functions

Window functions are the most consistently tested "advanced" topic in modern SQL interviews — expect at least one question here in almost any technical round beyond pure entry-level screening.

1. What is a window function, and how is it fundamentally different from GROUP BY? Intermediate

Example:

SELECT employee_id, department_id, salary,
  AVG(salary) OVER (PARTITION BY department_id) AS dept_avg_salary
FROM employees;

Explanation: A window function calculates a value across a set of related rows (the "window," defined by OVER() and optionally PARTITION BY) but returns a result for every individual row, unlike GROUP BY which collapses rows into one row per group. Here, every employee keeps their own row while also seeing their department's average.

Why it matters: This distinction — "aggregates without collapsing rows" — is exactly what interviewers are checking for when they ask "what's the difference between a window function and GROUP BY?"

2. What does ROW_NUMBER() do, and what's a real use case? Intermediate

Example:

WITH ranked AS (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY customer_email ORDER BY order_date DESC) AS rn
  FROM customers
)
SELECT * FROM ranked WHERE rn = 1;

Explanation: ROW_NUMBER() assigns a unique, strictly sequential number within each partition (here, each email address); keeping only rn = 1 keeps just the most recent record per customer.

Real interview use case: Deduplicating a customer table where the same person signed up multiple times with slightly different records — one of the single most common real-world window function applications.

3. What is the difference between RANK() and DENSE_RANK()? Intermediate

Example:

SELECT sales_rep, total_sales,
  RANK() OVER (ORDER BY total_sales DESC) AS rank_val,
  DENSE_RANK() OVER (ORDER BY total_sales DESC) AS dense_rank_val
FROM rep_sales;

Output example: For sales of 500, 500, 400: RANK gives 1, 1, 3 (skips 2 after the tie); DENSE_RANK gives 1, 1, 2 (no skip).

Explanation: RANK() skips subsequent rank numbers after a tie; DENSE_RANK() doesn't skip — the difference only shows up when ties exist. ROW_NUMBER(), by contrast, never ties — it always assigns a unique number even for identical values, breaking ties arbitrarily based on the underlying row order.

Real interview use case: Ranking sales reps for a leaderboard, where how ties are handled directly affects bonus eligibility cutoffs — a very common follow-up: "which of the three would you use for a top-10 bonus list, and why?"

4. What do LEAD() and LAG() do? Advanced

Example:

SELECT month, monthly_sales,
  LAG(monthly_sales) OVER (ORDER BY month) AS previous_month_sales,
  monthly_sales - LAG(monthly_sales) OVER (ORDER BY month) AS mom_change
FROM sales_summary;

Explanation: LAG() accesses a previous row's value within the current window/partition; LEAD() accesses a following row's value — both without needing a self-join. This example calculates month-over-month change directly.

Real interview use case: Month-over-month or year-over-year comparison reporting — one of the most frequently asked practical window-function coding problems.

5. What does NTILE() do? Advanced

Example: NTILE(4) OVER (ORDER BY total_spent DESC) divides customers into 4 roughly equal groups (quartiles) based on total_spent, labeling each row 1 through 4.

Real interview use case: Segmenting customers into spending tiers (e.g., top 25%, next 25%, etc.) for a targeted marketing campaign, without manually calculating percentile boundaries.

6. How do you calculate a running total using a window function? Advanced

Example:

SELECT order_date, amount,
  SUM(amount) OVER (ORDER BY order_date) AS running_total
FROM orders;

Explanation: A window function with SUM() OVER (ORDER BY ...) and no explicit frame clause defaults to a running (cumulative) total up to and including the current row, rather than the grand total across all rows.

Real interview use case: Tracking cumulative revenue progress toward an annual target on a live dashboard — a very common business reporting need.

7. What is a window frame, and what does ROWS BETWEEN control? Advanced

Example:

SELECT order_date, amount,
  AVG(amount) OVER (ORDER BY order_date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS moving_avg_3day
FROM orders;

Explanation: The frame clause (ROWS BETWEEN ... AND ...) explicitly defines exactly which rows within the partition are included in each row's calculation — here, a 3-row moving average using the current row and the two before it.

Why it matters: This is a senior-level nuance question — most candidates know window functions exist but haven't explored controlling the frame explicitly, so demonstrating this signals real depth.

More window function questions to be ready for:

Question Quick Answer
Can you use a window function in a WHERE clause directly? No — window functions are evaluated after WHERE in the logical query order, so you must wrap the query in a subquery or CTE and filter on the outer layer instead.
What does PARTITION BY do differently from GROUP BY? PARTITION BY defines separate windows for a window function calculation without collapsing rows; GROUP BY collapses rows into groups directly.
Can multiple window functions be used in the same SELECT statement? Yes — you can combine ROW_NUMBER, LAG, and a running SUM in the same query, each with its own OVER() clause if needed.
What is the default frame when ORDER BY is used inside OVER() without an explicit ROWS/RANGE clause? RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW — effectively a running calculation up to the current row.
Are window functions supported in every database? Most modern databases (PostgreSQL, MySQL 8+, SQL Server, Oracle) fully support them — older MySQL versions (before 8.0) notably did not.

📊 Window functions are the topic that most separates a "knows the basics" candidate from a genuinely strong one in 2026 interviews. Drilling ROW_NUMBER, RANK, and LAG on real practice problems — not just reading syntax — is exactly the kind of hands-on repetition available on SQLabHub.com.

NULL-Handling, Date, String & Mathematical Functions

1. What does COALESCE do? Beginner

Example: SELECT COALESCE(phone, email, 'No Contact Info') FROM customers; returns phone if it's not NULL, otherwise email, otherwise falls back to the literal text.

Explanation: COALESCE returns the first non-NULL value from a list of expressions, evaluated left to right — commonly used to substitute a sensible default for missing data.

2. What does NULLIF do, and how is it different from COALESCE? Intermediate

Example: SELECT NULLIF(revenue, 0) FROM sales; returns NULL if revenue equals 0, otherwise returns revenue itself.

Real interview use case: Preventing a divide-by-zero error: SELECT revenue / NULLIF(units_sold, 0) FROM sales; — if units_sold is 0, the division returns NULL instead of throwing an error.

3. What is the difference between COALESCE, IFNULL, and ISNULL across databases? Intermediate

Answer: COALESCE is the ANSI-standard function, supported everywhere, and can accept any number of arguments. IFNULL (MySQL) and ISNULL (SQL Server) are database-specific equivalents that accept exactly two arguments. Using COALESCE by default is generally the safer, more portable choice across database engines.

4. What are the most useful date functions, and how do their names differ by database? Intermediate

Example:

-- Difference between two dates
SELECT DATEDIFF(order_date, signup_date) FROM customers;      -- MySQL
SELECT order_date - signup_date FROM customers;               -- PostgreSQL (returns integer days)
SELECT DATEDIFF(day, signup_date, order_date) FROM customers; -- SQL Server

-- Current date/time
SELECT CURRENT_DATE, CURRENT_TIMESTAMP;                        -- ANSI standard, widely supported

Why it matters: Date function syntax is one of the areas with the most cross-database variation — being aware that DATEDIFF's argument order and behavior differs between MySQL and SQL Server (and that PostgreSQL handles date subtraction natively) is a genuine, practical E-E-A-T signal.

5. How do you extract the year, month, or day from a date column? Beginner

Example:

SELECT EXTRACT(YEAR FROM order_date) AS order_year FROM orders;   -- ANSI / PostgreSQL
SELECT YEAR(order_date) AS order_year FROM orders;                -- MySQL / SQL Server shorthand

Real interview use case: Grouping transaction data by year or month for a trend report: GROUP BY EXTRACT(YEAR FROM order_date), EXTRACT(MONTH FROM order_date).

6. What are the most useful string functions? Beginner

Example:

SELECT UPPER(first_name), LOWER(last_name), LENGTH(email),
  CONCAT(first_name, ' ', last_name) AS full_name,
  SUBSTRING(email, 1, POSITION('@' IN email) - 1) AS username
FROM employees;

Explanation: UPPER/LOWER change casing, LENGTH returns character count, CONCAT joins strings, and SUBSTRING extracts part of a string — here combined with POSITION to dynamically extract the username portion of an email address.

7. What does TRIM do, and why does it matter for data quality? Beginner

Example: SELECT TRIM(city) FROM customers; removes leading and trailing whitespace.

Real interview use case: Data imported from external systems or user forms frequently has accidental leading/trailing spaces ("Delhi " vs "Delhi"), which silently breaks GROUP BY and JOIN matching unless cleaned first — a very common root cause when live-test results look "almost right" but not quite.

8. What are the most useful mathematical functions? Beginner

Example:

SELECT ROUND(price, 2), CEIL(price), FLOOR(price), ABS(profit), POWER(base, 2), MOD(order_id, 2)
FROM products;

Explanation: ROUND rounds to a specified decimal precision, CEIL/FLOOR round up/down to the nearest integer, ABS returns absolute value, POWER raises to an exponent, and MOD returns the remainder of division — often used to split data into even/odd groups.

More NULL, date, string & math function questions to be ready for:

Question Quick Answer
What does REPLACE do? Substitutes all occurrences of one substring with another within a text value — REPLACE(phone,'-','') to strip formatting characters.
How do you convert a string to a date? Using CAST or CONVERT (CAST('2026-01-15' AS DATE)), or database-specific functions like STR_TO_DATE in MySQL.
What does DATE_TRUNC do in PostgreSQL? Rounds a timestamp down to a specified precision (e.g., 'month', 'day'), commonly used to group timestamps into clean reporting periods.
What is the difference between CAST and CONVERT? CAST is the ANSI-standard, widely portable way to change data types; CONVERT is largely SQL-Server-specific and offers additional formatting-style options.
How would you check if a string contains a specific substring? Using LIKE with wildcards (WHERE email LIKE '%gmail.com'), or a function like POSITION/CHARINDEX/INSTR depending on the database.

Views & Indexes

1. What is a View, and what's its main benefit? Beginner

Example:

CREATE VIEW high_value_customers AS
SELECT customer_id, customer_name, SUM(amount) AS total_spent
FROM customers c JOIN orders o ON c.customer_id = o.customer_id
GROUP BY customer_id, customer_name
HAVING SUM(amount) > 50000;

SELECT * FROM high_value_customers WHERE customer_name LIKE 'A%';

Explanation: A View is a saved, virtual table based on a stored SQL query — it doesn't store data itself, just the query definition, and re-runs that query fresh each time it's referenced. It's used to simplify repeated complex queries, and to restrict which columns/rows certain users can see.

2. What is the difference between a View and a Materialized View? Advanced

Answer: A standard View re-executes its underlying query every time it's accessed, always reflecting live data. A Materialized View physically stores the query's result set, refreshed on a schedule or manually — trading some data freshness for significantly faster read performance on expensive queries.

3. What is an index, and why does it speed up queries? Intermediate

Example: CREATE INDEX idx_customer_email ON customers(email);

Explanation: An index is a separate data structure (typically a B-tree) that stores a sorted, fast-lookup path to rows based on the indexed column's values — similar in concept to a book's index letting you jump straight to a topic instead of reading every page. Without an index, the database must scan every row (a full table scan) to find matches.

Why it matters: Interviewers use this question to check whether you understand the trade-off, not just the benefit — indexes speed up reads but slightly slow down writes (INSERT/UPDATE/DELETE), since the index itself must be updated too, and they consume additional storage.

4. What is the difference between a clustered index and a non-clustered index? Advanced

Answer: A clustered index physically sorts and stores the table's actual data rows in the order of the indexed column — a table can have only one (since data can only be physically sorted one way). A non-clustered index is a separate structure that stores pointers back to the actual data rows — a table can have several.

5. When would adding an index actually hurt performance? Advanced

Answer: On tables with very heavy write activity (frequent INSERT/UPDATE/DELETE), too many indexes slow down every write since each index must also be updated — and indexing a column with very low cardinality (few distinct values, like a boolean "is_active" flag) rarely helps read performance enough to justify the write cost.

More views & indexes questions to be ready for:

Question Quick Answer
Can you update data through a View? Sometimes — simple Views based on a single table without aggregation are usually updatable; Views involving JOINs or GROUP BY generally are not.
What is a composite index? An index built on multiple columns together, most effective when queries commonly filter or sort on that same combination of columns.
What is index cardinality? The number of unique values in an indexed column — higher cardinality generally makes an index more selective and useful.
What is a covering index? An index that includes every column a specific query needs, letting the database satisfy the query entirely from the index without touching the actual table data.
Does creating an index guarantee a query will use it? No — the query optimizer decides whether using an index is actually faster than a full table scan for a given query and data distribution; sometimes it chooses not to use an available index.

Transactions & ACID Properties

1. What is a transaction in SQL? Intermediate

Example:

BEGIN TRANSACTION;
UPDATE accounts SET balance = balance - 5000 WHERE account_id = 1;
UPDATE accounts SET balance = balance + 5000 WHERE account_id = 2;
COMMIT;

Explanation: A transaction groups multiple SQL statements into a single, all-or-nothing unit of work — either every statement in the transaction succeeds and is saved together (COMMIT), or if something fails partway through, the entire transaction can be undone (ROLLBACK), leaving no partial changes.

2. What are the ACID properties, explained with a real example? Intermediate

Answer:

Why it matters: This example-driven explanation is far stronger than reciting the four terms — interviewers specifically probe whether you can connect ACID to a concrete scenario, not just define it.

3. What are the different transaction isolation levels? Advanced

Answer: From least to most strict: Read Uncommitted (can see other transactions' uncommitted changes — "dirty reads"), Read Committed (only sees committed data, the common default in many databases), Repeatable Read (guarantees the same query returns the same result throughout the transaction), and Serializable (the strictest — transactions behave as if executed one at a time, fully isolated).

Real interview use case: Rarely asked in full depth for fresher roles, but knowing that stricter isolation trades off against concurrency performance is a valuable, senior-signaling point to raise if the topic comes up.

4. What is a deadlock, and how does a database typically handle it? Advanced

Answer: A deadlock occurs when two transactions each hold a lock the other needs, and both wait indefinitely for the other to release it. Most databases automatically detect this situation and terminate (roll back) one of the transactions to break the cycle, returning an error to the affected application so it can retry.

More transaction questions to be ready for:

Question Quick Answer
What is a dirty read? Reading uncommitted data from another transaction that might later be rolled back — a risk specific to the Read Uncommitted isolation level.
What is the difference between optimistic and pessimistic locking? Pessimistic locking blocks other transactions from touching a row until the current one finishes; optimistic locking allows concurrent access but checks for conflicts before committing.
Can a SELECT statement be part of a transaction? Yes — while SELECT alone doesn't modify data, it can be included within a transaction, particularly relevant for consistent reads under stricter isolation levels.
What does autocommit mode mean? By default, many databases commit each individual statement immediately unless you explicitly start a transaction — autocommit mode governs this default behavior.

Stored Procedures, Triggers & Performance Optimization

1. What is a stored procedure? Intermediate

Example:

CREATE PROCEDURE GetMonthlySales (IN p_month INT)
BEGIN
  SELECT region, SUM(order_amount) AS total_sales
  FROM orders
  WHERE MONTH(order_date) = p_month
  GROUP BY region;
END;

CALL GetMonthlySales(7);

Explanation: A stored procedure is a saved, reusable block of SQL code that can accept parameters and be executed with a single call — here, calling GetMonthlySales(7) returns July's regional sales without rewriting the underlying query.

Real interview use case: Automating a recurring report requested regularly by different stakeholders, reducing repeated manual query-writing and centralizing the logic in one maintainable place.

2. What is a trigger, and what's a real use case? Advanced

Example:

CREATE TRIGGER update_stock AFTER INSERT ON order_details
FOR EACH ROW
BEGIN
  UPDATE products SET stock_quantity = stock_quantity - NEW.quantity
  WHERE product_id = NEW.product_id;
END;

Explanation: A trigger is a block of code that automatically executes in response to a specific event (INSERT, UPDATE, or DELETE) on a table — here, automatically reducing stock quantity whenever a new order line is inserted, without the application needing to handle that logic separately.

Common mistake: Overusing triggers for complex business logic that would be clearer and more maintainable as explicit application code — triggers can make a system's behavior harder to trace, since they execute silently in the background.

3. What is a function vs a stored procedure in SQL? Advanced

Answer: A function must return a single value (or table) and can be used directly inside a SELECT statement or expression; a stored procedure doesn't have to return a value, can perform broader actions (like multiple INSERTs/UPDATEs), and is called explicitly rather than embedded in another query.

4. How would you optimize a slow SQL query? Advanced

Answer: A structured approach: check whether relevant columns (used in WHERE, JOIN, and ORDER BY) are indexed; review the execution plan to find full table scans or expensive operations; avoid SELECT * when only specific columns are needed; rewrite correlated subqueries as JOINs where possible, since they often perform better; and ensure filtering happens as early as possible in the query rather than after unnecessary joins or aggregations.

5. What is an execution plan, and how do you read one? Advanced

Answer: An execution plan (viewed via EXPLAIN in MySQL/PostgreSQL, or SET SHOWPLAN_ALL in SQL Server) shows exactly how the database intends to execute a query — which indexes it will use, the join order, and the estimated cost of each step. Reading one means looking for full table scans on large tables, high estimated row counts feeding into expensive operations, and joins happening in a suboptimal order.

Real interview use case: "This report takes 30 seconds to run — how would you investigate?" — Answer: start with EXPLAIN on the query to identify the actual bottleneck before guessing at a fix.

More stored procedures, triggers & optimization questions to be ready for:

Question Quick Answer
What is the difference between a trigger and a stored procedure? A trigger fires automatically in response to a table event; a stored procedure only runs when explicitly called.
What are SQL best practices for writing readable queries? Use meaningful table aliases, format multi-line queries consistently, avoid SELECT *, use CTEs over deeply nested subqueries, and comment non-obvious business logic.
Why is SELECT * generally discouraged in production queries? It retrieves unnecessary columns (wasting bandwidth and memory), can break if the table structure changes, and makes it unclear which columns the query actually depends on.
What is query caching? Some databases can cache the result of a repeated identical query to avoid re-executing it, though modern systems increasingly rely on more sophisticated buffer/plan caching instead of literal result caching.
How would you find and remove duplicate rows that have no unique identifier? Use ROW_NUMBER() OVER (PARTITION BY the duplicate-defining columns ORDER BY some tiebreaker), then delete all rows where the row number is greater than 1.

⚙️ Optimization and execution-plan questions are where SQL interviews shift from "do you know the syntax" to "have you actually worked with real, slow, production-scale queries" — exactly the kind of practical depth the DataVix Data Analyst course builds through real project work.

50 SQL Coding Questions (Easy, Medium, Hard)

These 50 problems mirror what you'll actually be asked to solve live — in a real query editor, against real (if simplified) tables. They reuse three small shared schemas so you can focus entirely on the logic.

Schema A — HR: employees(employee_id, first_name, department_id, manager_id, salary, hire_date), departments(department_id, department_name)

Schema B — Sales: orders(order_id, customer_id, order_date, amount, status), customers(customer_id, customer_name, city, signup_date)

Schema C — Retail: products(product_id, product_name, category, price), order_details(order_id, product_id, quantity)

Easy (1-20)

  1. Get all employees hired after Jan 1, 2024.

    SELECT * FROM employees WHERE hire_date > '2024-01-01';
    
  2. Find all customers from Mumbai or Delhi.

    SELECT * FROM customers WHERE city IN ('Mumbai', 'Delhi');
    
  3. Get the top 5 highest-paid employees.

    SELECT * FROM employees ORDER BY salary DESC LIMIT 5;
    
  4. Count the total number of orders.

    SELECT COUNT(*) AS total_orders FROM orders;
    
  5. Find all products priced above ₹1000.

    SELECT * FROM products WHERE price > 1000;
    
  6. List all distinct cities customers are from.

    SELECT DISTINCT city FROM customers;
    
  7. Find the average order amount.

    SELECT AVG(amount) AS avg_order_amount FROM orders;
    
  8. Get employees whose names start with 'A'.

    SELECT * FROM employees WHERE first_name LIKE 'A%';
    
  9. Find orders placed in the last 30 days.

    SELECT * FROM orders WHERE order_date >= CURRENT_DATE - INTERVAL '30 days';
    -- MySQL: WHERE order_date >= CURDATE() - INTERVAL 30 DAY
    
  10. Get all departments with no employees assigned.

    SELECT d.* FROM departments d
    LEFT JOIN employees e ON d.department_id = e.department_id
    WHERE e.employee_id IS NULL;
    
  11. Find the total revenue by product category.

    SELECT p.category, SUM(od.quantity * p.price) AS total_revenue
    FROM order_details od JOIN products p ON od.product_id = p.product_id
    GROUP BY p.category;
    
  12. Find employees earning more than ₹75,000.

    SELECT * FROM employees WHERE salary > 75000;
    
  13. Get the most recent order date.

    SELECT MAX(order_date) AS latest_order FROM orders;
    
  14. Count how many employees are in each department.

    SELECT department_id, COUNT(*) AS headcount FROM employees GROUP BY department_id;
    
  15. Find customers who signed up in 2025.

    SELECT * FROM customers WHERE EXTRACT(YEAR FROM signup_date) = 2025;
    
  16. Get all cancelled orders.

    SELECT * FROM orders WHERE status = 'Cancelled';
    
  17. Find products with no category assigned (NULL).

    SELECT * FROM products WHERE category IS NULL;
    
  18. Sort employees by department, then by salary descending within each department.

    SELECT * FROM employees ORDER BY department_id, salary DESC;
    
  19. Get the shortest and longest product name.

    SELECT MIN(LENGTH(product_name)), MAX(LENGTH(product_name)) FROM products;
    
  20. Find all orders with an amount between ₹1000 and ₹5000.

    SELECT * FROM orders WHERE amount BETWEEN 1000 AND 5000;
    

Medium (21-40)

  1. Find the second-highest salary in the employees table.

    SELECT MAX(salary) AS second_highest FROM employees
    WHERE salary < (SELECT MAX(salary) FROM employees);
    

    Alternative (handles ties correctly using DENSE_RANK):

    SELECT salary FROM (
      SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk FROM employees
    ) t WHERE rnk = 2;
    

    Why the alternative matters: The first approach silently fails if you need the "second-highest distinct salary" but there are duplicate top salaries — DENSE_RANK handles this correctly by design.

  2. Find the Nth highest salary (parameterized), e.g., the 3rd highest.

    SELECT DISTINCT salary FROM employees ORDER BY salary DESC LIMIT 1 OFFSET 2;
    

    Optimization tip: For large tables, a window function (DENSE_RANK) approach is generally more efficient and more portable across databases than relying on OFFSET.

  3. Find employees who earn more than their manager.

    SELECT e.first_name AS employee, e.salary, m.salary AS manager_salary
    FROM employees e JOIN employees m ON e.manager_id = m.employee_id
    WHERE e.salary > m.salary;
    
  4. Find duplicate customer records based on email.

    SELECT email, COUNT(*) FROM customers GROUP BY email HAVING COUNT(*) > 1;
    
  5. Delete duplicate rows, keeping only the first occurrence per email.

    WITH ranked AS (
      SELECT customer_id, ROW_NUMBER() OVER (PARTITION BY email ORDER BY customer_id) AS rn
      FROM customers
    )
    DELETE FROM customers WHERE customer_id IN (SELECT customer_id FROM ranked WHERE rn > 1);
    
  6. Find the department with the highest total salary payout.

    SELECT department_id, SUM(salary) AS total_payout
    FROM employees GROUP BY department_id
    ORDER BY total_payout DESC LIMIT 1;
    
  7. Calculate month-over-month revenue growth.

    WITH monthly AS (
      SELECT DATE_TRUNC('month', order_date) AS month, SUM(amount) AS revenue
      FROM orders GROUP BY 1
    )
    SELECT month, revenue,
      revenue - LAG(revenue) OVER (ORDER BY month) AS mom_change,
      ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY month)) / LAG(revenue) OVER (ORDER BY month), 2) AS mom_pct
    FROM monthly;
    
  8. Find customers who have never placed an order.

    SELECT c.* FROM customers c
    LEFT JOIN orders o ON c.customer_id = o.customer_id
    WHERE o.order_id IS NULL;
    

    Alternative using NOT EXISTS:

    SELECT * FROM customers c
    WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id);
    
  9. Find the top 3 best-selling products by quantity.

    SELECT p.product_name, SUM(od.quantity) AS total_qty
    FROM order_details od JOIN products p ON od.product_id = p.product_id
    GROUP BY p.product_name ORDER BY total_qty DESC LIMIT 3;
    
  10. Find employees hired in the same month as their manager.

    SELECT e.first_name FROM employees e
    JOIN employees m ON e.manager_id = m.employee_id
    WHERE EXTRACT(MONTH FROM e.hire_date) = EXTRACT(MONTH FROM m.hire_date);
    
  11. Calculate a running total of daily revenue.

    SELECT order_date, SUM(amount) AS daily_revenue,
      SUM(SUM(amount)) OVER (ORDER BY order_date) AS running_total
    FROM orders GROUP BY order_date ORDER BY order_date;
    
  12. Find customers whose total spend is above the overall average.

    WITH totals AS (SELECT customer_id, SUM(amount) AS total_spent FROM orders GROUP BY customer_id)
    SELECT * FROM totals WHERE total_spent > (SELECT AVG(total_spent) FROM totals);
    
  13. Get the first order date for each customer.

    SELECT customer_id, MIN(order_date) AS first_order FROM orders GROUP BY customer_id;
    
  14. Find products that have never been ordered.

    SELECT p.* FROM products p
    LEFT JOIN order_details od ON p.product_id = od.product_id
    WHERE od.product_id IS NULL;
    
  15. Rank employees within each department by salary.

    SELECT employee_id, department_id, salary,
      RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS dept_rank
    FROM employees;
    
  16. Find orders placed on a weekend.

    SELECT * FROM orders WHERE EXTRACT(DOW FROM order_date) IN (0, 6);
    -- SQL Server: WHERE DATEPART(WEEKDAY, order_date) IN (1, 7)
    
  17. Calculate each customer's rank by total spend, using DENSE_RANK.

    WITH totals AS (SELECT customer_id, SUM(amount) AS total_spent FROM orders GROUP BY customer_id)
    SELECT *, DENSE_RANK() OVER (ORDER BY total_spent DESC) AS spend_rank FROM totals;
    
  18. Find the average time (in days) between signup and first order per customer.

    SELECT c.customer_id, MIN(o.order_date) - c.signup_date AS days_to_first_order
    FROM customers c JOIN orders o ON c.customer_id = o.customer_id
    GROUP BY c.customer_id, c.signup_date;
    
  19. Find pairs of products frequently bought together (in the same order).

    SELECT a.product_id AS product_a, b.product_id AS product_b, COUNT(*) AS times_together
    FROM order_details a JOIN order_details b
      ON a.order_id = b.order_id AND a.product_id < b.product_id
    GROUP BY a.product_id, b.product_id
    ORDER BY times_together DESC;
    

    Explanation: The a.product_id < b.product_id condition prevents matching a product with itself and avoids counting each pair twice (A-B and B-A separately).

  20. Find employees who manage more than 3 people.

    SELECT manager_id, COUNT(*) AS direct_reports
    FROM employees WHERE manager_id IS NOT NULL
    GROUP BY manager_id HAVING COUNT(*) > 3;
    

Hard (41-50)

  1. Find the longest streak of consecutive days a customer placed an order.

    WITH order_days AS (
      SELECT DISTINCT customer_id, order_date,
        order_date - (ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date))::int AS grp
      FROM orders
    )
    SELECT customer_id, COUNT(*) AS streak_length, MIN(order_date) AS streak_start
    FROM order_days GROUP BY customer_id, grp
    ORDER BY streak_length DESC LIMIT 1;
    

    Explanation: Subtracting a sequential row number from each date produces a constant value for any run of consecutive dates — a classic "gaps and islands" pattern, one of the most respected advanced SQL techniques to know.

  2. Find the median salary per department (without a built-in MEDIAN function).

    WITH ranked AS (
      SELECT department_id, salary,
        ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary) AS rn,
        COUNT(*) OVER (PARTITION BY department_id) AS cnt
      FROM employees
    )
    SELECT department_id, AVG(salary) AS median_salary
    FROM ranked
    WHERE rn IN (FLOOR((cnt+1)/2.0), CEIL((cnt+1)/2.0))
    GROUP BY department_id;
    
  3. Find customers who ordered every product in a specific category.

    WITH category_products AS (
      SELECT product_id FROM products WHERE category = 'Electronics'
    )
    SELECT o.customer_id
    FROM orders o JOIN order_details od ON o.order_id = od.order_id
    WHERE od.product_id IN (SELECT product_id FROM category_products)
    GROUP BY o.customer_id
    HAVING COUNT(DISTINCT od.product_id) = (SELECT COUNT(*) FROM category_products);
    

    Explanation: A classic "relational division" problem — matching the count of distinct products a customer ordered against the total count of products in the target category.

  4. Find the cumulative percentage contribution of each product to total revenue (for a Pareto/80-20 analysis).

    WITH product_revenue AS (
      SELECT p.product_name, SUM(od.quantity * p.price) AS revenue
      FROM order_details od JOIN products p ON od.product_id = p.product_id
      GROUP BY p.product_name
    )
    SELECT product_name, revenue,
      SUM(revenue) OVER (ORDER BY revenue DESC) * 100.0 / SUM(revenue) OVER () AS cumulative_pct
    FROM product_revenue ORDER BY revenue DESC;
    
  5. Find employees whose salary is in the top 10% company-wide.

    WITH ranked AS (
      SELECT *, NTILE(10) OVER (ORDER BY salary DESC) AS decile FROM employees
    )
    SELECT * FROM ranked WHERE decile = 1;
    
  6. Pivot monthly sales totals into columns (one column per month) using conditional aggregation.

    SELECT
      SUM(CASE WHEN EXTRACT(MONTH FROM order_date) = 1 THEN amount ELSE 0 END) AS jan,
      SUM(CASE WHEN EXTRACT(MONTH FROM order_date) = 2 THEN amount ELSE 0 END) AS feb,
      SUM(CASE WHEN EXTRACT(MONTH FROM order_date) = 3 THEN amount ELSE 0 END) AS mar
    FROM orders WHERE EXTRACT(YEAR FROM order_date) = 2026;
    
  7. Find the customer with the highest spend in each city.

    WITH city_spend AS (
      SELECT c.city, c.customer_id, c.customer_name, SUM(o.amount) AS total_spent,
        RANK() OVER (PARTITION BY c.city ORDER BY SUM(o.amount) DESC) AS rnk
      FROM customers c JOIN orders o ON c.customer_id = o.customer_id
      GROUP BY c.city, c.customer_id, c.customer_name
    )
    SELECT city, customer_name, total_spent FROM city_spend WHERE rnk = 1;
    
  8. Identify customers who churned — placed orders in one quarter but none in the following quarter.

    WITH quarterly AS (
      SELECT DISTINCT customer_id, EXTRACT(YEAR FROM order_date) AS yr, CEIL(EXTRACT(MONTH FROM order_date)/3.0) AS qtr
      FROM orders
    )
    SELECT a.customer_id FROM quarterly a
    LEFT JOIN quarterly b ON a.customer_id = b.customer_id AND b.yr = a.yr AND b.qtr = a.qtr + 1
    WHERE b.customer_id IS NULL AND a.qtr < 4;
    
  9. Find the three consecutive months with the highest combined revenue.

    WITH monthly AS (
      SELECT DATE_TRUNC('month', order_date) AS month, SUM(amount) AS revenue
      FROM orders GROUP BY 1
    )
    SELECT month AS start_month,
      revenue + LEAD(revenue,1) OVER (ORDER BY month) + LEAD(revenue,2) OVER (ORDER BY month) AS three_month_total
    FROM monthly
    ORDER BY three_month_total DESC LIMIT 1;
    
  10. Write a query to detect gaps in a sequential order_id column (missing IDs).

    WITH bounds AS (SELECT MIN(order_id) AS min_id, MAX(order_id) AS max_id FROM orders),
    all_ids AS (
      SELECT generate_series(min_id, max_id) AS id FROM bounds  -- PostgreSQL
    )
    SELECT id AS missing_order_id FROM all_ids
    WHERE id NOT IN (SELECT order_id FROM orders);
    

    Optimization tip: generate_series is PostgreSQL-specific; in MySQL/SQL Server, the same result requires a recursive CTE or a numbers/tally table instead.

💻 These 50 problems span exactly the difficulty curve real interviews use — if numbers 41-50 felt genuinely hard, that's normal; they're deliberately senior-level "gaps and islands" and relational-division patterns most candidates only encounter after real production experience.

Scenario-Based SQL Questions by Domain

Scenario questions test structured thinking over a single "correct" query — interviewers grade how you break down an ambiguous business question, not just syntax.

1. Sales Database: "Find our top 10 customers by revenue in the last 90 days." Intermediate

Structured Answer: "I'd filter orders to the last 90 days first, join to customers, aggregate total revenue per customer with SUM and GROUP BY, then sort descending with a LIMIT 10 — being careful to decide up front whether 'revenue' should include or exclude cancelled/refunded orders, since that assumption changes the result meaningfully."

2. E-commerce Database: "How would you identify cart abandonment — customers who added items but never completed checkout?" Advanced

Structured Answer: "This needs two related tables — a cart/cart_items table and an orders table. I'd find cart records with no matching completed order for that customer within a reasonable time window, using a LEFT JOIN or NOT EXISTS pattern, similar to finding customers with no orders at all, but scoped to a specific cart session rather than the customer's entire history."

3. HR Database: "Find employees who haven't had a salary review in over 12 months." Beginner

Structured Answer: "Assuming a salary_history table logs each review date, I'd get each employee's most recent review with MAX(review_date) grouped by employee, then filter where that maximum date is more than 12 months before today — a straightforward aggregation plus a date comparison."

4. Finance Database: "Reconcile transactions between two systems that should match but don't." Advanced

Structured Answer: "I'd use a FULL OUTER JOIN between the two transaction tables on a shared identifier (like a transaction reference number), then filter for rows where either side is NULL (present in one system but not the other) or where matched amounts differ — isolating exactly where and how the discrepancy occurs rather than re-checking every row manually."

5. Healthcare Database: "Find patients with more than 3 appointments in the last 6 months, without exposing identifying details to a general analytics team." Advanced

Structured Answer: "I'd build the aggregation (COUNT of appointments per patient_id, filtered to the last 6 months, HAVING COUNT > 3) against a de-identified view rather than the raw patient table, keeping identifying fields like name and contact info restricted to authorized roles only — a common real-world requirement layered on top of the query logic itself."

6. Banking Database: "Detect potentially fraudulent accounts based on unusual transaction patterns." Advanced

Structured Answer: "I'd start with statistical outlier detection — accounts with transaction amounts more than a few standard deviations above their own historical average, or an unusually high transaction count within a short time window — computed with window functions (AVG/STDEV OVER PARTITION BY account_id) rather than a single fixed threshold applied to every account equally."

7. Marketing Database: "Calculate the conversion rate for each marketing campaign." Intermediate

Structured Answer: "I'd join a campaign_leads table (everyone the campaign reached) to an orders table on customer_id, then calculate COUNT(DISTINCT converted customers) / COUNT(DISTINCT total leads) per campaign, being careful to define a clear conversion attribution window (e.g., orders within 30 days of being reached) rather than counting any order ever placed."

8. Operations Database: "Find warehouses that are consistently shipping orders late." Intermediate

Structured Answer: "I'd calculate the difference between promised_date and actual_ship_date per order, average that by warehouse_id, and filter for warehouses whose average delay exceeds an agreed threshold — then also check the standard deviation, since a high average with low variance (consistently late) is a different operational problem than a high average driven by a few extreme outliers."

9. Customer Support Database: "Find the average resolution time per support agent, and flag anyone significantly slower than the team average." Intermediate

Structured Answer: "I'd calculate resolution time (closed_at - created_at) per ticket, average it per agent with GROUP BY, then compare each agent's average against the overall team average — flagging anyone meaningfully above it, while also considering ticket complexity/category as a possible confounding factor before concluding an agent is genuinely underperforming."

10. Supply Chain Database: "Identify products at risk of stockout in the next 2 weeks based on current sales velocity." Advanced

Structured Answer: "I'd calculate each product's average daily sales over a recent trailing window, divide current stock_quantity by that daily rate to estimate days of stock remaining, and flag anything below 14 — a query combining a window-function-based average with a straightforward arithmetic projection, more useful to operations than a static low-stock threshold that ignores how fast a product actually sells."

Real Company SQL Interview Patterns

Every company runs a slightly different process, and the patterns below reflect commonly reported structures from public interview experiences and each company's general hiring approach — not confidential or verbatim leaked questions. Use this as a guide to what kind of SQL round to expect, not a script to memorize.

Company Typical SQL Round Format Common Topics
TCS Written/aptitude test (TCS NQT) or a short technical round SELECT/WHERE/GROUP BY fundamentals, JOIN types, basic aggregate functions
Infosys Technical round after an aptitude screen JOINs, GROUP BY/HAVING, basic subqueries
Accenture Technical round often paired with a business case study Query writing combined with a short client-style business scenario
Deloitte Case-study-heavy round reflecting its consulting culture Data reconciliation-style queries, JOINs, and structured business reasoning
EY Similar to Deloitte, risk/audit-adjacent framing Anomaly-detection-style queries, aggregate functions, basic subqueries
KPMG Technical round with a BFSI/audit lean Financial reconciliation queries, SUMIFS-equivalent conditional aggregation, JOINs
Capgemini Aptitude plus technical, often with a case-study element JOINs, GROUP BY, and an applied data-analysis task
Cognizant Technical round, sometimes with a light case study JOINs, window functions increasingly appearing given healthcare/BFSI client work
IBM Technical round with a stronger engineering lean Query optimization awareness, indexes, and moderately complex multi-table joins
Amazon Live coding on a real editor (often SQL-specific round) Window functions, subqueries, and query-writing under genuine time pressure with follow-up optimization questions
Flipkart Live practical task, e-commerce-context scenarios JOINs, aggregation, and window functions applied to sales/inventory-style datasets
Microsoft Live coding, sometimes combined with a broader technical round Query correctness plus a discussion of trade-offs (index usage, alternative query structures)
Google Live coding on a shared editor, high technical bar Complex multi-step queries (window functions, CTEs), with strong emphasis on explaining reasoning and edge cases clearly

What's consistent across all of them: every company tests core SELECT/JOIN/GROUP BY fundamentals in some form, and the differentiator is how much of the process leans toward business case reasoning (Big 4 and consulting) versus pure live technical coding depth (product companies and Big Tech, which test window functions and optimization thinking far more consistently than IT services firms do for entry-level hiring).

🏆 Product companies and Big Tech weight live, unaided query-writing far more heavily than IT services firms do — if that's your target, prioritize timed practice on a real editor over reading definitions.

Most Common SQL Mistakes in Interviews

Wrong JOIN type, especially defaulting to INNER JOIN when rows should be preserved. Using INNER JOIN when the question actually calls for LEFT JOIN silently drops rows that should have appeared with NULLs — a very common source of a technically-runs-but-wrong-answer in a live test.

Missing GROUP BY on a non-aggregated column. Including a plain column in SELECT alongside an aggregate function without adding it to GROUP BY either errors out or (in more permissive databases) returns an arbitrary, unreliable value.

Incorrect WHERE clause logic with mixed AND/OR. Forgetting parentheses around OR conditions combined with AND (e.g., WHERE city = 'Delhi' OR city = 'Mumbai' AND amount > 1000) changes the actual logic in a way that's easy to miss — always parenthesize explicitly when mixing operators.

Not handling NULLs correctly. Comparing against NULL with = instead of IS NULL, or assuming SUM/AVG treat NULL as zero, both produce silently wrong results rather than an obvious error.

Producing unintentional duplicate rows from a JOIN. Joining on a non-unique key (or forgetting a join condition entirely) multiplies rows unexpectedly — always sanity-check row counts before and after a JOIN when the result looks larger than expected.

Poor query performance from unnecessary complexity. Using a correlated subquery where a straightforward JOIN would work, or wrapping a query in several layers of unnecessary subqueries, both hurt readability and often performance — simpler is usually both faster and more interview-impressive.

Accidental Cartesian products. Forgetting a JOIN condition, or joining two tables via a comma without a WHERE filter, silently produces every combination of rows from both tables — a result set that's often shockingly larger than expected, and a fast way to visibly signal a fundamental gap to an interviewer.

Not clarifying ambiguous requirements before writing the query. Jumping straight into SQL for a vague ask ("get me total sales") without first confirming what counts as a "sale" (gross vs net, included statuses, date range) often means solving the wrong problem correctly — interviewers consistently rate this clarifying instinct highly.

SQL Practical Test: 25 Exercises with Solutions

Use this as a self-graded, timed practice test. Reuse the shared schemas from the coding questions section above.

  1. Get all employees earning above the company average.WHERE salary > (SELECT AVG(salary) FROM employees)
  2. Find the department with the fewest employees.GROUP BY department_id ORDER BY COUNT(*) ASC LIMIT 1
  3. List customers who placed more than 5 orders.GROUP BY customer_id HAVING COUNT(*) > 5
  4. Find the total revenue generated in the current year.WHERE EXTRACT(YEAR FROM order_date) = EXTRACT(YEAR FROM CURRENT_DATE)
  5. Get the three most recently hired employees.ORDER BY hire_date DESC LIMIT 3
  6. Find all orders where the amount is a round number (no decimals).WHERE amount = FLOOR(amount)
  7. List employees who share the same manager. → self-JOIN grouped by manager_id
  8. Find the product with the highest single-order quantity ever sold.ORDER BY quantity DESC LIMIT 1 on order_details
  9. Get the number of orders placed each day of the week.GROUP BY EXTRACT(DOW FROM order_date)
  10. Find customers whose name appears more than once (potential duplicates).GROUP BY customer_name HAVING COUNT(*) > 1
  11. Calculate each employee's tenure in years.EXTRACT(YEAR FROM AGE(CURRENT_DATE, hire_date))
  12. Find orders with no corresponding entry in order_details (data integrity check). → LEFT JOIN + WHERE od.order_id IS NULL
  13. Get the average order value per customer city. → JOIN customers to orders, GROUP BY city, AVG(amount)
  14. Find the top-selling product category by revenue. → JOIN + GROUP BY category + ORDER BY revenue DESC LIMIT 1
  15. List all employees who don't have a manager assigned.WHERE manager_id IS NULL
  16. Find the percentage of orders that were cancelled. → conditional aggregation: SUM(CASE WHEN status='Cancelled' THEN 1 ELSE 0 END) * 100.0 / COUNT(*)
  17. Get each customer's most recent order.ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC), filter rn = 1
  18. Find departments where the average salary exceeds ₹80,000.GROUP BY department_id HAVING AVG(salary) > 80000
  19. List products never assigned a category (data quality check).WHERE category IS NULL
  20. Find the day with the highest single-day revenue.GROUP BY order_date ORDER BY SUM(amount) DESC LIMIT 1
  21. Get a list of all employee-manager pairs, including employees with no manager. → self-JOIN using LEFT JOIN
  22. Find customers who ordered in both January and February of the same year. → two conditional EXISTS subqueries, or GROUP BY with COUNT(DISTINCT month) = 2
  23. Calculate the standard deviation of order amounts.SELECT STDDEV(amount) FROM orders; (STDEV in SQL Server)
  24. Find the average number of days between consecutive orders per customer. → LAG(order_date) per customer, then AVG of the date differences
  25. Write a query that returns "Weekday" or "Weekend" as a column based on order_date. → CASE WHEN on EXTRACT(DOW ...)

✅ Time yourself completing all 25 in one sitting — most live SQL assessments run 30-60 minutes for a similar volume of problems, so this is close to a realistic dry run.

The Ultimate SQL Cheat Sheet

Core commands by category

Category Commands
DDL CREATE, ALTER, DROP, TRUNCATE
DML SELECT, INSERT, UPDATE, DELETE
DCL GRANT, REVOKE
TCL COMMIT, ROLLBACK, SAVEPOINT

Query structure and logical execution order

SELECT column_list          -- 5. choose output columns
FROM table                  -- 1. start with the source table
JOIN other_table ON ...     -- 2. combine with related tables
WHERE condition              -- 3. filter individual rows
GROUP BY column              -- 4. group rows
HAVING aggregate_condition   -- 4b. filter groups
ORDER BY column               -- 6. sort the result
LIMIT n;                       -- 7. restrict row count

Join types at a glance

Join Returns
INNER JOIN Only matching rows in both tables
LEFT JOIN All left-table rows + matches from right (NULL if none)
RIGHT JOIN All right-table rows + matches from left (NULL if none)
FULL OUTER JOIN All rows from both, matched where possible
SELF JOIN A table joined to itself via aliases
CROSS JOIN Every combination of rows from both tables

Aggregate functions

Function Purpose
COUNT() Number of rows (or non-null values)
SUM() Total of a numeric column
AVG() Average of a numeric column
MAX() / MIN() Highest / lowest value
STDDEV() Standard deviation

Window functions

Function Purpose
ROW_NUMBER() Unique sequential number per partition
RANK() Ranking with gaps after ties
DENSE_RANK() Ranking without gaps after ties
LEAD() / LAG() Access next / previous row's value
NTILE(n) Divide rows into n roughly equal groups
SUM()/AVG() OVER() Running totals / moving averages

Date functions (syntax varies by database)

Task PostgreSQL MySQL SQL Server
Current date CURRENT_DATE CURDATE() GETDATE()
Date difference date2 - date1 DATEDIFF(date2, date1) DATEDIFF(day, date1, date2)
Extract part EXTRACT(MONTH FROM d) MONTH(d) MONTH(d)
Limit rows LIMIT n LIMIT n TOP n

Constraints

Constraint Enforces
PRIMARY KEY Unique, non-null row identifier
FOREIGN KEY Valid reference to another table's key
UNIQUE No duplicate values
NOT NULL A value must be provided
CHECK A custom validation rule
DEFAULT An automatic fallback value

Interview tips

30-Day SQL Interview Preparation Plan

Use this as a realistic, day-by-day structure if you have roughly one month before your interview and can dedicate 1-2 hours a day.

Week 1 — Fundamentals

Week 2 — Joins and Subqueries

Week 3 — Window Functions and Advanced Topics

Week 4 — Scenarios, Mock Interviews, and Company Research

📅 Want this exact plan with structured lessons, real project practice, and mentor-reviewed queries instead of self-guided prep? The DataVix SQL curriculum is built around this same sequence, end to end.

Free SQL Practice Resources

You don't need paid tools to prepare properly — here's how to practice for free, roughly in order of what actually moves the needle most.

Frequently Asked Questions

How many SQL interview questions should a fresher prepare? Preparing 50-70 questions in real depth — SELECT/WHERE fundamentals, all JOIN types, GROUP BY/HAVING, subqueries, CTEs, and at least ROW_NUMBER/RANK — covers roughly 80% of what's actually asked.

What is the most commonly asked SQL interview question for freshers? "What's the difference between WHERE and HAVING?" and "explain the JOIN types" come up in nearly every round; "find the second-highest salary" is the most common live-coding question.

Is SQL mandatory for a Data Analyst job? Yes, in almost every case — SQL is the most consistently tested skill across Data Analyst interviews in India, since most company data lives in relational databases.

Can a complete beginner learn SQL and clear an interview? Yes. Most beginners with zero coding background become comfortable with core SQL within 3-4 weeks of regular, hands-on practice.

Which SQL should I learn — MySQL, PostgreSQL, or SQL Server? Learn ANSI-standard concepts first (they're 95% identical across databases), then pick one — PostgreSQL or MySQL — to practice hands-on, both free and well-documented.

What is the difference between SQL interview questions for freshers and experienced professionals? Freshers are tested on fundamentals — SELECT/WHERE, JOINs, GROUP BY, basic subqueries; experienced candidates get deeper on window functions, optimization, and execution plans.

How do I practice SQL for interviews without a real company database? Use a free, no-signup practice platform like SQLabHub.com, and work through the 25-exercise practical test and 50 coding problems in this guide.

What is the second-highest salary SQL question, and why is it asked so often? It tests whether you understand subqueries, LIMIT/OFFSET, or window functions like DENSE_RANK — multiple valid approaches exist, letting interviewers see your reasoning process, not a memorized answer.

Are SQL interview questions and answers available as a downloadable PDF? This guide works as your complete reference and can be saved as a PDF directly from your browser to study offline.

What are the most important SQL topics for a Data Analyst interview? Joins, GROUP BY with aggregates, window functions, CTEs, and subqueries make up roughly 80% of real Data Analyst SQL interview questions.

What is asked in a TCS SQL interview? Fundamentals — SELECT/WHERE/GROUP BY, JOIN types, and basic aggregates — through the TCS NQT test and a foundational technical round.

What is asked in an Accenture SQL interview? Query writing (joins, aggregates) combined with a business case study, reflecting Accenture's client-project-based analyst work.

How difficult are SQL interviews for freshers? Moderately difficult but learnable — they test fundamentals and reward clear, structured reasoning over a single memorized correct answer.

What is the difference between a SQL interview and a SQL test? An interview is conversational Q&A; a test is a timed, hands-on task in a real query editor — increasingly the standard format.

What is the difference between DELETE, TRUNCATE, and DROP? DELETE removes specific rows and can be rolled back; TRUNCATE removes all rows and resets identity values; DROP removes the entire table structure.

What is the difference between a Primary Key and a Foreign Key? A Primary Key uniquely identifies rows in its own table and can't be NULL; a Foreign Key references a Primary Key in another table.

What is normalization in SQL? Organizing tables to reduce redundancy and improve data integrity, typically progressing through 1NF, 2NF, and 3NF.

What is the difference between WHERE and HAVING? WHERE filters individual rows before grouping; HAVING filters groups after aggregation.

What is the difference between INNER JOIN and LEFT JOIN? INNER JOIN returns only matching rows in both tables; LEFT JOIN returns all left-table rows plus matches from the right, with NULL where unmatched.

What is a subquery in SQL? A query nested inside another query, used to compute an intermediate result the outer query filters or compares against.

What is a Common Table Expression (CTE)? A named, temporary result set defined with WITH ... AS, referenceable multiple times within a single query for cleaner multi-step logic.

What are window functions in SQL? Functions that calculate a value across a set of related rows without collapsing the result the way GROUP BY does.

What is the difference between RANK() and DENSE_RANK()? RANK() skips numbers after a tie; DENSE_RANK() doesn't — the difference only shows up when ties exist.

What are ACID properties in a database? Atomicity, Consistency, Isolation, Durability — the properties that guarantee a transaction completes reliably.

What is the difference between UNION and UNION ALL? UNION removes duplicate rows; UNION ALL keeps all rows including duplicates, and is faster.

What is an index in SQL, and why does it matter for interviews? A data structure that speeds up data retrieval at the cost of slower writes and extra storage — interviewers test whether you understand this trade-off.

What is a stored procedure, and why would a Data Analyst use one? A saved, reusable, parameterized block of SQL code — useful for automating a recurring report requested regularly by stakeholders.

What is the correct order of execution in a SQL query? FROM → JOIN → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT — which differs from the order you write the query.

How do I answer a scenario-based SQL interview question? State your approach out loud before writing the query — interviewers grade your reasoning process as much as the final query.

What is the best way to practice SQL before an interview? Practice on real, messy-feeling datasets — SQLabHub.com offers free hands-on query practice for exactly this.

Do I need to know NoSQL for a SQL interview? No — deep NoSQL knowledge isn't expected unless the role explicitly requires it; a brief conceptual comparison question may come up at most.

What is a correlated subquery, and how is it different from a regular subquery? A correlated subquery references an outer-query column and re-evaluates per row; a regular subquery runs once and reuses its result.

What is the difference between CHAR and VARCHAR? CHAR stores fixed-length text, padding shorter values; VARCHAR stores variable-length text using only the space needed.

What is the GROUP BY clause used for? Collapsing rows sharing the same value into groups so an aggregate function can calculate one result per group.

What is a self join, and when would you use one? A table joined to itself via aliases — commonly used for hierarchical data like an employee-and-manager relationship stored in one table.

What is the difference between COUNT(*), COUNT(1), and COUNT(column)? COUNT(*) and COUNT(1) both count all rows including NULLs; COUNT(column) counts only non-null values in that specific column.

What SQL topics come up most in coding interview rounds? Finding the Nth highest value, running totals, month-over-month comparisons with LAG, deduplication with ROW_NUMBER, and multi-table joins with aggregation.

How long does it take to become interview-ready in SQL as a complete beginner? With consistent daily practice, most beginners reach a genuinely interview-ready level for fresher roles in 4-6 weeks.

📚 Keep preparing with the rest of the DataVix guide library — Data Analyst Interview Questions (covers SQL, Excel, and Power BI together), the Excel Interview Questions guide, and the Data Analyst Roadmap.

Ready to Move from "Knows SQL" to "Interview-Ready in SQL"?

Reading 150+ questions and 50 coding problems is a strong start, but real interview confidence comes from writing queries yourself, under pressure, not from reading solutions. Here's the fastest path to being genuinely ready:

This is exactly the sequence taught inside the DataVix Data Analyst course — SQL, Excel, Power BI, and Python, built around real projects and reviewed by mentors, with dedicated interview preparation and mock interviews included.

🚀 Ready to stop guessing and start preparing with a real structure? Enroll in the DataVix Data Analyst course — one-time fee, lifetime access, real project reviews, mentor support, and placement guidance. Or start with the free Data Analyst Roadmap and SQLabHub.com to start practicing today.

Frequently Asked Questions

How many SQL interview questions should a fresher prepare?

Preparing 50-70 questions in real depth — SELECT/WHERE fundamentals, all JOIN types, GROUP BY/HAVING, subqueries, CTEs, and at least ROW_NUMBER/RANK from window functions — covers roughly 80% of what's actually asked in fresher interviews. This guide has 150+ so you're over-prepared, but don't try to memorize everything equally.

What is the most commonly asked SQL interview question for freshers?

"What's the difference between WHERE and HAVING?" and "Explain the different types of JOINs" are asked in some form in nearly every SQL round, regardless of company or seniority level. "Find the second-highest salary" is the most common live-coding question.

Is SQL mandatory for a Data Analyst job?

Yes, in almost every case. SQL is the most consistently tested skill across Data Analyst interviews in India, because most company data lives in relational databases — even roles that emphasize Excel or Power BI still expect working SQL knowledge.

Can a complete beginner learn SQL and clear an interview?

Yes. SQL is a query language, not traditional programming, and most beginners with zero coding background become comfortable with core SQL (SELECT, WHERE, JOIN, GROUP BY) within 3-4 weeks of regular practice. See the 30-day plan later in this guide.

Which SQL should I learn — MySQL, PostgreSQL, or SQL Server?

Learn ANSI-standard SQL concepts first (they're 95% identical across databases), then pick one to practice hands-on — PostgreSQL and MySQL are both free, well-documented, and cover the vast majority of what's tested in interviews. Note syntax differences (LIMIT vs TOP vs FETCH FIRST) as you encounter them rather than memorizing all three upfront.

What is the difference between SQL interview questions for freshers and experienced professionals?

Freshers are tested on fundamentals — SELECT/WHERE, JOINs, GROUP BY, basic subqueries — with heavy emphasis on writing correct, readable queries. Experienced candidates get deeper on window functions, query optimization, execution plans, and system-design-adjacent database questions.

How do I practice SQL for interviews without a real company database?

Use a free, no-signup practice platform like SQLabHub.com to write real queries against realistic sample data, and pair that with the 25-exercise practical test and 50 coding problems included in this guide.

What is the second-highest salary SQL question, and why is it asked so often?

It's a classic query — find the second-highest value in a column — because it tests whether you understand subqueries, LIMIT/OFFSET, or window functions like DENSE_RANK, and there are multiple valid approaches, letting interviewers see your reasoning, not just a memorized answer. It's covered in full in the coding questions section below.

Are SQL interview questions and answers available as a downloadable PDF?

This guide is designed to work as your single reference — you can save it as a PDF directly from your browser (Print → Save as PDF) to study offline, and it stays current instead of going stale like a static file.

What are the most important SQL topics for a Data Analyst interview?

Joins (INNER/LEFT/self), GROUP BY with aggregate functions, window functions (ROW_NUMBER, RANK, running totals), CTEs, and subqueries make up roughly 80% of real Data Analyst SQL interview questions.

What is asked in a TCS SQL interview?

TCS generally tests SQL fundamentals — SELECT/WHERE/GROUP BY, JOIN types, and basic aggregate functions — through its NQT aptitude test and a foundational technical round, rarely going deep into window functions or optimization for entry-level hiring.

What is asked in an Accenture SQL interview?

Accenture typically combines SQL query-writing (joins, aggregates) with a business case study, since much of its analyst work is client-project based — expect a scenario question layered on top of a standard query task.

How difficult are SQL interviews for freshers?

Moderately difficult but very learnable — fresher SQL rounds test fundamentals (joins, aggregations, basic subqueries) rather than advanced optimization, and reward clear, structured reasoning over a memorized "correct" answer.

What is the difference between a SQL interview and a SQL test?

A SQL interview is conversational — questions, sometimes a whiteboard query. A SQL test (assessment) is a timed, hands-on task in a real query editor (HackerRank, CoderPad) — now the more common format at product companies and Big Tech.

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

DELETE removes specific rows and can be rolled back (with a WHERE clause optional); TRUNCATE removes all rows at once and resets identity/auto-increment values, generally faster but not row-filterable; DROP removes the entire table structure permanently, including its schema.

What is the difference between a Primary Key and a Foreign Key?

A Primary Key uniquely identifies each row in its own table and cannot be NULL; a Foreign Key is a column in one table that references a Primary Key in another table, enforcing referential integrity between the two.

What is normalization in SQL?

Normalization is the process of organizing database tables to reduce data redundancy and improve data integrity, typically progressing through normal forms (1NF, 2NF, 3NF) that eliminate repeating groups, partial dependencies, and transitive dependencies.

What is the difference between WHERE and HAVING?

WHERE filters individual rows before any grouping happens; HAVING filters groups after aggregation — you can't use an aggregate function like SUM() inside a WHERE clause, which is exactly why HAVING exists.

What is the difference between INNER JOIN and LEFT JOIN?

INNER JOIN returns only rows with matching values in both tables; LEFT JOIN returns all rows from the left table plus matched rows from the right table, filling in NULL where there's no match.

What is a subquery in SQL?

A subquery is a query nested inside another query, used to compute an intermediate result — like an average or a list of IDs — that the outer query then filters or compares against.

What is a Common Table Expression (CTE)?

A CTE, defined with WITH ... AS, creates a named, temporary result set that can be referenced multiple times within a single query — making multi-step logic significantly more readable than deeply nested subqueries.

What are window functions in SQL?

Window functions (ROW_NUMBER, RANK, LEAD, LAG, and aggregate functions used with OVER()) perform calculations across a set of rows related to the current row, without collapsing the result into fewer rows the way GROUP BY does.

What is the difference between RANK() and DENSE_RANK()?

RANK() skips numbers after a tie (1, 2, 2, 4); DENSE_RANK() doesn't skip (1, 2, 2, 3) — the difference only shows up when there are ties in the ranked values.

What are ACID properties in a database?

Atomicity, Consistency, Isolation, Durability — the four properties that guarantee a database transaction completes reliably: fully or not at all, leaving the database in a valid state, isolated from other concurrent transactions, and permanently saved once committed.

What is the difference between UNION and UNION ALL?

UNION combines results from two queries and removes duplicate rows; UNION ALL combines them and keeps all rows, including duplicates — and is faster since it skips the deduplication step.

What is an index in SQL, and why does it matter for interviews?

An index is a data structure that speeds up data retrieval by creating a fast lookup path to rows, at the cost of slightly slower writes and extra storage — interviewers ask about indexes to test whether you understand the trade-off between read and write performance, not just that indexes 'make queries faster.'

What is a stored procedure, and why would a Data Analyst use one?

A stored procedure is a saved, reusable block of SQL code that can accept parameters and be executed with a single call — useful for automating a recurring report that different stakeholders request regularly, without rewriting the same query each time.

What is the correct order of execution in a SQL query?

Logically: FROM → JOIN → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT — this differs from the order you *write* a query, which is why WHERE can't reference a column alias defined in SELECT.

How do I answer a scenario-based SQL interview question?

State your approach out loud before writing the query: what result is needed, which tables and joins are involved, and why — interviewers grade your reasoning process as much as the final, correct query.

What is the best way to practice SQL before an interview?

Practice on real, messy-feeling datasets rather than only theory — SQLabHub.com offers free, no-signup, hands-on query practice, and pairing that with the 25-exercise practical test in this guide builds real interview confidence.

Do I need to know NoSQL for a SQL interview?

No — a SQL interview tests relational database concepts specifically. NoSQL may come up briefly as a conceptual comparison question ("when would you use NoSQL over SQL?"), but deep NoSQL knowledge isn't expected unless the role explicitly requires it.

What is a correlated subquery, and how is it different from a regular subquery?

A correlated subquery references a column from the outer query and is re-evaluated once for every row the outer query processes; a regular (non-correlated) subquery runs once, independently, and its result is reused for the whole outer query.

What is the difference between CHAR and VARCHAR?

CHAR stores fixed-length text, padding shorter values with spaces; VARCHAR stores variable-length text, using only the space the actual value needs — VARCHAR is more storage-efficient for text that varies in length.

What is the GROUP BY clause used for?

GROUP BY collapses rows sharing the same value in one or more columns into groups, so an aggregate function (SUM, COUNT, AVG) can calculate one result per group instead of per row.

What is a self join, and when would you use one?

A self join joins a table to itself, treating it as two logical tables via aliases — commonly used to find relationships within the same table, like an employee-and-manager hierarchy stored in a single employees table.

What is the difference between COUNT(*), COUNT(1), and COUNT(column)?

COUNT(*) counts all rows including NULLs; COUNT(1) behaves identically to COUNT(*) in virtually all modern databases (a common myth is that it's faster — it isn't); COUNT(column) counts only rows where that specific column is not NULL.

What SQL topics come up most in coding interview rounds?

Finding the Nth highest value, running totals, month-over-month comparisons using LAG, deduplication with ROW_NUMBER, and multi-table joins with aggregation are the five most consistently asked live-coding patterns.

How long does it take to become interview-ready in SQL as a complete beginner?

With consistent daily practice (1-2 hours), most beginners reach a genuinely interview-ready level for fresher Data Analyst roles in 4-6 weeks — the 30-day plan in this guide is structured for exactly that timeline.

₹1,799

One-time fee · Lifetime access
Enroll Now