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.
Syntax
Section titled “Syntax”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 conditionCROSS JOIN table_sourceCROSS APPLY table_sourceOUTER APPLY table_sourceA query_term, the operand of a set operation, is one of:
SELECT … -- without ORDER BY, OFFSET or FETCH( query )TABLE table_nameVALUES ( value [ , … ] ) [ , … ]Arguments
Section titled “Arguments”Select list
Section titled “Select list”ALL | DISTINCT | DISTINCTROW
Section titled “ALL | DISTINCT | DISTINCTROW”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.
TOP n [ PERCENT ] [ WITH TIES ]
Section titled “TOP n [ PERCENT ] [ WITH TIES ]”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.
select_item
Section titled “select_item”A column or value to return. Each item is one of:
*: every column of every table in theFROMclause.- 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
CASEexpression 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.
Output column names
Section titled “Output column names”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
Exprname. - An unnamed expression is
Expr1000and up, numbered by its place in the select list: the second item isExpr1001. - 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.
FROM clause
Section titled “FROM clause”table_name [ [ AS ] alias ]
Section titled “table_name [ [ AS ] alias ]”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.
Comma-separated sources
Section titled “Comma-separated sources”FROM a, b pairs every row of a with every row of b (a cartesian product). Put the join condition in the
WHERE clause.
[ INNER ] JOIN … ON condition
Section titled “[ INNER ] JOIN … ON condition”Returns the pairs of rows for which condition is true. INNER is optional.
LEFT [ OUTER ] JOIN, RIGHT [ OUTER ] JOIN
Section titled “LEFT [ OUTER ] JOIN, RIGHT [ OUTER ] JOIN”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.
FULL [ OUTER ] JOIN
Section titled “FULL [ OUTER ] JOIN”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].
CROSS JOIN
Section titled “CROSS JOIN”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.
CROSS APPLY, OUTER APPLY
Section titled “CROSS APPLY, OUTER APPLY”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.
Nested joins
Section titled “Nested joins”Parentheses group joins: (a INNER JOIN b ON …) INNER JOIN c ON …. LibRed evaluates them as they nest; see
Differences from ACE.
IN external_database
Section titled “IN external_database”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.
WHERE, GROUP BY and HAVING
Section titled “WHERE, GROUP BY and HAVING”WHERE condition
Section titled “WHERE condition”Keeps only the rows for which condition is true. A row for which it is False or Null is left out.
GROUP BY expression [ , … ]
Section titled “GROUP BY expression [ , … ]”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.
HAVING condition
Section titled “HAVING condition”Keeps only the groups for which condition is true. It may use aggregates.
Window functions
Section titled “Window functions”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.
function
Section titled “function”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.
PARTITION BY
Section titled “PARTITION BY”Divides the rows into partitions, and the function runs over each separately. Without it the whole result is one partition.
ORDER BY
Section titled “ORDER BY”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.
FILTER ( WHERE condition ), WITHIN GROUP
Section titled “FILTER ( WHERE condition ), WITHIN GROUP”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, OFFSET and FETCH
Section titled “ORDER BY, OFFSET and FETCH”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 …).
OFFSET offset { ROW | ROWS }
Section titled “OFFSET offset { ROW | ROWS }”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.
Set operations
Section titled “Set operations”UNION [ ALL ]
Section titled “UNION [ ALL ]”Returns the rows of both queries. UNION leaves out duplicate rows; UNION ALL keeps them. The output columns
are named by the first query.
INTERSECT, EXCEPT
Section titled “INTERSECT, EXCEPT”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.
TABLE table_name
Section titled “TABLE table_name”Every column of the table, as SELECT * FROM table_name. It can stand alone or as a set operation’s operand.
VALUES ( value [ , … ] ) [ , … ]
Section titled “VALUES ( value [ , … ] ) [ , … ]”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.
Subqueries
Section titled “Subqueries”A query in parentheses can stand in several places. Each holds a full query, so it may itself be a set operation.
Scalar subquery
Section titled “Scalar subquery”( 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.
expression [ NOT ] IN ( query )
Section titled “expression [ NOT ] IN ( query )”True when expression equals a value in the subquery’s one column. IN also takes a list of values:
Country IN ('Norway', 'Finland').
[ NOT ] EXISTS ( query )
Section titled “[ NOT ] EXISTS ( query )”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.
Conditional expressions
Section titled “Conditional expressions”LibRed extension. Standard SQL CASE, in both forms:
CASE WHEN condition THEN result [ WHEN … ] [ ELSE result ] ENDCASE operand WHEN value THEN result [ WHEN … ] [ ELSE result ] ENDWithout an ELSE, a CASE that matches nothing is Null. In Access SQL, write nested IIf calls instead.
COALESCE, NULLIF
Section titled “COALESCE, NULLIF”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.
WITH OWNERACCESS OPTION
Section titled “WITH OWNERACCESS OPTION”WITH OWNERACCESS OPTION
Section titled “WITH OWNERACCESS OPTION”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.
Remarks
Section titled “Remarks”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.
Differences from ACE
Section titled “Differences from ACE”TOP nreturns exactly n rows. ACE’sTOP n, andTOP n PERCENT, also returns every further row whoseORDER BYkeys equal the last one’s, a stored query ACE wrote included. AddWITH TIESto 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 anONthat 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. NOTover a quantified comparison is its negation. ACE turnsNOT (x < ALL (…))intox >= ALL (…), which is not the negation, for every comparison but=.- An operand’s
ORDER BYis not ignored. ACE accepts anORDER BYon 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 NULLand other Boolean expressions returnTrueorFalseas a Boolean, where ACE returns the Int16-1or0. The values agree. INexternal_database has noAllowQueryRemoteTablesgate. ACE refuses every form unless itsAllowQueryRemoteTablessetting 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.
Examples
Section titled “Examples”These run against the Northwind sample database, as in the playground.
Basic queries
Section titled “Basic queries”SELECT CompanyName, City FROM Customers WHERE Country = 'Germany' ORDER BY CompanyNameA SELECT with no FROM returns one row:
SELECT 2 + 3 AS FiveA * among other items. Name comes first, then every column of Products:
SELECT ProductName AS Name, * FROM Products WHERE ProductID = 1Unnamed expressions are named Expr1001 and Expr1002, by their place in the list:
SELECT ProductID, UnitPrice * 2, UnitPrice * 3 FROM Products WHERE ProductID = 1DISTINCT and DISTINCTROW
Section titled “DISTINCT and DISTINCTROW”This returns 21 countries:
SELECT DISTINCT Customers.Country FROM Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerIDThis returns 89 rows, one per customer with orders:
SELECT DISTINCTROW Customers.Country FROM Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerIDThe five most expensive products:
SELECT TOP 5 ProductName, UnitPrice FROM Products ORDER BY UnitPrice DESCFour 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 DESCTen percent of 77 products, rounded up to 8 rows:
SELECT TOP 10 PERCENT ProductName, UnitPrice FROM Products ORDER BY UnitPrice DESCA parameter as the count (a LibRed extension):
SELECT TOP @n ProductName FROM Products ORDER BY ProductNameTwo joins, nested with parentheses:
SELECT Orders.OrderID, Customers.CompanyName, Employees.LastNameFROM (Orders INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID) INNER JOIN Employees ON Orders.EmployeeID = Employees.EmployeeIDORDER BY Orders.OrderIDCustomers with no orders:
SELECT Customers.CompanyNameFROM Customers LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerIDWHERE Orders.OrderID IS NULLEvery shipper with every category, written the Access way and with CROSS JOIN:
SELECT Shippers.CompanyName, Categories.CategoryName FROM Shippers, CategoriesSELECT Shippers.CompanyName, Categories.CategoryName FROM Shippers CROSS JOIN CategoriesSuppliers 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.CityFROM Suppliers AS s FULL OUTER JOIN Customers AS c ON s.City = c.CityThe most expensive product in each category (a LibRed extension):
SELECT c.CategoryName, p.ProductName, p.UnitPriceFROM Categories AS c CROSS APPLY (SELECT TOP 1 ProductName, UnitPrice FROM Products WHERE Products.CategoryID = c.CategoryID ORDER BY UnitPrice DESC) AS pAnother database
Section titled “Another database”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'Grouping
Section titled “Grouping”Countries with at least nine customers:
SELECT Country, COUNT(*) AS N FROM Customers GROUP BY Country HAVING COUNT(*) >= 9 ORDER BY COUNT(*) DESCWindow functions
Section titled “Window functions”Each product’s price rank within its category:
SELECT ProductName, CategoryID, UnitPrice, RANK() OVER (PARTITION BY CategoryID ORDER BY UnitPrice DESC) AS PriceRankFROM ProductsORDER BY CategoryID, UnitPrice DESCA running total of freight:
SELECT OrderID, OrderDate, Freight, SUM(Freight) OVER (ORDER BY OrderDate, OrderID ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS RunningFreightFROM OrdersORDER BY OrderDate, OrderIDCategories ranked by their number of products:
SELECT CategoryID, COUNT(*) AS N, RANK() OVER (ORDER BY COUNT(*) DESC) AS R FROM Products GROUP BY CategoryIDAn aggregate with FILTER, and a median:
SELECT COUNT(*) FILTER (WHERE UnitPrice > 50) AS Dear, COUNT(*) AS AllProducts FROM ProductsSELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY UnitPrice) AS Median FROM ProductsPaging
Section titled “Paging”Rows 11 to 15 by name (a LibRed extension):
SELECT ProductName FROM Products ORDER BY ProductName OFFSET 10 ROWS FETCH NEXT 5 ROWS ONLYSet operations
Section titled “Set operations”SELECT City FROM Customers UNION SELECT City FROM Suppliers ORDER BY CityCities 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 CitySELECT City FROM Suppliers EXCEPT SELECT City FROM Customers ORDER BY CityThe 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 ShippersSELECT * FROM (VALUES (1, 'a'), (2, 'b')) AS v(n, s)Subqueries
Section titled “Subqueries”SELECT ProductName FROM Products WHERE UnitPrice > (SELECT AVG(UnitPrice) FROM Products) AND CategoryID = 1SELECT CompanyName FROM Customers WHERE CustomerID IN (SELECT CustomerID FROM Orders WHERE Freight > 800)SELECT CompanyName FROM CustomersWHERE NOT EXISTS (SELECT * FROM Orders WHERE Orders.CustomerID = Customers.CustomerID)Products dearer than at least one beverage:
SELECT ProductName, UnitPrice FROM ProductsWHERE UnitPrice > ANY (SELECT UnitPrice FROM Products WHERE CategoryID = 1)A derived table:
SELECT q.CategoryID, q.NFROM (SELECT CategoryID, COUNT(*) AS N FROM Products GROUP BY CategoryID) AS qWHERE q.N > 10Conditional expressions
Section titled “Conditional expressions”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 StockFROM ProductsSELECT ProductName, IIf(UnitsInStock = 0, 'Out', IIf(UnitsInStock < 10, 'Low', 'OK')) AS Stock FROM ProductsSELECT CompanyName, COALESCE(Region, Country) AS Area, NULLIF(Country, 'USA') AS NonUS FROM CustomersWITH OWNERACCESS OPTION
Section titled “WITH OWNERACCESS OPTION”SELECT CompanyName FROM Customers WHERE Country = 'France' ORDER BY CompanyName WITH OWNERACCESS OPTION