Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Strong SQL interview answers explain both what a query returns and why. These questions cover SELECT structure, filtering, grouping, joins, set operations, subqueries, common table expressions, ordering, and practical query problems. Examples use broadly shared SQL syntax where possible; check row-limiting and other dialect-specific syntax against your target database.

What SQL questions are asked in interviews?

Interviewers commonly test whether you can read query structure, reason about rows and groups, combine data correctly, and make results predictable. Be ready to describe your approach before writing a query, state assumptions about ties or duplicates, and name the database dialect when syntax may vary.

What is the general shape of a SELECT query?

A SELECT statement returns expressions from rows supplied by its table expressions. A typical query is written in this order:

SELECT department_id, COUNT(*) AS employee_count
FROM employees
WHERE salary > 0
GROUP BY department_id
HAVING COUNT(*) > 1
ORDER BY employee_count DESC;
  • FROM identifies the input tables or other table expressions.
  • WHERE filters input rows.
  • GROUP BY forms groups for aggregate calculations.
  • HAVING filters those groups.
  • SELECT specifies the output expressions.
  • ORDER BY requests a sort; a row-limiting clause can restrict the returned rows.

PostgreSQL 17 describes a logical processing sequence that helps explain these roles: inputs are established, rows filtered, groups formed and filtered, output expressions computed, and results ordered and limited. This is an explanatory model, not a promise about the database’s physical execution plan. See the PostgreSQL 17 SELECT documentation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

What does GROUP BY do?

GROUP BY divides input rows into groups sharing the same value or values for the grouping expressions. Aggregate functions such as COUNT, SUM, and AVG can then produce a result per group. For example, this returns a total per customer:

SELECT customer_id, SUM(amount) AS total_spend
FROM orders
GROUP BY customer_id;

Selected nonaggregate expressions must comply with the grouping rules of the database. In a typical grouped query, an output expression is either aggregated or represented by the grouping key.

What is the difference between WHERE and HAVING?

WHERE filters individual rows before grouping; HAVING filters groups after aggregate values are available. Put an aggregate condition such as “keep customers whose total exceeds 1,000” in HAVING:

SELECT customer_id, SUM(amount) AS total_spend
FROM orders
WHERE order_date >= DATE '2026-01-01'
GROUP BY customer_id
HAVING SUM(amount) > 1000;

Here, WHERE first limits the input orders by date, and HAVING then keeps only customer groups whose summed amount passes the threshold. Microsoft’s SELECT examples show WHERE, GROUP BY, and HAVING used together.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

How do INNER JOIN and LEFT JOIN differ?

An INNER JOIN returns row combinations that satisfy its join condition. A LEFT JOIN preserves every row from its left input and supplies nulls for right-side columns when there is no match. Use a join when the result needs columns from related table inputs.

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

This keeps customers even if they have no order. Predicate placement matters: a condition on the right table in ON can restrict which rows match while preserving unmatched left rows; moving that condition to WHERE can filter out null-extended rows and change the result. Explain which behavior the question requires. Joins are part of the table-expression portion of a query; consult the target engine’s documentation for its detailed semantics, including the PostgreSQL SELECT reference or Microsoft SELECT documentation.

What is the difference between UNION and UNION ALL?

Both set operators combine the results of compatible queries; their duplicate handling differs. The inputs need corresponding columns that can be combined by the database.

Operator Result behavior Use it when
UNION Combines rows and removes duplicate result rows. You want a distinct combined result.
UNION ALL Combines rows while retaining duplicates. Repeated rows are meaningful or should remain in the output.
SELECT email FROM customers
UNION ALL
SELECT email FROM prospects;

Use UNION instead if duplicate result rows should be removed. PostgreSQL documents set operators in its SELECT reference; Microsoft illustrates the behavior in its SELECT examples. Set operators act on result sets, unlike joins, which combine related table inputs within a query.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

What is a common table expression (CTE)?

A common table expression is a named query introduced with WITH, available to the statement that follows it. It can make a multi-stage query easier to read without changing its intended result:

WITH customer_totals AS (
  SELECT customer_id, SUM(amount) AS total_spend
  FROM orders
  GROUP BY customer_id
)
SELECT customer_id, total_spend
FROM customer_totals
WHERE total_spend > 1000;

A CTE is a way to organize a query, not a blanket performance optimization. PostgreSQL 17 documents cases where a multiply referenced WITH query is computed once unless NOT MATERIALIZED is specified; do not assume the same planning behavior across engines. See the PostgreSQL 17 SELECT documentation.

Why should you use ORDER BY?

Without ORDER BY, SQL does not promise a stable row order. If an interviewer asks for the latest orders or a top-N result, state the sort rule explicitly. Include a tie-breaker when the primary sort key can match across rows:

SELECT order_id, customer_id, order_date
FROM orders
ORDER BY order_date DESC, order_id DESC;

The second key makes ordering more specific when dates are equal. PostgreSQL states that absent ORDER BY, rows can be returned in whatever order the system finds fastest to produce; an order observed in one run is not a guarantee. See its SELECT documentation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

How do you find the highest-paid employee in each department?

First decide what should happen when employees tie for the highest salary. To return exactly one employee per department, use ROW_NUMBER() with a stable employee identifier as a tie-breaker, then keep row 1. The following illustrates the pattern; confirm window-function and row-limiting syntax for the target database.

WITH ranked_employees AS (
  SELECT employee_id, department_id, salary,
         ROW_NUMBER() OVER (
           PARTITION BY department_id
           ORDER BY salary DESC, employee_id
         ) AS rn
  FROM employees
)
SELECT employee_id, department_id, salary
FROM ranked_employees
WHERE rn = 1;

Because the sort includes employee_id, this chooses one row deterministically among equal salaries, rather than returning every employee tied for first. If the requirement is to return all top-paid ties, use a ranking approach that preserves ties instead, and verify its syntax for the chosen dialect.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

How do you find duplicate values?

Define what “duplicate” means before writing the query. To find email addresses used more than once:

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

Grouping by email finds repeated email values; grouping by every column instead tests for repeated full rows. The HAVING condition filters groups by their count. Microsoft’s SELECT examples include aggregate filtering with HAVING.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

What is the difference between a join and a subquery?

A join relates table inputs in the query’s table-expression portion. A subquery is a query nested inside another query, where it may provide a scalar value, a set of rows, or an existence test. Some tasks can be expressed either way; choose the form that makes the intended relationship and result clearest, then consider the target engine.

For example, a subquery can test whether a customer has any orders:

SELECT c.customer_id
FROM customers AS c
WHERE EXISTS (
  SELECT 1
  FROM orders AS o
  WHERE o.customer_id = c.customer_id
);

Microsoft’s SELECT examples demonstrate joins, subqueries, and correlated subqueries.

How do I prepare for a SQL interview?

Practise explaining the result and the reasoning, not just memorizing query shapes. Use small sample tables to check edge cases such as missing matches, duplicate values, tied scores, and groups with only one row.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Clarify the requested result. Identify output columns, row-level conditions, grouping keys, and whether duplicate rows or tied results should be retained.
  2. Choose the query structure. Decide whether the task needs related table inputs, a nested query, a CTE, grouping, or a set operator.
  3. Place conditions at the right stage. Filter input rows with WHERE; filter aggregate groups with HAVING.
  4. Make ordering and ties explicit. Add ORDER BY for ordered output and a tie-breaker when a single deterministic row is required.
  5. Name the SQL dialect. PostgreSQL and SQL Server share many SELECT fundamentals but differ in details. PostgreSQL documents LIMIT/FETCH forms, while SQL Server documents TOP; verify syntax and behavior for the database and version you will use. See the PostgreSQL 17 reference and SQL Server SELECT reference.

For practice, solve a customer-total problem with a threshold, find duplicate emails, combine two compatible result sets both with and without deduplication, and return the most recent order per customer with an explicit tie-breaker. For each, say what happens at the boundaries before you present the query.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.