मुख्य सामग्री पर जाएँ

Top 99 SQL Interview Questions and Answers (Beginner to Advanced) for 2026

99 SQL interview questions and answers for 2026, from beginner definitions to advanced scenario-based queries, with dialect notes for PostgreSQL, MySQL, and SQL Server.
Elena Kosourova
Elena Kosourova

अपना निःशुल्क खाता बनाएँ

अभ्यास और ट्रैक अपनी प्रगति को।

Google के साथ जारी रखेंजारी रखकर, आप हमारी उपयोग की शर्तें, हमारी गोपनीयता नीति को स्वीकार करते हैं और यह भी कि आपका डेटा USA में संग्रहीत है।

SQL interview questions fall into 3 groups: definitions (keys, joins, constraints, command types), query writing (aggregations, subqueries, CTEs, window functions), and scenario problems where you clean or analyze realistic data with duplicates, ties, and NULL values. Whether you're preparing for a data analyst, data engineer, or data scientist interview, or you're a hiring manager building an interview loop, you need answers for all 3.

In this article, I list 99 SQL interview questions and answers for 2026, from beginner definitions to advanced scenario-based queries. Where PostgreSQL, MySQL, SQL Server, Oracle, and SQLite behave differently, the answer says so.

If you're preparing for a specific database, you can also see our guides to MySQL interview questions, PostgreSQL interview questions, and SQL Server interview questions.

TL;DR

  • Beginner rounds test definitions: command types, keys, constraints, joins, and NULL handling.
  • Intermediate rounds test query writing: GROUP BY with HAVING, subqueries, CTEs, and window functions.
  • Advanced rounds hand you a business problem with duplicates, ties, gaps, or NULLs to handle correctly.
  • Window functions such as ROW_NUMBER(), RANK(), and LAG() come up at every level above beginner.
  • Practice in the employer's dialect: LIMIT vs TOP and EXCEPT vs MINUS trip candidates up.

SQL Interview Questions at a Glance

SQL interview questions follow the order in which people learn the language: definitions first, then query writing, then problem-solving on realistic data. The table maps each level to what interviewers check and where those questions sit in this article.

LevelWhat interviewers checkQuestions
BeginnerSQL, dialects, statements, aliases, keys, constraints, joins, and command types (DDL, DML, DCL, TCL, DQL)1–40
IntermediateCTEs, window functions, set operators, views, normalization, indexes, triggers, and DELETE vs TRUNCATE vs DROP41–87
Advanced and scenario-basedDeduplication, running totals, gaps and islands, pivots, top N per group, transactions, deadlocks, and query tuning88–99

How SQL interviews are run

Most companies use one or more of these formats:

  • Live coding: you write queries in a shared editor or an online assessment platform while the interviewer watches, usually against a small schema they describe.
  • Take-home assignment: you get a dataset and a set of business questions, and submit the queries plus a short write-up.
  • Whiteboard or verbal questions: you explain concepts such as join types or isolation levels, or sketch a query without running it.

In every format, say your assumptions out loud: how ties should rank, whether NULLs count, and which dialect you're writing in. Interviewers want to hear that reasoning, not only see the final query.

General SQL Interview Questions

Before the technical questions, your interviewer may ask about your overall experience with SQL.

Don't worry if your experience in SQL is limited: this is something your interviewer, most probably, already knows from your resume. Since they are interested in talking to you anyway, your profile was considered a good fit for their company. Also, it's perfectly fine if you have only worked with one SQL dialect. Remember that all SQL dialects are fairly similar. Therefore, being familiar with only one of them is a solid basis for you to learn any others.

1. What is SQL?

It stands for Structured Query Language, and it's a programming language used for interaction with relational database management systems (RDBMS). This includes fetching, updating, inserting, and removing data from tables.

2. What are SQL dialects? Give some examples.

The various versions of SQL, both free and paid, are called SQL dialects. They share the core ANSI/ISO standard syntax and differ mainly in extra functions, data types, and procedural extensions. Examples include the dialects of PostgreSQL, MySQL, SQLite, Oracle (PL/SQL), and Microsoft SQL Server (T-SQL).

3. What are the main applications of SQL?

Using SQL, we can:

  • create, delete, and update tables in a database
  • access, manipulate, and modify data in a table
  • retrieve and summarize the necessary information from a table or several tables
  • add or remove certain rows or columns from a table

SQL Interview Questions for Beginners

Interviewers usually open with definitions to check that you share their vocabulary:

4. What is an SQL statement?

Also known as an SQL command. It's a string of characters interpreted by the SQL engine as a legal command and executed accordingly. Some examples of SQL statements are SELECT, CREATE, DELETE, DROP, REVOKE, and so on.

5. What is an SQL query?

A query is a piece of code written in SQL to access or modify data from a database.

There are two types of SQL queries: queries for data retrieval and data modification. The first ones are used to retrieve the necessary data (this also includes limiting, grouping, ordering the data, extracting the data from multiple tables, etc.), while the second ones are used to create, add, delete, update, and rename the data.

6. What is an SQL subquery?

A subquery (also called an inner query) is a query placed inside another query (the outer query). It can appear in the SELECT, FROM, WHERE, and HAVING clauses, and inside INSERT, UPDATE, and DELETE statements. A non-correlated subquery runs once and passes its result to the outer query, while a correlated subquery references the outer query and is evaluated for each outer row (see question 70).

7. What is an SQL join?

A clause used to combine and retrieve records from two or multiple tables. SQL tables can be joined based on the relationship between the columns of those tables. Check out our SQL joins tutorial for more context, plus our dedicated guide to SQL joins interview questions. 

8. What is an SQL comment?

A human-readable clarification of what a particular piece of code does. SQL code comments can be single-line (preceded by a double dash --) or span over multiple lines (as follows: /*comment_text*/). When the SQL engine runs, it ignores code comments. The purpose of adding SQL code comments is to make the code easier to understand for people who read it later.

9. What is an SQL alias?

A temporary name given to a table or a column for the duration of a query. Aliases make code shorter and easier to read, and they're required when a table is joined to itself. An alias is introduced with the AS keyword:

SELECT c.first_name AS customer_name
FROM customers AS c;

Technical SQL Interview Questions

Now, let's move on to the technical SQL interview questions and some potential answers to them.

When answering technical questions, give precise, focused answers. Tangents rarely earn credit, and they can invite follow-up questions on topics you're less sure about.

All in all, SQL allows querying a database in multiple ways. In addition, SQL easily integrates with other programming languages, such as Python or R, so we can use their combined power.

10. What types of SQL commands do you know?

  • Data Definition Language (DDL) – to define and modify the structure of a database.
  • Data Manipulation Language (DML) – to access, manipulate, and modify data in a database.
  • Data Control Language (DCL) – to control user access to the data in the database and give or revoke privileges to a specific user or a group of users.
  • Transaction Control Language (TCL) – to control transactions in a database.
  • Data Query Language (DQL) – to perform queries on the data in a database to retrieve the necessary information from it.

11. Give some examples of common SQL commands.

  • DDL: CREATE, ALTER TABLE, DROP, TRUNCATE, and ADD COLUMN

  • DML: UPDATE, DELETE, and INSERT

  • DCL: GRANT and REVOKE

  • TCL: COMMIT, SET TRANSACTION, ROLLBACK, and SAVEPOINT

  • DQL: – SELECT

12. What is DBMS, and what types of DBMS do you know?

It stands for Database Management System, a software package used to perform various operations on the data stored in a database, such as accessing, updating, wrangling, inserting, and removing data. There are various types of DBMS, such as relational, hierarchical, network, graph, or object-oriented. These types are based on the way the data is organized, structured, and stored in the system.

13. What is RDBMS? Give some examples of RDBMS.

It stands for Relational Database Management System. It's the most common type of DBMS used for working with data stored in multiple tables related to each other by means of shared keys. The SQL programming language is designed to interact with RDBMS. Some examples of RDBMS are MySQL, PostgreSQL, Oracle, MariaDB, etc.

14. What are tables and fields in SQL?

A table is an organized set of related data stored in a tabular form, i.e., in rows and columns. A field is another term for a column of a table.

15. What types of SQL subqueries do you know?

  • Single-row – returns at most one row.
  • Multi-row – returns more than one row.
  • Multi-column – returns at least two columns.
  • Correlated – a subquery related to the information from the outer query.
  • Nested (non-correlated) – a subquery that doesn’t reference the outer query and can run on its own.

16. What is a constraint, and why use constraints?

A set of conditions defining the type of data that can be input into each column of a table. Constraints protect data integrity by rejecting values that break the rules.

17. What SQL constraints do you know?

  • DEFAULT – provides a default value for a column.

  • UNIQUE – allows only unique values.

  • NOT NULL – allows only non-null values.

  • PRIMARY KEY – allows only unique and strictly non-null values (NOT NULL and UNIQUE).

  • FOREIGN KEY – provides shared keys between two or more tables.

18. What types of joins do you know?

  • (INNER) JOIN – returns only those records that satisfy a defined join condition in both (or all) tables. It's a default SQL join.

  • LEFT (OUTER) JOIN – returns all records from the left table and those records from the right table that satisfy a defined join condition.

  • RIGHT (OUTER) JOIN – returns all records from the right table and those records from the left table that satisfy a defined join condition.

  • FULL (OUTER) JOIN – returns all records from both (or all) tables. It can be considered as a combination of left and right joins.

  • CROSS JOIN – returns every combination of rows from both tables (the Cartesian product), with no join condition.

  • Self join – joins a table to itself using two aliases (see question 69).

Note: FULL OUTER JOIN is supported by PostgreSQL, SQL Server, Oracle, and SQLite 3.39.0 and later. MySQL doesn't support it, so you emulate it by combining a LEFT JOIN and a RIGHT JOIN with UNION. Our SQL joins cheat sheet shows each join type side by side.

19. What is a primary key in SQL?

A column (or multiple columns) of a table to which the PRIMARY KEY constraint was imposed, so every value in that column is unique and non-null. In other words, a primary key is a combination of the NOT NULL and UNIQUE constraints. The primary key uniquely identifies each record of the table.

Related concept — Surrogate key: A surrogate key is an artificially generated identifier (typically a sequential integer or UUID) assigned to each record, independent of the actual data values. Unlike natural keys (e.g., an email address), surrogate keys remain stable when business data changes, making them a popular choice for primary keys in production databases.

Each table can have at most one PRIMARY KEY, which may span several columns (see question 59). Most engines don't strictly require one, but tables without a primary key are harder to update and join reliably.

20. What is a unique key in SQL?

A column (or set of columns) with a UNIQUE constraint, which blocks duplicate values. Unlike a primary key, a unique key can contain NULL values, and a table can have several unique keys.

Note: how many NULLs a unique column accepts depends on the database:

  • SQL Server: only one NULL, unless you use a filtered unique index.
  • PostgreSQL, MySQL, and Oracle: multiple NULLs, because one NULL is never equal to another. PostgreSQL 15 and later can reject them with UNIQUE NULLS NOT DISTINCT.

21. What is a foreign key in SQL? 

A column (or set of columns) that references the primary key, or another unique key, of a different table. The FOREIGN KEY constraint stops you from inserting a value that doesn't exist in the referenced table, which keeps related tables consistent (referential integrity). Read our guide to foreign keys for examples.

22. What is an SQL index?

A special data structure related to a database table and used for storing its important parts and enabling faster data search and retrieval. Indexes are especially efficient for large databases, where they significantly enhance query performance.

23. What types of indexes do you know?

  • Unique index – doesn't allow duplicates in a table column and hence helps maintain data integrity.
  • Clustered index – defines the physical order of records of a database table and performs data searching based on the key values. A table can have only one clustered index.
  • Non-clustered index – a separate structure that stores the indexed values with pointers to the table rows, so the physical order of the data doesn't change. A table can have multiple non-clustered indexes.

24. What is a schema?

A collection of database structural elements such as tables, stored procedures, indexes, functions, and triggers. It shows the overall database architecture, specifies the relationships between various objects of a database, and defines different access permissions for them. Read our database schema guide for a deeper understanding.

25. What is a SQL operator?

A reserved character, a combination of characters, or a keyword used in SQL queries to perform a specific operation. SQL operators are commonly used with the WHERE clause to set a condition (or conditions) for filtering the data.

26. What types of SQL operators do you know?

  • Arithmetic (+, -, *, /, etc.)

  • Comparison (>, <, =, >=, etc.)

  • Compound (+=, -=, *=, /=, etc.), available in SQL Server's T-SQL

  • Logical (AND, OR, NOT, BETWEEN, etc.)

  • String (the % and _ wildcards used with LIKE, and concatenation with || in PostgreSQL and Oracle or + in SQL Server)

  • Set (UNION, UNION ALL, INTERSECT, and MINUS (or EXCEPT))

27. What is a clause?

A clause is a part of a SQL statement that specifies what the statement does, such as which rows to filter or how to sort the result. Examples are WHERE, GROUP BY, HAVING, ORDER BY, and LIMIT.

28. What are some common statements used with the SELECT query?

The most common ones are FROM, GROUP BY, JOIN, WHERE, ORDER BY, LIMIT, and HAVING.

29. How do you create a table in SQL?

Using the CREATE TABLE statement. For example, to create a table with three columns of predefined datatypes, we apply the following syntax:

CREATE TABLE table_name (col_1 datatype,
                         col_2 datatype,
                         col_3 datatype);

30. How to update a table?

Using the UPDATE statement. The syntax is:

UPDATE table_name
SET col_1 = value_1, col_2 = value_2
WHERE condition;

31. How to delete a table from a database?

Using the DROP TABLE statement. The syntax is: DROP TABLE table_name;.

32. How to get the count of records in a table?

Using the COUNT() aggregate function with the asterisk passed as its argument: SELECT COUNT(*) FROM table_name;.

33. How to sort records in a table?

Using the ORDER BY statement:

SELECT * FROM table_name
ORDER BY col_1;

We can specify that we need a descending order using the DESC keyword; otherwise, the order will be ascending by default. Also, we can sort by more than one column and specify for each one, ascending or descending order separately. For example:

SELECT * FROM table_name
ORDER BY col_1 DESC, col_3, col_6 DESC;

34. What is the difference between UNION and UNION ALL?

Both combine the results of two or more SELECT statements into one result set. UNION removes duplicate rows, while UNION ALL keeps every row, which makes it faster because the database skips the deduplication step.

-- Customers who placed a large order or live in Berlin, each listed once
SELECT customer_id FROM orders WHERE amount > 500
UNION
SELECT customer_id FROM customers WHERE city = 'Berlin';

Use UNION ALL when duplicates can't occur or should be kept, such as when stacking monthly sales tables. Both queries must return the same number of columns with compatible types. Our UNION vs UNION ALL tutorial covers the edge cases.

35. How to select common records from two tables?

Using the INTERSECT statement:

SELECT col1, col2 FROM table_1
INTERSECT
SELECT col1, col2 FROM table_2;

Note: INTERSECT requires the same number of columns and compatible types.

36. What is the DISTINCT statement, and how do you use it?

This statement is used with the SELECT statement to filter out duplicates and return only unique values from a column of a table. The syntax is:

SELECT DISTINCT col_1
FROM table_name;

37. What are relationships? Give some examples.

Relationships are the connections and correlations between entities, basically meaning how two or more tables of a database are related to one another. For example, we can find an ID of the same client in a table on sales data and in a customer table.

38. What is a NULL value? How is it different from zero or a blank space?

A NULL value indicates the absence of data for a certain cell of a table. Instead, zero is a valid numeric value, and an empty string is a legal string of zero length.

39. What is the difference between SQL and NoSQL?

SQL databases are relational, structured, and use tables with predefined schemas, while NoSQL databases are non-relational, schema-less, and designed to handle unstructured or semi-structured data.

40. What is SQL injection, and how do you prevent it?

SQL injection is an attack where user input is pasted into a query string and runs as SQL. If an application builds "SELECT * FROM users WHERE name = '" + user_input + "'", an input such as ' OR '1'='1 returns every user in the table.

The fix is to never concatenate input into SQL:

  • Parameterized queries (prepared statements): the driver sends the query and the values separately, so input is always treated as data. In Python, for example: cursor.execute("SELECT * FROM users WHERE name = %s", (user_input,)).
  • Least-privilege accounts: the application's database user gets only the permissions it needs, which limits the damage of a successful attack.
  • Allowlists: values that can't be parameterized, such as a sort column chosen by the user, are checked against a fixed list.

The OWASP SQL Injection Prevention Cheat Sheet names prepared statements as the primary defense, and our SQL injection tutorial walks through attacks and defenses.

Intermediate SQL Interview Questions

Intermediate SQL interview questions test whether you can write and reason about multi-step queries: CTEs, window functions, set operators, views, normalization, and the differences between commands that look alike.

41. What is a Common Table Expression (CTE)?

A Common Table Expression (CTE) is a temporary named result set that you can reference within a SELECT, INSERT, UPDATE, or DELETE statement. CTEs improve query readability and allow you to break complex queries into simpler, reusable parts. The syntax uses the WITH keyword:

WITH sales_summary AS (
  SELECT product_id, SUM(amount) AS total_sales
  FROM sales
  GROUP BY product_id
)
SELECT p.product_name, s.total_sales
FROM products p
JOIN sales_summary s ON p.id = s.product_id
WHERE s.total_sales > 10000;

CTEs are particularly useful for recursive queries (hierarchical data like org charts) and when you need to reference the same subquery multiple times.

A recursive CTE references itself, which is how SQL walks a hierarchy of unknown depth. This query lists every employee with their level in the org chart:

WITH RECURSIVE org_chart AS (
  -- Anchor: start with the employee who has no manager
  SELECT id, name, manager_id, 1 AS level
  FROM employees
  WHERE manager_id IS NULL
  UNION ALL
  -- Recursive step: add the direct reports of the previous level
  SELECT e.id, e.name, e.manager_id, oc.level + 1
  FROM employees e
  JOIN org_chart oc ON e.manager_id = oc.id
)
SELECT name, level
FROM org_chart
ORDER BY level, name;

PostgreSQL, MySQL 8.0+, and SQLite require the RECURSIVE keyword, and SQLite accepts it but doesn’t require it. SQL Server leaves it out. Oracle also leaves it out but needs a column list after the CTE name, such as WITH org_chart (id, name, manager_id, lvl) AS (...), and level must be renamed because it’s a reserved word.

42. What are window functions, and how do they differ from aggregate functions?

Window functions perform calculations across a set of rows related to the current row, without collapsing the result into a single output row like aggregate functions do. They use the OVER() clause to define the window of rows. Keep our SQL window functions cheat sheet open while you practice.

Key window functions include:

  • ROW_NUMBER() – assigns a unique sequential number to each row
  • RANK() – assigns a rank with gaps for ties
  • DENSE_RANK() – assigns a rank without gaps for ties
  • LAG() / LEAD() – access data from previous/next rows
  • SUM() OVER(), AVG() OVER() – running or cumulative calculations

Example: Calculate running total of sales

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

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

All three are ranking window functions, but they handle ties differently:

  • ROW_NUMBER() – always assigns unique sequential numbers (1, 2, 3, 4...), even for ties
  • RANK() – assigns the same rank to ties, then skips numbers (1, 2, 2, 4...)
  • DENSE_RANK() – assigns the same rank to ties, without skipping (1, 2, 2, 3...)
SELECT 
  name, 
  score,
  ROW_NUMBER() OVER (ORDER BY score DESC) AS row_num,
  RANK() OVER (ORDER BY score DESC) AS score_rank,
  DENSE_RANK() OVER (ORDER BY score DESC) AS dense_score_rank
FROM students;

Use DENSE_RANK() when finding the "nth highest" value where ties should share the same position. Our SQL RANK() tutorial covers partitioned rankings.

44. What is a function in SQL?

A database object representing a set of SQL statements frequently used for a certain task. A function takes in some input parameters, performs calculations or other manipulations on them, and returns the result. Functions help improve code readability and avoid repetition of the same code snippets.

45. What types of SQL functions do you know?

  • Aggregate functions – work on multiple, usually grouped records for the provided columns of a table, and return a single value (usually by group).
  • Scalar functions – work on each individual value and return a single value.

On the other hand, SQL functions can be built-in (defined by the system) or user-defined (created by the user for their specific needs).

46. What SQL aggregate functions do you know?

  • AVG() – returns the average value

  • SUM() – returns the sum of values

  • MIN() – returns the minimum value

  • MAX() – returns the maximum value

  • COUNT() – returns the number of rows: COUNT(*) counts every row, while COUNT(column) skips rows where that column is NULL

47. What SQL scalar functions do you know?

  • LEN() (in other SQL dialects – LENGTH()) – returns the length of a string, usually including the blank spaces. SQL Server’s LEN() ignores trailing spaces; use DATALENGTH() to count them.

  • UCASE() (in other SQL dialects – UPPER()) – returns a string converted to the upper case

  • LCASE() (in other SQL dialects – LOWER()) – returns a string converted to the lower case

  • INITCAP() – returns a string converted to title case (i.e., each word of the string starts with a capital letter)

  • MID() (in other SQL dialects – SUBSTR()) – extracts a substring from a string

  • ROUND() – returns the numerical value rounded to a specified number of decimals

  • NOW() – returns the current date and time

48. What is the difference between CHAR and VARCHAR?

CHAR(n) stores fixed-length strings and pads shorter values with spaces up to n characters, while VARCHAR(n) stores variable-length strings up to n characters and uses only the space the value needs.

  • Use CHAR for values that always have the same length, such as two-letter country codes ('US', 'DE').
  • Use VARCHAR for values whose length varies, such as names, emails, or product titles.

In Oracle, the variable-length type is called VARCHAR2, which is why some interviewers ask about "CHAR vs VARCHAR2". PostgreSQL also offers TEXT, which has no length limit and performs the same as VARCHAR.

49. What are character manipulation functions in SQL?

Character manipulation functions represent a subset of character functions, and they're used to modify the text data.

  • CONCAT() – joins two or more string values, appending the second string to the end of the first one

  • SUBSTRING()/SUBSTR() – returns part of a string, given a start position and a number of characters

  • LENGTH() (in other SQL dialects – LEN()) – returns the length of a string, including the blank spaces

  • REPLACE() – replaces all occurrences of a defined substring in a provided string with another substring

  • INSTR() – returns the numeric position of a defined substring in a provided string

  • LPAD() and RPAD() – return the padding of the left-side/right-side character for right-justified/left-justified value

  • TRIM() – removes all the defined characters, as well as white spaces, from the left, right, or both ends of a provided string

50. What is a trigger in SQL?

A trigger is a stored block of SQL that the database runs automatically when a specified event happens on a table, such as an INSERT, UPDATE, or DELETE. Triggers fire BEFORE or AFTER the event and are commonly used for audit logs, business rules, and keeping derived columns in sync.

-- MySQL: record every salary change in an audit table
CREATE TRIGGER log_salary_change
AFTER UPDATE ON employees
FOR EACH ROW
INSERT INTO salary_audit (employee_id, old_salary, new_salary, changed_at)
VALUES (OLD.id, OLD.salary, NEW.salary, NOW());

Triggers run without the person issuing the query seeing them, so heavy trigger logic makes writes slower and harder to debug. Syntax differs by database: PostgreSQL, for example, attaches a trigger to a separate trigger function. Our SQL triggers guide covers each dialect.

51. What is the difference between SQL and PL/SQL?

SQL is a standard language for querying and managing relational databases. PL/SQL (Procedural Language/SQL) is Oracle's extension of SQL that adds procedural constructs such as variables, loops, conditions, and exception handling, so business logic can run inside the database. Our PL/SQL interview questions are a good review if the role uses Oracle.

52. What is the difference between LEFT JOIN and LEFT OUTER JOIN?

There is no difference between LEFT JOIN and LEFT OUTER JOIN. They are interchangeable. SQL allows the OUTER keyword to be optional, so LEFT JOIN is simply a shorthand for LEFT OUTER JOIN. Both return all records from the left table and the matching records from the right table.

53. What is indexing in SQL, and how does it improve performance?

Indexing creates a special data structure that speeds up data retrieval by allowing the database to find rows more efficiently. It works like an optimized lookup table, reducing the need for full table scans. However, excessive indexing can slow down insert, update, and delete operations due to the need for index maintenance. Our introduction to indexing in SQL shows how to create and test them.

54. What is a stored procedure, and how is it different from a function?

A stored procedure is a precompiled set of SQL statements executed as a unit to perform a task. Procedures can modify data or schema objects, manage transactions, and return zero or more result sets. Functions, on the other hand, are typically used in SQL expressions, must return a value (scalar or table-valued), and in many databases are restricted from side effects. Exact behavior differs by DB (e.g., T-SQL has scalar and table-valued functions; PostgreSQL distinguishes between functions and procedures).

55. What is the default data ordering with the ORDER BY statement, and how do you change it?

Default is ascending (NULLS FIRST/LAST varies by DB). Use ASC/DESC per column keyword as follows:

SELECT * FROM table_name 
ORDER BY col_1 DESC;

56. What are SQL set operators?

  • UNION – returns the records obtained by at least one of two queries (excluding duplicates)

  • UNION ALL – returns the records obtained by at least one of two queries (including duplicates)

  • INTERSECT – returns the records obtained by both queries

  • EXCEPT (called MINUS in Oracle, which also accepts EXCEPT from 21c; MySQL supports EXCEPT from 8.0.31) – returns only the records obtained by the first query but not the second one

57. What operator is used in the query for pattern matching?

The LIKE operator in combination with the % and _ wildcards. The % wildcard represents any number of characters including zero, while _ – strictly one character.

58. What is the difference between a primary key and a unique key in SQL?

While both types of keys ensure unique values in a column of a table, the first one uniquely identifies each record of the table, and the second one prevents duplicates in that column.

59. What is a SQL composite primary key?

The primary key of a table, based on multiple columns.

60. What is the typical order of SQL clauses in a SELECT statement?

SELECT – FROM – JOIN – ON – WHERE – GROUP BY – HAVING – ORDER BY – LIMIT

61. In which order does the interpreter execute the common statements in the SELECT query?

Here is the SQL order of execution: 

FROM → ON → JOIN → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT/OFFSET (FETCH)

SQL evaluates SELECT after it filters and groups the rows

62. What is a view in SQL?

A virtual table containing a subset of data retrieved from one or more database tables (or other views). Standard views store no data; materialized views do. Views can simplify queries, encapsulate logic, and, combined with privileges, restrict columns/rows. They can join/aggregate data from multiple tables.

63. Can we create a view based on another view in SQL?

Yes. This is also known as nested views. However, we should avoid nesting multiple views since the code becomes difficult to read and debug.

64. Can we still use a view if the original table is deleted?

Not in a usable way. In SQL Server, MySQL, and Oracle, the database lets you drop the table, but the dependent views become invalid and return an error when queried. PostgreSQL refuses to drop a table that a view depends on unless you add CASCADE, which drops the views too.

65. What types of SQL relationships do you know?

  • One-to-one – each record in one table corresponds to only one record in another table
  • One-to-many – each record in one table corresponds to several records in another table
  • Many-to-many – each record in both tables corresponds to several records in another table

66. What is the difference between EXISTS and IN?

IN checks whether a value matches any value in a list or subquery result, while EXISTS checks whether a subquery returns at least one row. EXISTS stops at the first match, and modern optimizers often produce the same plan for both in simple cases.

The difference interviewers usually look for is NOT IN with NULL values. If the subquery returns even one NULL, NOT IN returns no rows at all, because x NOT IN (1, NULL) evaluates to unknown rather than true:

-- Returns nothing if any orders.customer_id is NULL
SELECT name FROM customers
WHERE customer_id NOT IN (SELECT customer_id FROM orders);

-- Returns customers with no orders, regardless of NULLs
SELECT c.name FROM customers c
WHERE NOT EXISTS (
  SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id
);

Finding rows in one table with no match in another is called an anti-join. You can also write it as a LEFT JOIN with WHERE o.customer_id IS NULL. See our SQL EXISTS tutorial for more examples.

67. What is normalization in SQL?

Normalization is the process of organizing tables to reduce redundancy and avoid update anomalies, mostly by splitting data into related tables linked by keys. Interviewers usually ask about the first three normal forms:

  • First normal form (1NF): every column holds a single, atomic value, and there are no repeating groups (no phone_1, phone_2, phone_3 columns).
  • Second normal form (2NF): the table is in 1NF, and every non-key column depends on the whole primary key, not on part of a composite key.
  • Third normal form (3NF): the table is in 2NF, and no non-key column depends on another non-key column. For example, city shouldn't be stored next to zip_code when the zip code already determines it.

Higher forms such as Boyce-Codd normal form (BCNF) tighten these rules further, and our guide to normalization from 1NF through 5NF has worked examples. The trade-off is more joins at read time, which is why analytical databases often denormalize (see the next question).

68. What is denormalization in SQL?

Denormalization is the process opposite of normalization: it introduces data redundancy and combines data from multiple tables. Denormalization optimizes the performance of the database infrastructure in situations when read operations are more important than write operations since it helps avoid complex joins and reduces the time of query running.

69. What is a self join, and when would you use it?

A self join joins a table to itself, with two aliases so SQL can treat it as two tables. It's the standard way to query hierarchical or paired data stored in one table, such as employees and their managers:

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

The LEFT JOIN keeps employees without a manager, such as the CEO, whose manager value comes back as NULL. Other common uses are comparing rows within one table, such as pairs of products in the same category or flights between the same two cities.

70. What is the difference between nested and correlated subqueries?

A correlated subquery refers to values from the outer query, so it's evaluated once for each row of the outer query and can't run on its own. A non-correlated (nested) subquery doesn't depend on the outer query, runs once, and can be executed independently. Question 90 shows a correlated subquery in practice.

71. What is the difference between clustered and non-clustered indexes?

A clustered index determines the physical order in which a table's rows are stored, so the table data itself is the index. A non-clustered index is a separate structure that holds the key values plus pointers to the rows. A table can have only one clustered index but many non-clustered ones, and in SQL Server the primary key creates the clustered index by default.

72. What is the CASE() function?

The way to implement the if-then-else logic in SQL. This function sequentially checks the provided conditions in the WHEN clauses and returns the value from the corresponding THEN clause when the first condition is satisfied. If none of the conditions is satisfied, the function returns the value from the ELSE clause in case it's provided, otherwise, it returns NULL. The syntax is:

CASE
    WHEN condition_1 THEN value_1
    WHEN condition_2 THEN value_2
    WHEN condition_3 THEN value_3
    ...
    ELSE value
END;

73. What is the difference between the DELETE and TRUNCATE statements?

DELETE is a DML (Data Manipulation Language) command used to remove one or more rows from a table based on a condition in the WHERE clause. It is reversible only if wrapped in a transaction (via ROLLBACK).

TRUNCATE is a DDL (Data Definition Language) command that removes all rows at once by deallocating data pages instead of deleting row by row, so it's much faster on large tables. It can't take a WHERE clause, and most databases block it on tables referenced by a foreign key. Whether you can roll it back depends on the engine: PostgreSQL and SQL Server allow it inside a transaction, while MySQL and Oracle commit it immediately.

74. What is the difference between the DROP and TRUNCATE statements?

DROP deletes a table from the database completely, including the table structure and all the associated constraints, relationships with other tables, and access privileges. TRUNCATE deletes all rows from a table without affecting the table structure and constraints.  Both are DDL. DROP removes the table and its metadata; TRUNCATE deletes all rows but keeps the table definition. Performance and transactional behavior depend on the DB engine.

75. What is the difference between the HAVING and WHERE statements?

The first one works on aggregated data after they are grouped, while the second one checks each row individually. If both statements are present in a query, they appear in the following order:WHERE – GROUP BY – HAVING. The SQL engine also evaluates them in this order. Our tutorial on the difference between WHERE and HAVING has worked examples.

76. How do you add a record to a table?

Using the INSERT INTO statement in combination with VALUES. The syntax is:

INSERT INTO table_name
VALUES (value_1, value_2, ...);

77. How do you delete a record from a table?

Using the DELETE statement. The syntax is:

DELETE FROM table_name
WHERE condition;

In this way, we can also delete multiple records if they satisfy the provided condition.

78. How do you add a column to a table?

Using the ALTER TABLE statement in combination with ADD. The syntax is:

ALTER TABLE table_name
ADD column_name datatype;

79. How do you rename a column of a table?

Using the ALTER TABLE statement in combination with RENAME COLUMN ... TO ... The syntax is:

ALTER TABLE table_name
RENAME COLUMN old_column_name TO new_column_name;

80. How do you delete a column from a table?

Using the ALTER TABLE statement in combination with DROP COLUMN. The syntax is:

ALTER TABLE table_name
DROP COLUMN column_name;

81. How do you select all even or all odd records in a table?

By checking the remainder of division by 2. PostgreSQL, MySQL, SQL Server, and SQLite all support the modulo operator (%), and PostgreSQL, MySQL, and Oracle also provide the MOD() function (Oracle has only MOD()). To select all even records using MOD:

SELECT * FROM table_name
WHERE MOD(ID_column, 2) = 0;

To select all even records using %:

SELECT * FROM table_name 
WHERE ID_column % 2 = 0;

To select all odd records, the syntax is identical in both cases, only that we would use the inequality operator <> instead of =.

82. How to prevent duplicate records when making a query?

Using the DISTINCT statement in combination with SELECT or creating a unique key for that table.

83. How do you insert many rows in a table?

Using the INSERT INTO statement in combination with VALUES. The syntax is:

INSERT INTO table_name
VALUES (value_1, value_2, ...),
      (value_3, value_4, ...),
      (value_5, value_6, ...),
      ...;

84. How do you find the second highest salary, or the nth highest value in a column?

For the second highest value, the classic answer uses a subquery that finds the maximum among values below the overall maximum:

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

For any nth value, use a window function so ties are handled correctly:

SELECT column_name
FROM (
  SELECT column_name, DENSE_RANK() OVER (ORDER BY column_name DESC) AS rnk
  FROM table_name
) t
WHERE rnk = :n;

For the nth row by order (ignoring ties): ORDER BY column_name DESC OFFSET n-1 ROWS FETCH NEXT 1 ROW ONLY.

85. How do you find the values in a text column of a table that start with a certain letter?

Using the LIKE operator with the % wildcard, which matches any number of characters, including zero. For example, to find all surnames that start with "A":

SELECT * FROM table_name
WHERE surname LIKE 'A%';

To require at least 2 characters, add the _ wildcard, which matches exactly 1 character: LIKE 'A_%'. LIKE 'A_' matches only 2-character values such as "Al". Case sensitivity depends on the database: PostgreSQL's LIKE is case-sensitive (use ILIKE to ignore case), while MySQL and SQL Server compare case-insensitively under their default collations.

86. How do you find the last id in a table?

The simplest method is to use the aggregate function MAX().

SELECT MAX(id) AS highest_id
FROM table_name;

Using ORDER BY with LIMIT or TOP

SELECT id
FROM table_name
ORDER BY id DESC
LIMIT 1;

87. How to select random rows from a table?

Using the RAND() function in combination with ORDER BY and LIMIT. In some SQL dialects, such as PostgreSQL, it's called RANDOM(). For example, the following code will return five random rows from a table in MySQL:

SELECT * FROM table_name
ORDER BY RAND()
LIMIT 5;

In SQL Server, RAND() returns the same value for every row, so use SELECT TOP 5 * FROM table_name ORDER BY NEWID(); instead. On large tables, sorting every row is slow, and PostgreSQL and SQL Server offer TABLESAMPLE for approximate samples.

Advanced and Scenario-Based SQL Interview Questions

Scenario-based SQL interview questions give you a business problem and ask for a working query. Interviewers use them to see how you handle edge cases such as duplicates, NULL values, ties, and gaps in a sequence.

88. How do you find and remove duplicate records from a table?

Finding duplicates:

SELECT email, COUNT(*) AS duplicate_count
FROM users
GROUP BY email
HAVING COUNT(*) > 1;

Removing duplicates (keeping one record):

WITH duplicates AS (
  SELECT id, 
         ROW_NUMBER() OVER (PARTITION BY email ORDER BY id) AS rn
  FROM users
)
DELETE FROM users 
WHERE id IN (SELECT id FROM duplicates WHERE rn > 1);

This approach uses a CTE with ROW_NUMBER() to number the rows within each email, then deletes every row after the first, keeping the record with the lowest ID. Our guide to removing duplicates in SQL covers other methods.

89. How do you calculate a running total (cumulative sum)?

Use the SUM() window function with an ORDER BY clause:

SELECT 
  transaction_date,
  amount,
  SUM(amount) OVER (ORDER BY transaction_date) AS running_total
FROM transactions;

For a running total per category (e.g., per customer):

SELECT 
  customer_id,
  transaction_date,
  amount,
  SUM(amount) OVER (
    PARTITION BY customer_id 
    ORDER BY transaction_date
  ) AS customer_running_total
FROM transactions;

90. How do you find employees who earn more than the average salary in their department?

This is a classic correlated subquery scenario:

SELECT e.name, e.department, e.salary
FROM employees e
WHERE e.salary > (
  SELECT AVG(salary) 
  FROM employees 
  WHERE department = e.department
);

Alternatively, using a window function:

SELECT name, department, salary
FROM (
  SELECT 
    name, 
    department, 
    salary,
    AVG(salary) OVER (PARTITION BY department) AS dept_avg
  FROM employees
) t
WHERE salary > dept_avg;

91. How do you find gaps in a sequence of numbers (e.g., missing invoice numbers)?

Use LEAD() to compare each value with the next. Window functions can't appear in a WHERE clause, so compute the next value in a CTE first and filter in the outer query:

WITH numbered AS (
  SELECT
    invoice_number,
    LEAD(invoice_number) OVER (ORDER BY invoice_number) AS next_invoice
  FROM invoices
)
SELECT
  invoice_number,
  next_invoice,
  next_invoice - invoice_number - 1 AS gap_size
FROM numbered
WHERE next_invoice - invoice_number > 1;

Each output row marks the start of a gap. With invoices 1001, 1002, 1005, 1006, and 1010, the query returns 1002 followed by 1005 (2 missing) and 1006 followed by 1010 (3 missing). LAG() works the same way in the other direction, as our LAG() tutorial shows.

92. How do you find customers who made purchases in consecutive months?

Use LAG() to compare with the previous row:

WITH monthly_purchases AS (
  SELECT 
    customer_id,
    DATE_TRUNC('month', purchase_date) AS purchase_month,
    LAG(DATE_TRUNC('month', purchase_date)) OVER (
      PARTITION BY customer_id 
      ORDER BY DATE_TRUNC('month', purchase_date)
    ) AS prev_month
  FROM purchases
  GROUP BY customer_id, DATE_TRUNC('month', purchase_date)
)
SELECT DISTINCT customer_id
FROM monthly_purchases
WHERE purchase_month = prev_month + INTERVAL '1 month';

93. How do you pivot data from rows to columns?

Use conditional aggregation with CASE statements:

SELECT 
  product_name,
  SUM(CASE WHEN EXTRACT(MONTH FROM sale_date) = 1 THEN amount ELSE 0 END) AS jan_sales,
  SUM(CASE WHEN EXTRACT(MONTH FROM sale_date) = 2 THEN amount ELSE 0 END) AS feb_sales,
  SUM(CASE WHEN EXTRACT(MONTH FROM sale_date) = 3 THEN amount ELSE 0 END) AS mar_sales
FROM sales
GROUP BY product_name;

Some databases (SQL Server, Oracle) have native PIVOT syntax for this operation, which we cover in our guide to pivoting rows to columns in SQL.

94. How do you find the top 3 products by sales in each category?

Use DENSE_RANK() with PARTITION BY:

WITH ranked_products AS (
  SELECT 
    category,
    product_name,
    SUM(sales_amount) AS total_sales,
    DENSE_RANK() OVER (
      PARTITION BY category 
      ORDER BY SUM(sales_amount) DESC
    ) AS sales_rank
  FROM sales
  GROUP BY category, product_name
)
SELECT category, product_name, total_sales
FROM ranked_products
WHERE sales_rank <= 3
ORDER BY category, sales_rank;

Because DENSE_RANK() gives tied products the same rank, a category can return more than 3 rows. Use ROW_NUMBER() instead if the business needs exactly 3 per category, and say which one you chose and why.

95. What are ACID properties in database transactions?

ACID is an acronym for the four key properties that guarantee reliable database transactions:

  • Atomicity: A transaction is "all or nothing" – either all operations complete successfully, or none do
  • Consistency: A transaction brings the database from one valid state to another, maintaining all defined rules and constraints
  • Isolation: Concurrent transactions don't interfere with each other; each transaction sees a consistent snapshot of the data
  • Durability: Once a transaction is committed, the changes persist even if the system crashes

Example transaction:

BEGIN TRANSACTION;

UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;
UPDATE accounts SET balance = balance + 100 WHERE account_id = 2;

COMMIT;

Isolation is configurable. The SQL standard defines 4 isolation levels, and each one prevents more concurrency problems in exchange for more locking or retries:

Isolation levelDirty readsNon-repeatable readsPhantom reads
READ UNCOMMITTEDPossiblePossiblePossible
READ COMMITTEDPreventedPossiblePossible
REPEATABLE READPreventedPreventedPossible
SERIALIZABLEPreventedPreventedPrevented

Defaults differ: PostgreSQL, SQL Server, and Oracle use READ COMMITTED, while MySQL's InnoDB engine uses REPEATABLE READ. In MySQL, start a transaction with START TRANSACTION rather than BEGIN TRANSACTION.

96. What is a deadlock, and how do you prevent it?

A deadlock occurs when two or more transactions are waiting for each other to release locks, creating a circular dependency where neither can proceed.

Example scenario: Transaction A locks Table X and waits for Table Y, while Transaction B locks Table Y and waits for Table X.

A deadlock is two transactions each waiting for a lock the other holds

Prevention strategies:

  • Consistent lock ordering: Always acquire locks in the same order across all transactions
  • Keep transactions short: Commit or rollback as quickly as possible
  • Use appropriate isolation levels: Lower isolation levels reduce lock contention
  • Access only required data: Avoid locking unnecessary rows
  • Handle deadlock retries: Most databases automatically detect and resolve deadlocks by rolling back one transaction

97. How do you optimize a slow-running SQL query?

Start with the execution plan to find the slowest step, then fix what it shows. Our guide to SQL query optimization covers 15 techniques; these are the ones interviewers expect you to name:

  • Add appropriate indexes: Create indexes on columns used in WHERE, JOIN, and ORDER BY clauses

  • Analyze execution plans: Use EXPLAIN (PostgreSQL/MySQL) or EXPLAIN PLAN (Oracle) to identify bottlenecks

  • Avoid SELECT *: Only retrieve the columns you need

  • Use JOINs instead of subqueries: JOINs are often more efficient than correlated subqueries

  • Limit result sets: Use LIMIT/TOP when you don't need all rows

  • Avoid functions on indexed columns: WHERE YEAR(date_col) = 2026 can't use an index; use WHERE date_col >= '2026-01-01' AND date_col < '2027-01-01' instead

  • Consider partitioning: For very large tables, partition by date or category

98. How do you handle NULL values in calculations and comparisons?

NULL represents missing or unknown data and requires special handling:

  • Comparisons: Use IS NULL or IS NOT NULL instead of = NULL

  • COALESCE(): Returns the first non-NULL value: COALESCE(column, 'default')

  • NULLIF(): Returns NULL if two values are equal: NULLIF(a, b)

  • ISNULL() / NVL(): Database-specific functions to replace NULL values

SELECT 
  name,
  COALESCE(phone, email, 'No contact') AS contact_info,
  CASE WHEN status IS NULL THEN 'Unknown' ELSE status END AS status
FROM customers;

99. How do you find the longest streak of consecutive login days for a user?

This is an advanced "islands and gaps" problem:

WITH login_groups AS (
  SELECT 
    user_id,
    login_date,
    login_date - ROW_NUMBER() OVER (
      PARTITION BY user_id 
      ORDER BY login_date
    ) * INTERVAL '1 day' AS group_id
  FROM user_logins
)
SELECT 
  user_id,
  MIN(login_date) AS streak_start,
  MAX(login_date) AS streak_end,
  COUNT(*) AS streak_length
FROM login_groups
GROUP BY user_id, group_id
ORDER BY streak_length DESC
LIMIT 1;

The trick is subtracting a row number from each date: consecutive dates produce the same group_id. This is PostgreSQL syntax (in MySQL, use DATE_SUB(login_date, INTERVAL rn DAY) with the row number in a subquery). The query returns the single longest streak across all users; remove LIMIT 1 to see every user's streaks.

Upskilling Your Team with SQL

Interview prep covers one hire at a time. If your whole team works with data, regular SQL training keeps everyone's queries correct and consistent, from the analyst writing a first GROUP BY to the engineer tuning a slow join.

If you’re a team leader or business owner who wants your whole team to be proficient in SQL, DataCamp for Business offers tailored training programs that can help your employees master SQL skills, from the basics to advanced concepts. We can provide:

  • Targeted learning paths: Customizable to your team’s current skill level and business needs.
  • Hands-on practice: Real-world scenarios and exercises that reinforce learning and improve retention.
  • Progress tracking: Tools to monitor and assess your team’s progress, ensuring they achieve their learning goals.

Teams that learn from the same material also write SQL the same way, which makes shared queries easier to review. Talk to our team and request a demo.

Final Thoughts

The SQL interview questions that separate candidates in 2026 are the ones with edge cases: ties in a ranking, a NULL inside a NOT IN, duplicates that have to go without losing the original row. Definitions get you through the first round, and talking through those edge cases out loud gets you through the rest.

My advice is to rewrite each query in this article from memory, in the dialect your target employer uses, then change the data and check that the answer still holds. Our guide on how to practice SQL lists free datasets and tools for that.

For structured practice, I recommend our Joining Data in SQL and PostgreSQL Summary Stats and Window Functions courses, or browse our full list of SQL courses:

FAQs

How can I start learning SQL?

Start with how relational databases store data in tables, then learn to write SELECT queries with filtering, sorting, and aggregation before moving on to joins. Our Introduction to SQL course covers the basics in about 2 hours, and the Associate Data Analyst in SQL career track takes you from there to job-ready analysis. Keep the SQL Basics cheat sheet nearby, or browse all SQL courses.

Where can I find real-world SQL problems to practice?

On the DataCamp platform there are many SQL projects to hone your skills, suitable for all levels.

What are some common SQL interview questions for beginners?

Beginner SQL interview questions ask you to define core terms and write single-table queries. Expect questions on what SQL and an RDBMS are, primary vs foreign keys, the types of joins, WHERE vs HAVING, DELETE vs TRUNCATE vs DROP, UNION vs UNION ALL, and how NULL differs from zero. Questions 1 to 40 in this article cover them.

What are some common SQL interview questions for intermediate practitioners?

Intermediate practitioners might face questions on more complex SQL concepts such as joins (INNER, LEFT, RIGHT, FULL), subqueries, aggregations and grouping data (GROUP BY), and the use of set operations like UNION, INTERSECT, and EXCEPT. They may also be asked to solve problems that involve optimizing queries for performance.

How should I prepare for an SQL interview?

Preparation for an SQL interview should include:

  • Reviewing SQL basics and advanced concepts.
  • Practicing writing queries to solve common problems.
  • Understanding database design and normalization.
  • Familiarizing yourself with the specific SQL dialect that the employer uses (e.g., PostgreSQL, MySQL, SQL Server).
  • Solving sample interview questions and problems available online.
What should I expect in a technical SQL interview and how can I best demonstrate my skills?

Technical SQL interviews test definitions, query writing, and scenario-based problems involving joins, subqueries, and window functions with edge cases like NULLs and ties. Demonstrate skills by writing precise queries, explaining assumptions aloud (tie-breaking, NULL handling, dialect), and reasoning clearly through live coding, take-home, or whiteboard formats.

How important is it to learn specific SQL dialects, and which ones should I focus on?

Learning the dialect a target employer uses matters because differences like LIMIT vs TOP or EXCEPT vs MINUS trip up candidates. SQL dialects share core ANSI/ISO syntax, so focus on PostgreSQL, MySQL, SQL Server, Oracle, or SQLite based on the role, then adapt from there.

Does DataCamp have extra FREE resources to prepare for SQL interviews?

Yes! If you are currently a university teacher or student, you can use DataCamp Classrooms to get our entire premium catalog for FREE. This includes our SQL tracks and certifications.

You may also take a look at our free SQL Basics and SQL Window Functions cheat sheets.

What are the most important SQL topics to study for interviews in 2026?

Focus on these key areas: (1) Joins and subqueries – understand INNER, LEFT, RIGHT, and FULL joins, plus correlated vs non-correlated subqueries; (2) Window functions – ROW_NUMBER, RANK, DENSE_RANK, LAG, LEAD, and running totals; (3) CTEs (Common Table Expressions) – for readable, maintainable queries; (4) Aggregations and GROUP BY – including HAVING clause usage; (5) Query optimization – indexing strategies and execution plans.

What is the difference between ROW_NUMBER, RANK, and DENSE_RANK?

All three are ranking window functions, but they handle ties differently: ROW_NUMBER() assigns unique sequential numbers even for ties (1, 2, 3, 4); RANK() gives the same rank to ties but skips subsequent numbers (1, 2, 2, 4); DENSE_RANK() gives the same rank to ties without skipping (1, 2, 2, 3). Use DENSE_RANK when finding the "nth highest" value where ties should share the same position.

What SQL questions are asked in a data analyst interview?

Data analyst SQL interviews focus on query writing over theory. Expect joins and GROUP BY with HAVING, CASE expressions, date handling, and window functions for rankings, running totals, and month-over-month changes. Typical prompts are "find the top 3 products in each category", "find customers with no orders", and "remove duplicate records", all covered in this article. Our guide on how to prepare for a data analyst interview covers the rest of the process.

What is the difference between SQL and MySQL?

SQL is the language for querying relational databases, while MySQL is one relational database management system (RDBMS) that uses its own dialect of SQL. PostgreSQL, SQL Server, Oracle, and SQLite are other RDBMSs with their own dialects. If the role uses MySQL, our MySQL interview questions cover its specifics.

Elena Kosourova

लेखक

Elena Kosourova

IBM Certified Data Scientist (2020), previously Petroleum Geologist/Geomodeler of oil and gas fields worldwide with 12+ years of international work experience. Proficient in Python, R, and SQL. Areas of expertise: data cleaning, data manipulation, data visualization, data analysis, data modeling, statistics, storytelling, machine learning. Extensive experience in managing data science communities and writing/reviewing articles and tutorials on data science and career topics.

विषय

संबंधित

ब्लॉग

Top 30 SQL Server Interview Questions (2026)