100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
SQL

Common SQL Interview Questions

A curated walkthrough of the SQL interview questions asked most often, with clear, technically accurate answers.

Interview PrepIntermediate14 min readJul 8, 2026
Analogies

Overview

SQL interviews rarely test exotic syntax. Instead, they probe whether you understand core relational concepts well enough to explain them clearly and apply them correctly: how filtering differs before and after grouping, what makes a key a key, how deletion commands differ in cost and reversibility, and how three-valued NULL logic changes the way comparisons behave. This topic collects the questions that come up again and again across junior-to-mid-level SQL interviews, paired with answers that go beyond a one-liner so you understand the reasoning, not just the result.

🏏

Cricket analogy: Just as a selector's interview probes whether a player truly understands field placements and not just memorized stats, a SQL interview probes whether you understand WHERE vs HAVING and keys, not just recite syntax.

Frequently Asked Questions

Q: What is the difference between WHERE and HAVING?

WHERE filters individual rows before any grouping or aggregation happens, and it cannot reference aggregate functions like SUM() or COUNT(). HAVING filters groups after GROUP BY has produced them, and it is specifically designed to filter on aggregate results, such as HAVING COUNT(*) > 5. A query can use both: WHERE narrows the rows that get grouped, then HAVING narrows which resulting groups are kept. If you write a condition on a raw column with no aggregation, put it in WHERE for better performance, since WHERE can eliminate rows before the (often expensive) grouping work happens.

🏏

Cricket analogy: WHERE is like a selector cutting players before trials even form squads, while HAVING is like cutting entire squads after they've been formed and their combined stats, like total runs, are known.

Q: What are the different types of JOIN, and how do they differ?

INNER JOIN returns only rows that have matching values in both tables. LEFT (OUTER) JOIN returns all rows from the left table plus matched rows from the right table, filling unmatched right-side columns with NULL. RIGHT (OUTER) JOIN is the mirror image, keeping all rows from the right table. FULL OUTER JOIN keeps all rows from both tables, matching where possible and filling NULLs elsewhere. CROSS JOIN produces the Cartesian product of both tables with no matching condition at all. A SELF JOIN is not a distinct join type mechanically — it's any join (usually INNER or LEFT) where a table is joined to itself, typically used for hierarchical or comparative data like employee-manager relationships.

🏏

Cricket analogy: INNER JOIN keeps only batters who also bowled, LEFT JOIN keeps every batter even if they never bowled (NULL bowling stats), and CROSS JOIN pairs every batter with every possible bowler with no matching condition.

Q: What is the difference between a primary key and a unique key?

Both enforce uniqueness of values in a column or set of columns, and both are typically backed by an index. The differences: a table can have only one primary key but multiple unique keys/constraints. A primary key's columns cannot contain NULL, while a unique key generally allows one or more NULLs (since NULL is not considered equal to another NULL, so multiple NULLs don't violate uniqueness in most databases). The primary key is conventionally the column(s) other tables reference via foreign keys, signaling 'this is the canonical identifier for a row', while a unique key just guarantees no duplicate values exist for that column, such as an email address.

🏏

Cricket analogy: A primary key is like a player's unique jersey number that can never be blank and is what other tables reference, while a unique key is like a player's passport number, also unique but allowed to be missing for some records.

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

DELETE is a DML statement that removes rows one at a time (optionally filtered by WHERE), logs each row deletion, can be rolled back within a transaction, and fires any ON DELETE triggers. TRUNCATE is a DDL-like statement that deallocates the data pages holding all rows in one fast operation, cannot use WHERE (it always removes everything), typically cannot be rolled back in many databases (or requires the truncate to occur inside an explicit transaction, depending on the engine), and resets identity/auto-increment counters. DROP removes the entire table object itself — structure, data, indexes, constraints, and permissions all disappear. In short: DELETE removes some or all rows and keeps the table; TRUNCATE removes all rows fast and keeps the table; DROP removes the table entirely.

🏏

Cricket analogy: DELETE is like removing specific dismissed batters from a scorecard one by one, which can be undone before the innings closes; TRUNCATE is like wiping the whole scorecard clean instantly; DROP is like tearing up the scorecard sheet entirely.

Q: What is a Common Table Expression (CTE), and why use one?

A CTE, defined with WITH name AS (SELECT ...), is a named, temporary result set that exists only for the duration of the query that follows it. It improves readability by letting you break a complex query into logical, named steps instead of nesting subqueries. CTEs can also be referenced multiple times in the same query without repeating the subquery logic, and a recursive CTE (WITH RECURSIVE in many databases) is the standard way to walk hierarchical data such as an org chart or category tree. Unlike a view, a CTE is not persisted in the database schema — it's scoped entirely to one statement.

🏏

Cricket analogy: A CTE is like a temporary net-practice drill set up just for one training session and torn down after, letting a coach break a complex strategy review into named steps like 'top_order_stats' without saving it permanently.

Q: How does NULL behave in comparisons, and why does it trip people up?

NULL represents 'unknown', not zero or empty string, so any direct comparison with NULL using =, !=, <, or > evaluates to UNKNOWN rather than TRUE or FALSE — including NULL = NULL. This means WHERE column = NULL never matches any row, even rows that are NULL, which surprises many developers. The correct way to test for NULL is IS NULL or IS NOT NULL. NULL also affects aggregate functions (most ignore NULLs, e.g., AVG and COUNT(column) skip them, while COUNT(*) counts all rows) and logical operators (UNKNOWN propagates through AND/OR using three-valued logic, so a row is only returned by WHERE if the final result is TRUE, not UNKNOWN).

🏏

Cricket analogy: WHERE column = NULL is like asking an umpire 'is this delivery equal to unknown outcome,' which never resolves to yes; you must ask IS NULL instead, just as three-valued logic means NULL never equals NULL.

Q: What's the difference between UNION and UNION ALL?

UNION combines the result sets of two or more SELECT statements and removes duplicate rows, which requires an implicit sort/deduplication step and is therefore slower. UNION ALL combines the result sets and keeps every row, including duplicates, making it faster since no deduplication work is done. Both require the SELECT statements to have the same number of columns with compatible data types in the same order. Use UNION ALL whenever you know duplicates either can't occur or don't matter, since it avoids unnecessary overhead.

🏏

Cricket analogy: UNION merging two squad lists and removing duplicate players requires sorting and checking for repeats, while UNION ALL just stacks both lists together instantly, even if a player appears on both rosters.

Q: What is a correlated subquery, and how does it differ from a regular subquery?

A regular (non-correlated) subquery runs once, independently of the outer query, and its result is used by the outer query. A correlated subquery references a column from the outer query, so conceptually it re-executes once per row processed by the outer query, using that row's values as input. For example, finding employees who earn more than the average salary in their own department requires a correlated subquery that recalculates the department average per row. Correlated subqueries are powerful but can be slow on large datasets since naive execution is row-by-row; modern query optimizers often rewrite them as joins internally when possible.

🏏

Cricket analogy: A correlated subquery finding batters who scored above their own team's average is like recalculating a team's average score fresh for each player being checked, versus a non-correlated subquery that computes one overall average once.

Q: What is the difference between a clustered and a non-clustered index?

A clustered index determines the physical order in which table rows are stored on disk — there can be only one per table because data can only be sorted one way physically. A non-clustered index is a separate structure that stores the indexed column values plus a pointer (or the clustered key) back to the actual row, and a table can have many non-clustered indexes. Reading via a clustered index is generally faster for range scans since the data is already in order, while non-clustered indexes add an extra lookup step to fetch the full row unless the query is 'covered' by the index alone.

🏏

Cricket analogy: A clustered index is like a scorecard physically sorted by batting order, so there's only one true physical order, while a non-clustered index is like a separate quick-reference sheet pointing back to each entry, and you can have several.

Q: How would you find duplicate rows in a table?

The classic approach groups by the columns that define a 'duplicate' and filters groups with a count greater than one: SELECT email, COUNT(*) FROM users GROUP BY email HAVING COUNT(*) > 1. To then delete duplicates while keeping one copy, a common pattern uses a window function like ROW_NUMBER() OVER (PARTITION BY email ORDER BY id) in a CTE, then deletes rows where the row number is greater than 1. This is asked frequently because it tests whether a candidate can combine GROUP BY/HAVING or window functions correctly rather than writing a slow self-join.

🏏

Cricket analogy: Deduplicating players registered twice by GROUP BY email HAVING COUNT(*) > 1 is like a scorer flagging any player listed twice on a roster; ROW_NUMBER() PARTITION BY email then lets you keep only the first registration and drop the rest.

Q: What is the difference between a scalar function and an aggregate function?

A scalar function operates on a single value and returns a single value for each row it's applied to, such as UPPER(), ROUND(), or DATEDIFF(). An aggregate function operates across a set of rows (typically a group, or the whole table) and collapses them into one summary value, such as SUM(), AVG(), COUNT(), MIN(), and MAX(). This distinction matters for where each can legally appear: scalar functions can be used almost anywhere including WHERE, while aggregate functions require GROUP BY context and can't be used directly in a WHERE clause, only in HAVING or SELECT.

🏏

Cricket analogy: A scalar function like ROUND() applied to one batter's strike rate at a time is like adjusting one player's individual stat, while an aggregate function like AVG() collapses an entire team's scores into one summary number, usable only with GROUP BY context.

Quick Reference

  • WHERE filters rows before grouping; HAVING filters groups after aggregation.
  • INNER, LEFT, RIGHT, FULL OUTER, CROSS, and SELF joins each answer a different 'which rows survive' question.
  • Primary key: one per table, no NULLs, canonical row identifier. Unique key: many allowed, NULLs usually permitted.
  • DELETE removes rows (logged, filterable, rollback-able); TRUNCATE clears all rows fast; DROP removes the table itself.
  • A CTE is a named, query-scoped temporary result set, useful for readability and recursion.
  • NULL comparisons with =/!= always evaluate to UNKNOWN; use IS NULL / IS NOT NULL instead.
  • UNION deduplicates and sorts; UNION ALL keeps all rows and is faster.
  • A correlated subquery references the outer query's row values and conceptually runs per row.
  • A table has at most one clustered index but can have many non-clustered indexes.
  • GROUP BY + HAVING COUNT(*) > 1, or ROW_NUMBER() window functions, are the standard duplicate-detection tools.
  • Scalar functions return one value per row; aggregate functions collapse many rows into one value.

Key Takeaways

  • Interviewers care more about *why* an answer is correct than the syntax itself — practice explaining, not just writing queries.
  • Filtering order (WHERE before grouping, HAVING after) is one of the most commonly misunderstood fundamentals.
  • Knowing the practical differences between DELETE/TRUNCATE/DROP signals you understand transactional and operational risk, not just syntax.
  • NULL's three-valued logic is a frequent source of subtle bugs and a favorite interview trap.
  • Being able to write a duplicate-detection or top-N-per-group query fluently is one of the best signals of real SQL fluency.

Practice what you learned

Was this page helpful?

Topics covered

#SQL#DatabaseSQLStudyNotes#Database#CommonSQLInterviewQuestions#Common#Interview#Questions#Frequently#StudyNotes#SkillVeris

Frequently Asked Questions

21 categories · pick one to explore

Where can I get free study notes for programming and tech subjects?
SkillVeris offers completely free study notes covering programming and tech subjects, with no signup fees or paywalls. The notes are structured by course and topic, written for quick understanding, and enriched with the Learn Through Hobbies analogy method, so you can revise concepts through cricket, music, gaming, cooking and more.
Are SkillVeris study notes good for exam revision?
Yes, the study notes are designed for efficient revision: each topic answers its heading immediately, keeps explanations concise, and links to related glossary terms and cheat sheets. Students preparing for university exams or certification tests use them as quick revision notes because they distil concepts without the padding of full textbooks.
What subjects do the free study notes cover?
The study notes span the platform's main domains, including AI and machine learning, Python and programming, web development, DevOps, cloud, security and databases. Coverage mirrors the 37 live courses, so notes exist for the topics you are actually studying, and new note sets are added as courses launch.
How are SkillVeris study notes different from regular textbooks?
The notes are answer-first, concise and free, whereas textbooks are long and often expensive. Each section explains one concept directly, then reinforces it through selectable hobby analogies like cricket or cooking. Notes also cross-link to the glossary, blog and cheat sheets, letting you jump to related material instantly instead of flipping pages.
Can I use the developer study material without creating an account?
The study notes are free to access, and SkillVeris does not charge anything for its developer study material at any point. Browsing notes is straightforward from the Study Notes section, and if you want progress tracking, certificates and AI Mentor conversations tied to your learning, a free account unlocks those extras.
Do the study notes explain concepts with analogies?
Yes, this is a signature SkillVeris feature. Study notes use the Learn Through Hobbies method, explaining technical concepts through analogies from twelve domains including cricket, music, gaming, photography, travel, movies, fitness, chess, cooking, finance, business and sports. You can switch the analogy domain instantly to whichever hobby makes the concept click.
Are the revision notes suitable for last-minute exam preparation?
Yes, revision notes on SkillVeris work well for last-minute preparation because every section states the answer in its first sentences, so skimming is genuinely effective. Pair them with the relevant cheat sheet for formulas and syntax, and use the glossary for any unfamiliar term you meet while cramming.
Is there free study material for AI and machine learning?
Yes, SkillVeris provides free study notes across its AI and ML catalogue, covering Python for AI, deep learning frameworks like PyTorch and TensorFlow, Hugging Face Transformers, Large Language Models, RAG, AI agents and MLOps. All of it is free, making it a strong resource for Indian students and global learners alike.
Can beginners understand the study notes, or are they for experts?
Beginners can absolutely use them. The notes are written in plain language, define terms as they appear, and lean on hobby analogies to make abstract ideas concrete. Difficulty scales with the underlying course level, so beginner-course notes stay gentle while advanced-course notes go deeper, and the glossary supports you throughout.
How do study notes connect with SkillVeris courses?
Study notes are organised by course and topic, so they map directly to the structured courses and their 24–40-lesson curriculum. Many learners study a lesson first, then use the matching notes for revision before module assessments and the final exam, where 80 percent is required to pass and earn the certificate.
Are there study notes for Python specifically?
Yes, Python is well covered through notes tied to the Python-focused courses, including Python for AI and ML. Topics span fundamentals through applied machine learning usage. You can reinforce the notes with Python practice in Code Lab, which runs code in your browser with no installation required.
Do the study notes include code examples?
Yes, study notes include code examples wherever a concept is best shown in code, alongside explanations, key points and analogies. Reading a snippet in the notes and then reproducing it yourself in Code Lab is an effective loop, since Code Lab lets you run code in the browser across six languages.
How often is new study material added to SkillVeris?
Study material grows alongside the course catalogue. Whenever new courses join the platform's 37 live courses, matching study notes, glossary entries and cheat sheets are added so the resources stay in sync. Existing notes are also refined over time, so it is worth revisiting topics you studied earlier.
Can I use SkillVeris notes to prepare for technical interviews?
Yes, the notes make excellent interview revision because they compress each concept into direct, answer-first explanations, which mirrors how you should answer interview questions. Combine them with the SkillVeris interview questions feature, which includes readiness scoring, to test whether your revision has actually made you interview-ready.
Are the study notes mobile-friendly for studying on the go?
Yes, the study notes are built to load fast and read comfortably on mobile devices, so you can revise during a commute or between classes. Sections are short and answer-first, which suits small screens, and analogy switching works on mobile too, letting you study anywhere without carrying books.
What is the difference between study notes and cheat sheets?
Study notes explain concepts in depth with context, examples and analogies, making them ideal for learning and revision. Cheat sheets are compact quick-reference summaries of syntax, commands and key facts, ideal once you already understand a topic. Most learners study the notes first, then keep the cheat sheet handy while coding.
Do study notes help if I am stuck on a course lesson?
Yes, reading the matching study notes often clarifies a lesson because the same concept is explained from a different angle, frequently with a different analogy. If you are still stuck, ask the AI Mentor, which answers 24/7 at Quick, Detailed or Deep-dive depth until the idea genuinely makes sense.
Is there free study material for DevOps and cloud topics?
Yes, SkillVeris carries free study notes for DevOps and cloud topics as part of its coverage across 37 live courses. The material suits learners following the DevOps Engineer or Cloud Engineer paths, and it links to related glossary terms and cheat sheets so you can revise the whole toolchain in one place.
Can school or college students in India use these notes for projects?
Yes, students across India and worldwide use SkillVeris notes for coursework, projects and exam preparation, and everything is free, which matters for student budgets. The notes explain concepts clearly enough to cite in project reports, and Code Lab lets you prototype the project code directly in your browser.
How should I combine study notes with other SkillVeris resources?
A proven loop: learn from a course lesson, revise with the matching study notes, look up unfamiliar terms in the glossary, keep the cheat sheet open while practising in Code Lab, and quiz yourself with interview questions. The AI Mentor fills any remaining gaps 24/7, at whatever depth you need.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse