Skip to content

SELECT

Returns rows from one or more tables or stored queries.

Access SQL, with LibRed extensions. ACE accepts the core of this statement. Several clauses are LibRed extensions, which ACE has no syntax for; each is marked LibRed extension where it is described below.

SELECT [ ALL | DISTINCT | DISTINCTROW ]
[ TOP n [ PERCENT ] [ WITH TIES ] ]
select_item [ , … ]
[ FROM table_source [ , … ] [ IN external_database ] ]
[ WHERE condition ]
[ GROUP BY expression [ , … ] ]
[ HAVING condition ]
[ { UNION [ ALL ] | INTERSECT | EXCEPT } query_term ] [ … ]
[ ORDER BY expression [ ASC | DESC ] [ , … ] ]
[ OFFSET offset { ROW | ROWS } ]
[ FETCH { FIRST | NEXT } count { ROW | ROWS } { ONLY | WITH TIES } ]
[ WITH OWNERACCESS OPTION ]

A select_item is one of:

*
table_name.*
expression [ [ AS ] alias ]

A table_source is a table, a query or a parenthesised join, followed by any number of joins:

table_name [ [ AS ] alias ]
( query ) [ [ AS ] alias [ ( column_name [ , … ] ) ] ]
( table_source )
[ INNER | LEFT [ OUTER ] | RIGHT [ OUTER ] | FULL [ OUTER ] ] JOIN table_source ON condition
CROSS JOIN table_source
CROSS APPLY table_source
OUTER APPLY table_source

A query_term, the operand of a set operation, is one of:

SELECT … -- without ORDER BY, OFFSET or FETCH
( query )
TABLE table_name
VALUES ( value [ , … ] ) [ , … ]

Which rows to return. ALL is the default and returns every row. DISTINCT leaves out rows whose output columns repeat an earlier row’s.

DISTINCTROW leaves out rows that repeat the same underlying row of the tables that supply the output columns. It makes a difference only when the output comes from some of the joined tables but not all of them: SELECT DISTINCTROW Customers.Country FROM Customers INNER JOIN Orders … returns one row per customer that has orders, where DISTINCT returns one row per country.

Returns the first n rows of the result in ORDER BY order. With PERCENT, returns n percent of the rows, rounded up.

n is an integer literal in Access SQL. LibRed extension: n may also be a parameter (TOP @n), a parenthesised expression (TOP (2 + 1)), or a sum or difference of literals and parameters. Parameters are named (@n); a positional ? is refused, because LibRed takes named parameters only.

LibRed extension: WITH TIES also returns every further row whose ORDER BY keys equal the last returned row’s. It needs an ORDER BY, it cannot be combined with DISTINCT or DISTINCTROW, and a view cannot store it.

In a set operation, a TOP belongs to its own operand: SELECT TOP 5 … UNION SELECT TOP 5 … takes five rows from each side.

A column or value to return. Each item is one of:

  • *: every column of every table in the FROM clause.
  • table_name.*: every column of that table.
  • An expression, optionally named by alias. An expression can be a column, a literal, an operator expression, a function call, a CASE expression or a subquery that returns one value.

A bare * may stand among other items, in any position (SELECT ProductName AS Name, *). The other items come first, then every column that none of them already returns. A * in a grouped or aggregate query is refused.

SELECT needs no FROM clause. Without one it returns one row: SELECT 2 + 3 AS Five.

Each output column is named as ACE names it:

  • An item with an alias keeps it, even when two items have the same alias.
  • A column reference is named after the column. If the same column is written twice, every copy but the last gets an Expr name.
  • An unnamed expression is Expr1000 and up, numbered by its place in the select list: the second item is Expr1001.
  • Two outputs that would still share a name are told apart by their table: Orders.CustomerID, Customers.CustomerID.
  • A reference written with Access’s bang, Customers!CompanyName, is named as written.

A table or a stored query. A table and its alias are separated by AS or a space.

( query ) [ [ AS ] alias [ ( column_name [ , … ] ) ] ]

Section titled “( query ) [ [ AS ] alias [ ( column_name [ , … ] ) ] ]”

A derived table: a query in parentheses, used as a table.

LibRed extension: the column list after the alias names the derived table’s columns in order: (VALUES (1, 'a'), (2, 'b')) AS v(n, s). A view cannot store one.

FROM a, b pairs every row of a with every row of b (a cartesian product). Put the join condition in the WHERE clause.

Returns the pairs of rows for which condition is true. INNER is optional.

Returns the inner join’s rows, plus every row of the left (or right) table that matched nothing, with Null in the other table’s columns.

LibRed extension. Returns the inner join’s rows, plus the unmatched rows of both tables. ACE has no full outer join. Because FULL is a keyword here, a column named Full has to be bracketed: [Full].

LibRed extension. Pairs every row with every row, as a comma does. It takes no ON. Access has no CROSS JOIN keyword, and writes a cartesian product as a comma-separated list.

LibRed extension. A lateral join. The right side is evaluated once per left row, with that row’s columns in scope, so it may refer to the left side, which an ordinary join’s right side may not. CROSS APPLY drops a left row whose right side returns no rows; OUTER APPLY keeps it, with Null in the right side’s columns. Neither takes an ON: the correlation inside the right side is the condition.

Parentheses group joins: (a INNER JOIN b ON …) INNER JOIN c ON …. LibRed evaluates them as they nest; see Differences from ACE.

Reads every table of the FROM clause from another Access database. It ends the whole FROM clause: it comes after any alias and before WHERE, once per FROM. LibRed takes the forms ACE takes:

IN 'C:\Data\Archive.accdb'
IN 'C:\Data\Archive.accdb' 'MS Access;'
IN 'C:\Data\Archive.accdb' [MS Access;]
IN '' [;DATABASE=C:\Data\Archive.accdb]
IN '' [MS Access;DATABASE=C:\Data\Archive.accdb]

FROM a IN 'x', b is a syntax error; write FROM a, b IN 'x', which reads both tables from x. A stored query of the other file can be named too, and runs there. A subquery elsewhere in the statement still reads the statement’s own database.

Keeps only the rows for which condition is true. A row for which it is False or Null is left out.

Combines the rows with equal values in the listed expressions into one row each. Every item in the select list must then be a grouping expression, an aggregate (COUNT, SUM, AVG, MIN, MAX, First, Last …), or an expression over these.

Keeps only the groups for which condition is true. It may use aggregates.

LibRed extension. ACE has no window functions.

function ( [ argument [ , … ] ] ) [ FILTER ( WHERE condition ) ]
OVER ( [ PARTITION BY expression [ , … ] ]
[ ORDER BY expression [ ASC | DESC ] [ , … ] ]
[ frame ] )

where frame is

{ ROWS | RANGE | GROUPS } { start | BETWEEN start AND end }
[ EXCLUDE { CURRENT ROW | GROUP | TIES | NO OTHERS } ]

and start and end are each UNBOUNDED PRECEDING, n PRECEDING, CURRENT ROW, n FOLLOWING or UNBOUNDED FOLLOWING.

ROW_NUMBER(), RANK(), DENSE_RANK(), NTILE(n), PERCENT_RANK(), CUME_DIST(), LAG/LEAD(x [, offset [, default]]), FIRST_VALUE, LAST_VALUE, NTH_VALUE(x, n) [ FROM FIRST | FROM LAST ], or an aggregate. LAG, LEAD, FIRST_VALUE, LAST_VALUE and NTH_VALUE take RESPECT NULLS or IGNORE NULLS before the OVER.

Divides the rows into partitions, and the function runs over each separately. Without it the whole result is one partition.

Orders the rows within each partition.

The rows of the partition that a frame-reading function (an aggregate, FIRST_VALUE …) sees from the current row. A lone start ends the frame at the current row. A RANGE offset measures a number or date ORDER BY key, a date in days. Without a frame, a window with an ORDER BY runs to the current row and its peers, and one without an ORDER BY covers the whole partition.

The words these clauses add are not reserved, so a column named Range or Current still works unbracketed.

Over a grouped query the windows run over the groups that HAVING keeps, so RANK() OVER (ORDER BY COUNT(*) DESC) ranks the groups.

LibRed extension. FILTER limits an aggregate, grouped or windowed, to the rows for which condition is true: COUNT(*) FILTER (WHERE UnitPrice > 50). WITHIN GROUP (ORDER BY …) gives an ordered-set aggregate (PERCENTILE_CONT, PERCENTILE_DISC, LISTAGG) its ordering.

ORDER BY expression [ ASC | DESC ] [ , … ]

Section titled “ORDER BY expression [ ASC | DESC ] [ , … ]”

Sorts the result. ASC is the default.

ORDER BY orders the whole query: after a set operation it sorts the result of the set operation, not its last operand. An operand that needs its own ordering, for a TOP say, must be in parentheses: (SELECT TOP 3 … ORDER BY …) UNION ALL (SELECT TOP 3 … ORDER BY …).

LibRed extension. Skips the first offset rows.

FETCH { FIRST | NEXT } count { ROW | ROWS } { ONLY | WITH TIES }

Section titled “FETCH { FIRST | NEXT } count { ROW | ROWS } { ONLY | WITH TIES }”

LibRed extension. Returns at most count rows, after any OFFSET. FIRST and NEXT mean the same, as do ROW and ROWS. WITH TIES has the meaning it has after TOP.

offset and count may be any expression, not only a literal.

Returns the rows of both queries. UNION leaves out duplicate rows; UNION ALL keeps them. The output columns are named by the first query.

LibRed extension. INTERSECT returns the distinct rows both queries return. EXCEPT returns the distinct rows of the first query that the second does not return. Access has neither.

Every column of the table, as SELECT * FROM table_name. It can stand alone or as a set operation’s operand.

LibRed extension. A table value constructor: one row per parenthesised list. It can stand in for a query in a set operation or a derived table. Its columns are named by the first query of the set operation, or by a derived table’s column list.

A query in parentheses can stand in several places. Each holds a full query, so it may itself be a set operation.

( query ) as a value, in the select list or a condition. It may return at most one row; more is an error, “At most one record can be returned by this subquery.” No row gives Null.

A subquery that stands for a value, here or after IN or a comparison with ANY, SOME or ALL, must name one field. One that names more is refused before anything runs, even when no row would reach it: “You have written a subquery that can return more than one field without using the EXISTS reserved word in the main query’s FROM clause. Revise the SELECT statement of the subquery to request only one field.” An EXISTS subquery may name any number of fields.

True when expression equals a value in the subquery’s one column. IN also takes a list of values: Country IN ('Norway', 'Finland').

True when the subquery returns at least one row.

expression comparison { ANY | SOME | ALL } ( query )

Section titled “expression comparison { ANY | SOME | ALL } ( query )”

Compares expression with each row of a one-column subquery, using =, <>, <, <=, > or >=. ANY (or SOME) is true when one comparison is, ALL when every one is. Over no rows ANY is False and ALL is True, whatever expression is. Otherwise, a Null that leaves the answer undecided makes it Null. The subquery cannot be replaced by a list of values.

LibRed extension: a set operation inside a subquery predicate (IN (… UNION …), EXISTS (… EXCEPT …)) or a scalar subquery.

LibRed extension. Standard SQL CASE, in both forms:

CASE WHEN condition THEN result [ WHEN … ] [ ELSE result ] END
CASE operand WHEN value THEN result [ WHEN … ] [ ELSE result ] END

Without an ELSE, a CASE that matches nothing is Null. In Access SQL, write nested IIf calls instead.

LibRed extension. COALESCE(a, b, …) returns the first argument that is not Null. NULLIF(a, b) returns Null when a equals b, and a otherwise. GREATEST and LEAST are also available. The functions LibRed supports, Access’s and its own, are listed in docs/functions.md.

Runs the query with its owner’s permissions. LibRed has no users to act for, so it changes nothing when the query runs, but a stored query keeps it. It ends the query, after any ORDER BY, and appears once.

A name that is a reserved word or contains a space goes in square brackets or backticks: [Order Details]. Access’s bang joins a table and column as a dot does: Customers!CompanyName is Customers.CompanyName.

A command runs one statement. To declare a query’s parameters, see PARAMETERS.

  • TOP n returns exactly n rows. ACE’s TOP n, and TOP n PERCENT, also returns every further row whose ORDER BY keys equal the last one’s, a stored query ACE wrote included. Add WITH TIES to get ACE’s rows.
  • Nested joins are evaluated as their parentheses nest them. An inner join on a column of an outer join’s optional side ((a LEFT JOIN b ON …) INNER JOIN c ON b.x = c.x), and an inner join nested as an outer join’s operand (a LEFT JOIN (b INNER JOIN c ON …) ON …), each return the rows standard SQL defines. ACE refuses both with “JOIN expression not supported”.
  • Any condition may stand in an ON. ACE refuses an ON that does not refer to both sides (… INNER JOIN c ON c.k = 1) with the same message. LibRed takes any condition, constants, functions and subqueries included, and evaluates it as written.
  • NOT over a quantified comparison is its negation. ACE turns NOT (x < ALL (…)) into x >= ALL (…), which is not the negation, for every comparison but =.
  • An operand’s ORDER BY is not ignored. ACE accepts an ORDER BY on a set operation’s operand and then ignores it. LibRed refuses it unless the operand is in parentheses, where it orders that operand.
  • A comparison is typed Boolean. x = y, x IS NULL and other Boolean expressions return True or False as a Boolean, where ACE returns the Int16 -1 or 0. The values agree.
  • IN external_database has no AllowQueryRemoteTables gate. ACE refuses every form unless its AllowQueryRemoteTables setting allows it. LibRed opens Access databases only: a dBASE, Paradox, Excel or text type is refused. The other file stays open for as long as the database that reached it.

Differences from ACE lists the rest.

These run against the Northwind sample database, as in the playground.

SELECT CompanyName, City FROM Customers WHERE Country = 'Germany' ORDER BY CompanyName

A SELECT with no FROM returns one row:

SELECT 2 + 3 AS Five

A * among other items. Name comes first, then every column of Products:

SELECT ProductName AS Name, * FROM Products WHERE ProductID = 1

Unnamed expressions are named Expr1001 and Expr1002, by their place in the list:

SELECT ProductID, UnitPrice * 2, UnitPrice * 3 FROM Products WHERE ProductID = 1

This returns 21 countries:

SELECT DISTINCT Customers.Country FROM Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID

This returns 89 rows, one per customer with orders:

SELECT DISTINCTROW Customers.Country FROM Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID

The five most expensive products:

SELECT TOP 5 ProductName, UnitPrice FROM Products ORDER BY UnitPrice DESC

Four products cost 18. TOP 2 returns two of them; TOP 2 WITH TIES returns all four:

SELECT TOP 2 WITH TIES ProductName, UnitPrice FROM Products WHERE UnitPrice <= 18 ORDER BY UnitPrice DESC

Ten percent of 77 products, rounded up to 8 rows:

SELECT TOP 10 PERCENT ProductName, UnitPrice FROM Products ORDER BY UnitPrice DESC

A parameter as the count (a LibRed extension):

SELECT TOP @n ProductName FROM Products ORDER BY ProductName

Two joins, nested with parentheses:

SELECT Orders.OrderID, Customers.CompanyName, Employees.LastName
FROM (Orders INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID)
INNER JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
ORDER BY Orders.OrderID

Customers with no orders:

SELECT Customers.CompanyName
FROM Customers LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
WHERE Orders.OrderID IS NULL

Every shipper with every category, written the Access way and with CROSS JOIN:

SELECT Shippers.CompanyName, Categories.CategoryName FROM Shippers, Categories
SELECT Shippers.CompanyName, Categories.CategoryName FROM Shippers CROSS JOIN Categories

Suppliers and customers by city, keeping those of both with no match (a LibRed extension):

SELECT s.CompanyName AS Supplier, c.CompanyName AS Customer, s.City, c.City
FROM Suppliers AS s FULL OUTER JOIN Customers AS c ON s.City = c.City

The most expensive product in each category (a LibRed extension):

SELECT c.CategoryName, p.ProductName, p.UnitPrice
FROM Categories AS c
CROSS APPLY (SELECT TOP 1 ProductName, UnitPrice FROM Products
WHERE Products.CategoryID = c.CategoryID ORDER BY UnitPrice DESC) AS p

These read from C:\Data\Archive.accdb, another Access database with the Northwind tables; put the path of your own file in its place.

SELECT CompanyName, City FROM Customers IN 'C:\Data\Archive.accdb' WHERE Country = 'Norway'
SELECT * FROM Customers IN '' [;DATABASE=C:\Data\Archive.accdb] WHERE Country = 'Norway'

Countries with at least nine customers:

SELECT Country, COUNT(*) AS N FROM Customers GROUP BY Country HAVING COUNT(*) >= 9 ORDER BY COUNT(*) DESC

Each product’s price rank within its category:

SELECT ProductName, CategoryID, UnitPrice,
RANK() OVER (PARTITION BY CategoryID ORDER BY UnitPrice DESC) AS PriceRank
FROM Products
ORDER BY CategoryID, UnitPrice DESC

A running total of freight:

SELECT OrderID, OrderDate, Freight,
SUM(Freight) OVER (ORDER BY OrderDate, OrderID ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS RunningFreight
FROM Orders
ORDER BY OrderDate, OrderID

Categories ranked by their number of products:

SELECT CategoryID, COUNT(*) AS N, RANK() OVER (ORDER BY COUNT(*) DESC) AS R FROM Products GROUP BY CategoryID

An aggregate with FILTER, and a median:

SELECT COUNT(*) FILTER (WHERE UnitPrice > 50) AS Dear, COUNT(*) AS AllProducts FROM Products
SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY UnitPrice) AS Median FROM Products

Rows 11 to 15 by name (a LibRed extension):

SELECT ProductName FROM Products ORDER BY ProductName OFFSET 10 ROWS FETCH NEXT 5 ROWS ONLY
SELECT City FROM Customers UNION SELECT City FROM Suppliers ORDER BY City

Cities with both a customer and a supplier, and cities with a supplier but no customer (LibRed extensions):

SELECT City FROM Customers INTERSECT SELECT City FROM Suppliers ORDER BY City
SELECT City FROM Suppliers EXCEPT SELECT City FROM Customers ORDER BY City

The first three of each, each operand ordered on its own:

(SELECT TOP 3 ProductName FROM Products ORDER BY ProductName)
UNION ALL
(SELECT TOP 3 CompanyName FROM Suppliers ORDER BY CompanyName)
TABLE Shippers
SELECT * FROM (VALUES (1, 'a'), (2, 'b')) AS v(n, s)
SELECT ProductName FROM Products WHERE UnitPrice > (SELECT AVG(UnitPrice) FROM Products) AND CategoryID = 1
SELECT CompanyName FROM Customers WHERE CustomerID IN (SELECT CustomerID FROM Orders WHERE Freight > 800)
SELECT CompanyName FROM Customers
WHERE NOT EXISTS (SELECT * FROM Orders WHERE Orders.CustomerID = Customers.CustomerID)

Products dearer than at least one beverage:

SELECT ProductName, UnitPrice FROM Products
WHERE UnitPrice > ANY (SELECT UnitPrice FROM Products WHERE CategoryID = 1)

A derived table:

SELECT q.CategoryID, q.N
FROM (SELECT CategoryID, COUNT(*) AS N FROM Products GROUP BY CategoryID) AS q
WHERE q.N > 10

With CASE (a LibRed extension), and the same with IIf:

SELECT ProductName,
CASE WHEN UnitsInStock = 0 THEN 'Out' WHEN UnitsInStock < 10 THEN 'Low' ELSE 'OK' END AS Stock
FROM Products
SELECT ProductName, IIf(UnitsInStock = 0, 'Out', IIf(UnitsInStock < 10, 'Low', 'OK')) AS Stock FROM Products
SELECT CompanyName, COALESCE(Region, Country) AS Area, NULLIF(Country, 'USA') AS NonUS FROM Customers
SELECT CompanyName FROM Customers WHERE Country = 'France' ORDER BY CompanyName WITH OWNERACCESS OPTION