The syntax of the SQL programming language is defined and maintained by ISO/IEC SC 32 as part of ISO/IEC 9075. This standard is not freely available. Despite the existence of the standard, SQL code is not completely portable among different database systems without adjustments.

Language elements

The SQL language is subdivided into several language elements, including:

Keywords are words that are defined in the SQL language. They are either reserved (e.g. , and ), or non-reserved (e.g. , and ). List of SQL reserved words. Identifiers are names on database objects, like tables, columns and schemas. An identifier may not be equal to a reserved keyword, unless it is a delimited identifier. Delimited identifiers means identifiers enclosed in double quotation marks. They can contain characters normally not supported in SQL identifiers, and they can be identical to a reserved word, e.g. a column named is specified as . In MySQL, double quotes are string literal delimiters by default instead. Enabling the SQL mode enforces the SQL standard behavior. These can also be used regardless of this mode through backticks: . Clauses, which are constituent components of statements and queries. (In some cases, these are optional.)ANSI/ISO/IEC International Standard (IS). Database Language SQL—Part 2: Foundation (SQL/Foundation). 1999. Expressions, which can produce either scalar values, or tables consisting of columns and rows of data Predicates, which specify conditions that can be evaluated to SQL three-valued logic (3VL) (true/false/unknown) or Boolean truth values and are used to limit the effects of statements and queries, or to change program flow. Queries, which retrieve the data based on specific criteria. This is an important element of SQL. Statements, which may have a persistent effect on schemata and data, or may control transactions, program flow, connections, sessions, or diagnostics. SQL statements also include the semicolon (";") statement terminator. Though not required on every platform, it is defined as a standard part of the SQL grammar. Insignificant whitespace is generally ignored in SQL statements and queries, making it easier to format SQL code for readability.

Operators

Operator Description Example = Equal to <> Not equal to (many dialects also accept !=) > Greater than < Less than >= Greater than or equal <= Less than or equal Between an inclusive range. SYMMETRIC inverts the range bounds if the first is higher than the second. Begins with a character pattern Contains a character pattern Equal to one of multiple possible values Compare to null (missing data) or Boolean truth value test Is equal to value or both are nulls (missing data) Used to change a column name when viewing results

Other operators have at times been suggested or implemented, such as the skyline operator (for finding only those rows that are not 'worse' than any others).

SQL has the expression, which was introduced in SQL-92. In its most general form, which is called a "searched case" in the SQL standard:

CASE WHEN n > 0 THEN 'positive' WHEN n < 0 THEN 'negative' ELSE 'zero' END

SQL tests conditions in the order they appear in the source. If the source does not specify an expression, SQL defaults to . An abbreviated syntax called "simple case" can also be used:

CASE n WHEN 1 THEN 'One' WHEN 2 THEN 'Two' ELSE 'I cannot count that high' END

This syntax uses implicit equality comparisons, with the usual caveats for comparing with NULL.

There are two short forms for special expressions: and .

The expression returns the value of the first non-NULL operand, found by working from left to right, or NULL if all the operands equal NULL.

COALESCE(x1,x2) is equivalent to:

CASE WHEN x1 IS NOT NULL THEN x1 ELSE x2 END

The expression has two operands and returns NULL if the operands have the same value, otherwise it has the value of the first operand.

NULLIF(x1, x2)

is equivalent to CASE WHEN x1 = x2 THEN NULL ELSE x1 END

Comments Standard SQL allows two formats for comments: , which is ended by the first newline, and , which can span multiple lines.

Queries

The most common operation in SQL, the query, makes use of the declarative SELECT statement. retrieves data from one or more tables, or expressions. Standard statements have no persistent effects on the database. Some non-standard implementations of can have persistent effects, such as the syntax provided in some databases.

Queries allow the user to describe desired data, leaving the database management system (DBMS) to carry out planning, optimizing, and performing the physical operations necessary to produce that result as it chooses.

A query includes a list of columns to include in the final result, normally immediately following the keyword. An asterisk ("*"), or "wildcard", can be used to specify that the query should return all columns of the queried tables. is the most complex statement in SQL, with optional keywords and clauses that include:

The FROM clause, which indicates the table(s) to retrieve data from. The clause can include optional JOIN subclauses to specify the rules for joining tables. The WHERE clause includes a condition, which restricts the rows returned by the query. The clause eliminates all rows from the result set where the condition does not evaluate to True. The GROUP BY clause projects rows having common values into a smaller set of rows. is often used in conjunction with SQL aggregation functions or to eliminate duplicate rows from a result set. The clause is applied before the clause. The HAVING clause includes a predicate used to filter rows resulting from the clause. Because it acts on the results of the clause, aggregation functions can be used in the clause predicate. The ORDER BY clause identifies which column[s] to use to sort the resulting data, and in which direction to sort them (ascending or descending). Without an clause, the order of rows returned by an SQL query is undefined. The DISTINCT keyword eliminates duplicate data. The clause specifies the number of rows to skip before starting to return data. The clause specifies the number of rows to return. Some SQL databases instead have non-standard alternatives, e.g. , or . The clauses of a query have a particular order of execution, which is denoted by the number on the right hand side. It is as follows: SELECT <columns> 5. FROM <table> 1. WHERE <predicate on rows> 2. GROUP BY <columns> 3. HAVING <predicate on groups> 4. ORDER BY <columns> 6. OFFSET 7. FETCH FIRST 8.

The following example of a query returns a list of expensive books. The query retrieves all rows from the Book table in which the price column contains a value greater than 100.00. The result is sorted in ascending order by title. The asterisk (*) in the select list indicates that all columns of the Book table should be included in the result set.

SELECT * FROM Book WHERE price > 100.00 ORDER BY title;

The example below demonstrates a query of multiple tables, grouping, and aggregation, by returning a list of books and the number of authors associated with each book.

SELECT Book.title AS Title, count(*) AS Authors FROM Book JOIN Book_author ON Book.isbn = Book_author.isbn GROUP BY Book.title;

Example output might resemble the following:

Title Authors

SQL Examples and Guide 4 The Joy of SQL 1 An Introduction to SQL 2 Pitfalls of SQL 1

Under the precondition that isbn is the only common column name of the two tables and that a column named title only exists in the Book table, one could re-write the query above in the following form:

SELECT title, count(*) AS Authors FROM Book NATURAL JOIN Book_author GROUP BY title;

However, many vendors either do not support this approach, or require certain column-naming conventions for natural joins to work effectively.

SQL includes operators and functions for calculating values on stored values. SQL allows the use of expressions in the select list to project data, as in the following example, which returns a list of books that cost more than 100.00 with an additional sales_tax column containing a sales tax figure calculated at 6% of the price.

SELECT isbn, title, price, price * 0.06 AS sales_tax FROM Book WHERE price > 100.00 ORDER BY title;

Subqueries

Queries can be nested so that the results of one query can be used in another query via a relational operator or aggregation function. A nested query is also known as a subquery. While joins and other table operations provide computationally superior (i.e. faster) alternatives in many cases, the use of subqueries introduces a hierarchy in execution that can be useful or necessary. In the following example, the aggregation function receives as input the result of a subquery:

SELECT isbn, title, price FROM Book WHERE price < (SELECT AVG(price) FROM Book) ORDER BY title;

A subquery can use values from the outer query, in which case it is known as a correlated subquery.

Since 1999 the SQL standard allows clauses for subqueries, i.e. named subqueries, usually called common table expressions (also called subquery factoring). CTEs can also be recursive by referring to themselves; the resulting mechanism allows tree or graph traversals (when represented as relations), and more generally fixpoint computations.

Derived table

A derived table is the use of referencing an SQL subquery in a FROM clause. Essentially, the derived table is a subquery that can be selected from or joined to. The derived table functionality allows the user to reference the subquery as a table. The derived table is sometimes referred to as an inline view or a subselect.

In the following example, the SQL statement involves a join from the initial "Book" table to the derived table "sales". This derived table captures associated book sales information using the ISBN to join to the "Book" table. As a result, the derived table provides the result set with additional columns (the number of items sold and the company that sold the books):

SELECT b.isbn, b.title, b.price, sales.items_sold, sales.company_nm FROM Book b JOIN (SELECT SUM(Items_Sold) Items_Sold, Company_Nm, ISBN FROM Book_Sales GROUP BY Company_Nm, ISBN) sales ON sales.isbn = b.isbn

Null or three-valued logic (3VL)

The concept of Null allows SQL to deal with missing information in the relational model. The word is a reserved keyword in SQL, used to identify the Null special marker. Comparisons with Null, for instance equality (=) in WHERE clauses, results in an Unknown truth value. In SELECT statements SQL returns only results for which the WHERE clause returns a value of True; i.e., it excludes results with values of False and also excludes those whose value is Unknown.

Along with True and False, the Unknown resulting from direct comparisons with Null thus brings a fragment of three-valued logic to SQL. The truth tables SQL uses for AND, OR, and NOT correspond to a common fragment of the Kleene and Lukasiewicz three-valued logic (which differ in their definition of implication, however SQL defines no such operation).

p AND q p True False Unknown q True False Unknown p OR q p True False Unknown q True False Unknown

p = q p True False Unknown q True False Unknown q NOT q True False Unknown