Show me the different ways to say 'give me the top ten rows' across the common SQL dialects.
There is no single standard spelling, which is why this comes up in almost every SQL interview. SQL Server has its own TOP keyword, MySQL and SQLite and PostgreSQL use LIMIT, SQL Server's modern syntax uses OFFSET/FETCH, and Oracle 12c and later use FETCH FIRST. Only LIMIT and OFFSET are close to the standard.
CREATE TABLE products (
id INTEGER PRIMARY KEY,
name VARCHAR(120) NOT NULL,
unit_price DECIMAL(10, 2) NOT NULL
);
INSERT INTO products (id, name, unit_price) VALUES
(1, 'Mechanical Keyboard', 79.50),
(2, 'USB-C Hub', 32.00),
(3, '27-inch Monitor', 249.99),
(4, 'Standing Desk', 419.00);
-- SQLite, PostgreSQL, MySQL:
SELECT name, unit_price FROM products ORDER BY unit_price DESC LIMIT 3;
-- SQL Server (legacy TOP):
-- SELECT TOP (3) name, unit_price FROM products ORDER BY unit_price DESC;
-- SQL Server (modern OFFSET/FETCH, ORDER BY is mandatory):
-- SELECT name, unit_price FROM products ORDER BY unit_price DESC
-- OFFSET 0 ROWS FETCH NEXT 3 ROWS ONLY;
-- Oracle 12c and later:
-- SELECT name, unit_price FROM products ORDER BY unit_price DESC FETCH FIRST 3 ROWS ONLY;The runnable statement returns three rows: the Standing Desk at 419.00, the 27-inch Monitor at 249.99 and the Mechanical Keyboard at 79.50. The commented lines are the same request in the other dialects.
Two Oracle-specific cautions. Before 12c, Oracle had no row-limiting clause at all — you had to wrap the query in a subquery and filter on ROWNUM, and ROWNUM is assigned before the ORDER BY runs, so the classic WHERE ROWNUM <= 3 pattern returns three arbitrary rows rather than the top three after sorting. That bug is still taught in interviews. And Oracle's FETCH FIRST requires the ORDER BY to come before it, unlike the LIMIT clause in SQLite where the order of the keywords is LIMIT then OFFSET.
One more difference worth flagging: SQL Server's TOP accepts a variable or a parenthesised expression and can be combined with PERCENT, which LIMIT cannot do. If a report needs the top 10 percent of customers, that is a genuinely different piece of work on each engine.