SELECT Statement Clauses
The SELECT statement has the following clauses:
• SELECT
• FROM
• WHERE
• GROUP BY
• HAVING
• ORDER BY
• LIMIT
• OFFSET
• FETCH FIRST
• UNION
• INTERSECT
• EXCEPT
• WITH
SELECT Clause
The SELECT clause specifies which values are to be returned. To display all the columns of a table, use the asterisk wildcard character (*). For example, the following query displays all rows and columns from the employees table:
SELECT * FROM employees;
To select specific columns, specify the column names. For example, the following query displays all rows, but only two columns from the employees table:
SELECT ename, enumber FROM employees;
To specify the table from which the column is to be selected, use the table.column_name syntax. For example:
SELECT managers.name, employees.name
FROM managers, employees...
In the preceding example, both source tables contain a column called name. The column names are preceded by the name of the source table; the first column of the result table contains the values from the name column of the managers table, and the second column contains the values from the name column of the employees table. If a column name is used in more than one of the source tables, qualify the column name with the table to which it belongs, or with a correlation name. For details, see
FROM Clause.
The number of rows in the result table can be limited using the FIRST clause. RowCount is a positive integer value that indicates the maximum rows in the result table. The query is effectively evaluated without concern for the FIRST clause, but only the first “n” rows (as defined by rowCount) are returned. This clause cannot be used in a WHERE clause subselect and it can only be used in the first of a series of UNIONed selects. However, it can be used in the CREATE TABLE...AS SELECT and INSERT INTO...SELECT statements.
To eliminate duplicate rows from the result table, specify the keyword DISTINCT. To preserve duplicate rows, specify the keyword ALL. By default, duplicate rows are preserved.
For example, the following table contains order information; the partno column contains duplicate values, because different customers have placed orders for the same part:
The following query displays the part numbers for which there are orders on file:
SELECT DISTINCT partno FROM orders
The result table looks like this:
A constant value can be included in the result table. For example:
SELECT 'Name:', ename, CURRENT_DATE,
IFNULL(edept,'Unassigned')
FROM employees;
The preceding query selects all rows from the employees table; the result table is composed of the string constant 'Name:', the name of the employee, today's date, and the employee's department, or if there is no department assigned, the string constant 'Unassigned'.
The result table looks like this (depending, of course, on the data in the employees table):
The SELECT clause can be used to obtain values calculated from the contents of a table. For example, the following query calculates the weekly salary of each employee based on their annual salary:
SELECT ename, annual_salary/52 FROM employees;
Aggregate functions can be used to calculate values based on the contents of a column. For example, the following query returns the highest, lowest, and average salary from the employees table:
SELECT MAX(salary), MIN(salary), AVG(salary)
FROM employees;
These values are based on the amounts stored in the salary column.
To specify a name for a column in the result table, use the AS result_column clause. In the following example, the name, weekly_salary, is assigned to the second result column:
SELECT ename, annual_salary/52 AS weekly_salary
FROM employees;
If a result column name is omitted for columns that are not drawn directly from a table (for example, calculated values or constants), the result columns are assigned the default name COLn, where n is the column number; result columns are numbered from left to right. Column names cannot be assigned in SELECT clauses that use the asterisk wildcard (*) to select all the columns in a table.
FROM Clause
The FROM clause specifies the source tables and views from which data is to be read. The specified tables and views must exist at the time the query is issued. The from_source parameter can be:
• One or more tables or views, specified using the following syntax:
[schema.]table [[AS] corr_name]
where table is the name of a table, view, or synonym.
• A join between two or more tables or views, specified using the following syntax:
source join_type JOIN source ON search_condition
or
source join_type JOIN source USING (column {, column})
or
source CROSS JOIN source
(select_stmt) corr_name [(column_list)]
where select_stmt is a SELECT statement with no ORDER BY clause, corr_name is a mandatory correlation name, and column_list is an optional list of override names for the columns in the SELECT list of the select_list.
• A
table procedure (see
Table Procedure) specified using the following syntax:
proc_name ([param_name=]param_spec {,[param_name=]param_spec})
A maximum of 126 tables can be specified in a query, including the tables in the FROM list, tables in subselects, and tables and views resulting from the expansion of the definitions of any views included in the query.
WHERE Clause
The WHERE clause specifies criteria that restrict the contents of the results table. You can test for simple relationships or, using subselects, for relationships between a column and a set of columns.
Using a simple WHERE clause, the contents of the results table can be restricted, as follows:
Comparisons:
SELECT emp_name FROM employee
WHERE manager = 'Jones';
SELECT emp_name FROM employee
WHERE salary > 50000;
Ranges:
SELECT ordnum FROM orders
WHERE odate BETWEEN DATE('2014-01-01') AND CURRENT_DATE;
Set membership:
SELECT * FROM orders
WHERE partno IN ('123-45', '678-90');
Pattern matching:
SELECT * FROM employee
WHERE emp_name LIKE 'A%';
Nulls:
SELECT emp_name FROM employee
WHERE dept_no IS NULL;
Combined restrictions using logical operators:
SELECT emp_name FROM employee
WHERE dept_no IS NULL AND
hiredate = CURRENT_DATE;
Note: Aggregate functions cannot appear in a WHERE clause.
More information:
Predicates in SQL
GROUP BY Clause
The GROUP BY clause groups the selected rows based on identical values in a column or expression. This clause is typically used with aggregate functions to generate a single result row for each set of unique values in a set of columns or expressions.
A simple GROUP BY clause consists of a list of one or more columns or expressions that define the sets of rows that aggregations (like SUM, COUNT, MIN, MAX, and AVG) are to be performed on. A change in the value of any of the GROUP BY columns or expressions triggers a new set of rows to be aggregated.
If the GROUP BY clause contains CUBE or ROLLUP options, it creates superaggregate (subtotal) groupings in addition to the ordinary grouping.
GROUP BY has the following format:
GROUP BY [ALL | DISTINCT] grouping element {,grouping element}
where grouping element is:
column list
| ROLLUP (column list)
| CUBE (column list)
| GROUPING SETS (grouping element {,grouping element}
| ( )
and where:
ALL | DISTINCT
Retains (ALL) or eliminates (DISTINCT) duplicate values in the result set. Default: ALL
column list
Specifies one or more columns or expressions, each separated by a comma.
ROLLUP (column list)
Calculates group subtotals from right to left. Generates the simple GROUP BY aggregate rows, superaggregate rows, and a grand total row.
CUBE (column list)
Produces one row for each unique combination of expressions in the column list. Generates simple GROUP BY aggregate rows, superaggregate rows, cross-tabular rows, and a grand total row.
GROUPING SETS
Totals only the specified groups instead of the full set of aggregations generated by using CUBE or ROLLUP. GROUPING SETS syntax can be defined over simple column sets or CUBEs or ROLLUPs.
( )
Generates a total (that is, an aggregation computed over the entire set of input rows).
Simple GROUP BY Queries
The following query, which uses a simple GROUP BY clause, obtains the number of orders for each part number in the orders table:
SELECT partno, count(*) FROM orders
GROUP BY partno;
The preceding query returns one row for each part number in the orders table, even though there can be many orders for the same part number.
Nulls are used to represent unknown data, and two nulls are typically not considered to be equal in SQL comparisons. However, the GROUP BY clause treats nulls as equal and returns a single row for nulls in a grouped column or expression.
Grouping can be performed on multiple columns or expressions. For example, to display the number of orders for each part placed each day:
SELECT odate, partno, count(*) FROM orders
GROUP BY odate, partno;
If you specify the GROUP BY clause, columns referenced must be all the columns in the SELECT clause that do not contain an aggregate function. These columns can either be the column, an expression, or the ordinal number in the column list.
For example:
SELECT cust_no,
CURRENT_DATE - odate AS days_since_order_placed,
COUNT(*) AS number_of_orders
FROM orders
GROUP BY cust_no,
CURRENT_DATE - odate
ORDER BY 1, 2;
SELECT cust_no,
CURRENT_DATE - odate AS days_since_order_placed,
COUNT(*) AS number_of_orders
FROM orders
GROUP BY cust_no, 2
ORDER BY 1, 2;
ROLLUP, CUBE, and GROUPING SETS Queries
The GROUPING SETS extension to the GROUP BY clause includes:
• ROLLUP and CUBE
• GROUPING SETS expression
• GROUPING function
These extensions reduce the complexity of your SQL while allowing efficient analysis across multiple dimensions.
ROLLUP performs aggregations at increasing levels up to a grand total. When multiple columns are specified, say GROUP BY ROLLUP(c1, c2, c3), ROLLUP generates the GROUP BY aggregate rows for each unique combination of values of (c1, c2, c3), plus superaggregate rows for each unique combination of values of (c1, c2), and (c1).
ROLLUP also generates a superaggregate row for the entire set of input rows.
The order of the columns specified in ROLLUP() can change the result and the number of rows in the result set.
List each employee's salary, the subtotal of all salaries in each department, and the total salary amount:
SELECT deptno, empno, SUM(sal) AS salary,
CASE GROUPING(deptno, empno) WHEN 0 THEN ' ' WHEN 1 THEN 'department total' WHEN 3 THEN 'grand total' END
FROM salary GROUP BY ROLLUP(deptno, empno);
deptno empno salary col4
--------------------------------------------
(null) (null) 46800 grand total
100 (null) 4400 department total
300 (null) 8800 department total
400 (null) 6500 department total
500 (null) 10400 department total
800 (null) 16700 department total
100 840 4400
300 499 1150
300 521 1400
300 654 1500
300 698 850
300 844 1150
300 900 2750
400 789 6500
500 299 3900
500 371 2200
500 473 2200
500 902 2100
800 5 10500
800 854 6200
CUBE generates the GROUP BY aggregate rows, plus superaggregate rows for each unique combination of expressions in the column list. So CUBE(c1, c2, c3) produces aggregate rows for each unique combination of (c1, c2, c3), as well as superaggregate rows for each unique combination of values of (c1, c2), (c1, c3), (c2, c3), (c1), (c2), and (c3), and a grand total row for the entire set of input rows. The order of the columns specified in CUBE() has no effect.
CUBE is useful for situations that require cross-tabular reports.
Show each job and salary by department, totals for each department, and totals for the entire company:
SELECT deptno,
job,
count(*),
sum(sal)
FROM emp
GROUP BY CUBE(deptno,job);
DEPTNO JOB COUNT(*) SUM(SAL)
--------- --------- --------- ---------
10 CLERK 1 1300
10 DIRECTOR 1 2450
10 CEO 1 9000
10 3 12750
20 CLERK 2 1300
20 PROGRAMMER 2 5000
20 DIRECTOR 1 2975
20 5 9275
30 CLERK 1 950
30 DIRECTOR 1 2850
30 SALESMAN 4 5600
30 6 9400
PROGRAMMER 2 5000
CLERK 4 3550
DIRECTOR 3 8275
CEO 1 9000
SALESMAN 4 5600
14 31425
The GROUPING SETS syntax lets you define multiple independent sets of grouping columns on which the aggregates are to be computed. You can specify GROUPING SETS when you do not need all the groupings that are generated by using ROLLUP or CUBE and when aggregations are required on distinct sets of grouping columns. ROLLUP and CUBE are simply special short forms for specific sets of GROUPING SETS.
Each grouping set defines a set of columns for which an aggregate result is computed. The final result set is the set of distinct rows from the individual grouping column specifications in the grouping sets. GROUPING SETS syntax can be defined over simple column sets or CUBEs or ROLLUPs. In effect, CUBE and ROLLUP are simply short forms for specific varieties of GROUPING SETS.
A GROUPING SETS query can be considered to be simply a UNION of each of the individual groupings defined in the GROUPING SETs syntax (or CUBE or ROLLUP).
Show sales totals for division and region:
SELECT division, region, SUM(sales) AS sales FROM div_sales
GROUP BY GROUPING SETS (division, region);
division region sales
-----------------------------
capital (null) 58
energy (null) 155
technology (null) 206
home (null) 109
(null) us 174
(null) europe 124
(null) pacific 86
(null) americas 80
(null) mea 64
The empty grouping set—GROUP BY()—simply defines an aggregation to be computed over the entire source set of rows (a simple aggregate).
The
GROUPING() function (see
GROUPING) can be used to simplify a query that needs many GROUP BY levels. The function argument is a list of one or more columns or expressions in parentheses. Each parameter must appear in the GROUP BY clause. The result is an integer consisting of "n" binary digits, where "n" is the number of parameters to the function. For each result row of the grouped query, the digit corresponding to the nth parameter of the GROUPING function is 0 if the result row is based on a value of the nth parameter, else 1.
For example, for the following clause:
GROUP BY CUBE (c1, c2, c3)
GROUPING(c1, c2, c3) returns 0 for the <C1, C2, C3> rows, 4 for the <C2, C3> rows, 1 for the <C1, C2> rows, and so forth. Likewise, GROUPING(C3, C1) returns 3 for <C2> rows, 1 for <C3> rows, 0 for <C1, C3> rows and <C1, C2, C3> rows.
HAVING Clause
The HAVING clause filters the results of the GROUP BY clause, in the same way the WHERE clause filters the results of the SELECT...FROM clauses. The HAVING clause uses the same restriction operators as the WHERE clause.
For example, to return orders for each part for each day in the past week:
SELECT odate, partno, count(*) FROM orders
GROUP BY odate, partno
HAVING odate >= (date('today') - '1 week');
Any columns or expressions contained in the HAVING clause must follow the same limitations described for the SELECT clause.
ORDER BY Clause
The ORDER BY clause allows you to specify the columns on which the results table is to be sorted. For example, if the employees table contains the following data:
then this query:
SELECT emanager, ename, edept FROM employees
ORDER BY emanager, edept, ename
produces the following list of managers, the departments they manage, and the employees in each department:
and this query:
SELECT ename, edept, emanager FROM employees
ORDER BY ename
produces this alphabetized employee list:
To display result columns sorted in descending order (reverse numeric or alphabetic order), specify ORDER BY column_name DESC. For example, to display the employees in each department from oldest to youngest:
SELECT edept, ename, eage FROM employees
ORDER BY edept, eage DESC;
If a nullable column is specified in the ORDER BY clause, nulls are sorted to the end of the results table by default. When using the DESC modifier the NULLS are moved to the beginning of the output. To modify this behavior use the NULLS LAST or NULLS FIRST modifier:
SELECT dcolumn FROM dtest
UNION ALL
SELECT zcolumn FROM ztest
ORDER BY dcolumn NULLS FIRST;
SELECT dcolumn FROM dtest
UNION ALL
SELECT zcolumn FROM ztest
ORDER BY dcolumn DESC NULLS LAST;
Notes:
• If the ORDER BY clause is omitted, the order of the rows in the results table is not guaranteed to have any relationship to the storage structure or key structure of the source tables.
• There may be occasions where a column name is repeated in the output of an SQL statement, for example, where the same column name is repeated over several tables used in a join. The parser does not generate an error where such an ambiguity exists.
In such cases, we recommend that you clarify your intent by qualifying the column used in the ORDER BY clause by using its table name as a prefix.
In union selects, the result column names must either be the column names from the SELECT clause of the first SELECT statement, or the number of the result column. For example:
SELECT dcolumn FROM dtest
UNION ALL
SELECT zcolumn FROM ztest
ORDER BY dcolumn
In addition to specifying individual column names as the ordering-expressions of the ORDER BY clause, the results table can also be sorted on the value of an expression.
For example, the query:
SELECT ename, edept, emanager FROM employees
ORDER BY emanager+edept
produces the employee list ordered on the concatenation of the emanager and edept values.
ORDER BY BOOLEAN results in grouping rows in the order: FALSE, TRUE, NULL unless other modifiers are applied.
Note: The ORDER BY clause must contain a column name or expression that is in the select list.
Incorrect:
SELECT DISTINCT col1, col2 FROM table ORDER BY col3;
Correct:
SELECT DISTINCT col1, col2, col3 FROM table ORDER BY col3;
SELECT DISTINCT emp_name, dept_no, employee_id FROM employee_dim ORDER BY employee_id;
LIMIT Clause
The LIMIT clause syntax is LIMIT n where n is a positive integer. It limits the result set to the specified number of rows. For example, the following query returns 50 rows from the result set.:
SELECT * FROM mytable LIMIT 50
The LIMIT clause can be used with unions, views and can be used more than once in a single query involving subqueries.
For example, the following query returns rows 3 to 5 from the result set. Subquery returns rows 2 to 5, which is trimmed down further by the clauses in the outer query to return rows 3 to 5.
select * from (select c1 from fnam_xt1 order by c1 desc limit 4 offset 1 )a order by 1 asc limit 3 offset 1
OFFSET Clause and FETCH_FIRST Clause
The OFFSET and FETCH FIRST clauses are used to return a subset of rows from a result set.
A query can use any combination of the ORDER BY, OFFSET, and FETCH FIRST clauses, but in that order only.
OFFSET and FETCH FIRST clauses can be used with unions, views and can be used more than once in a single query involving subqueries.
For example, the following query returns rows 3 to 5 from the result set. Subquery returns rows 2 to 5, which is trimmed down further by the clauses in the outer query to return rows 3 to 5.
select * from (select c1 from fnam_xt1 order by c1 desc offset 1 fetch first 4 rows only)a order by 1 asc offset 1 fetch first 3 rows only
The FETCH FIRST clause cannot be used in the same SELECT statement as SELECT FIRST rowcount.
The OFFSET clause syntax is OFFSET n, where n is a positive integer, a host variable, or a procedure parameter or local variable. For example, the following query returns rows starting from the 25th row of the result set:
SELECT * FROM MYTABLE ORDER BY COL1 OFFSET 25
The FETCH FIRST clause syntax is as follows:
FETCH FIRST n ROWS ONLY
where n is a positive integer, a host variable, or procedure parameter or local variable. For example, the following query fetches only the first 10 rows of the result set:
SELECT * FROM MYTABLE ORDER BY COL1 FETCH FIRST 10 ROWS ONLY
In the FETCH FIRST clause, the keywords FIRST and NEXT, and the keywords ROWS and ROW are interchangeable. Because you can offset and fetch first in the same query, NEXT is an alternative for readability. For example:
OFFSET 10 FETCH NEXT 25 ROWS ONLY
First N After M Clause
The First N After M clause enables the ability of the FIRST n qualifier to be used in sub-selects as well as the main query and it is widened to include the offset capability using FIRST NAFTER M as a SELECT qualifier for both X100 and Ingres tables. The FIRST N After M clause syntax is as follows:
SELECT FIRST n AFTER m COL1 FROM MYTABLE
where, n and m are positive integers.
A sort order can be specified in the subqueries for deterministic results.
Notes:
• Top N, limit, Fetch_first, Fetch_next and First N are similar clauses and only one such clause can be used in a query.
• OFFSET and AFTER M are similar clauses and only one such clause can be used in a query.
• Either the OFFSET clause or the AFTER M clause can be combined with TOP N, LIMIT, FETCH_FIRST, FETCH_NEXT and First N clauses to enhance the results of a query.
• Correlated subselects with row limits are not supported.
Few examples of queries with valid combinations for the clauses specified above are listed here:
* SELECT TOP 4 COL1 FROM MYTABLE ORDER BY COL1 OFFSET 1
* SELECT TOP 4 AFTER 1 COL1 FROM MYTABLE ORDER BY COL1
* SELECT COL1 FROM MYTABLE ORDER BY COL1 OFFSET 1 FETCH FIRST 3 ROWS ONLY
* SELECT AFTER 1 COL1 FROM MYTABLE ORDER BY COL1 FETCH FIRST 3 ROWS ONLY
* SELECT COL1 FROM MYTABLE ORDER BY COL1 LIMIT 3 OFFSET 1
* SELECT AFTER 1 COL1 FROM MYTABLE ORDER BY COL1 LIMIT 3
* SELECT COL1 FROM MYTABLE ORDER BY COL1 OFFSET 2 FETCH NEXT 4 ROWS ONLY
* SELECT AFTER 1 COL1 FROM MYTABLE ORDER BY COL1 FETCH NEXT 3 ROWS ONLY
* SELECT FIRST 3 COL1 FROM MYTABLE ORDER BY COL1 OFFSET 1
* SELECT FIRST 3 AFTER 1 COL1 FROM MYTABLE ORDER BY COL1
UNION Clause
The UNION clause combines the results of SELECT statements into a single result table.
The following example lists all employees in the table of active employees plus those in the table of retired employees:
SELECT ename FROM active_emps
UNION
SELECT ename FROM retired_emps;
By default, the UNION clause eliminates any duplicate rows in the result table. To retain duplicates, specify UNION ALL. Any number of SELECT statements can be combined using the UNION clause, and both UNION and UNION ALL can be used when combining multiple tables.
If you know that the result sets you want to combine from the different SELECT statements are unique, or if uniqueness is not a concern, then use UNION ALL to get better performance.
Unions are subject to the following restrictions:
• The SELECT statements must return the same number of columns.
• The columns returned by the SELECT statements must correspond in order and data type, although the column names do not have to be identical.
• The SELECT statements cannot include individual ORDER BY clauses.
To sort the result table, specify the ORDER BY clause following the last SELECT statement. The result columns returned by a union are named according to the first SELECT statement.
By default, unions are evaluated from left to right. To specify a different order of evaluation, use parentheses.
Any number of SELECT statements can be combined using the UNION clause. A maximum of 126 tables is allowed in a query.
INTERSECT Clause
The INTERSECT clause takes the results of two SELECT statements and returns only rows that appear in both result tables. INTERSECT removes duplicate rows from the final result table. INTERSECT does not support the ALL option.
The following example returns all rows from the employee table where salary is between 75000 and 100000:
SELECT * FROM employee WHERE salary >= 75000
INTERSECT
SELECT * FROM employee WHERE salary <= 100000;
EXCEPT Clause
The EXCEPT clause takes the results of two SELECT statements and returns the rows of the first result table that do not appear in the second result table. EXCEPT removes duplicate rows from the final result table. EXCEPT does not support the ALL option.
The following example returns all rows from the employee table where salary is greater than 100000:
SELECT * FROM employee WHERE salary >= 75000
EXCEPT
SELECT * FROM employee WHERE salary <= 100000;
WITH Clause for SELECT
The WITH clause on the SELECT statement consists of a comma-separated list of one or more of the following options:
[NO]KEYJ
Controls whether key joins are permitted. WITH KEYJ permits keyjoins, although it may not result in a key join being compiled into a query plan. WITH NOKEYJ assures that no key joins are used.
Default: WITH KEYJ
[NO]FLATTEN
Controls whether query flattening is used to optimize queries, including queries involving aggregate subselects or singleton subselects.
Default: WITH FLATTEN
[NO]OJFLATTEN
Controls whether the query optimizer uses the transformation that converts a NOT EXISTS/NOT IN subselect to an outer join with the containing query.
Default: WITH OJFLATTEN
[NO]QEP
Specifies whether to display a diagrammatic representation of the query execution plan chosen for the query by the optimizer.
Default: WITH NOQEP
[NO]GREEDY
Enables or disables the exhaustive enumeration heuristic of the query optimizer for complex queries.
When the query references a large number of tables, the greedy enumeration heuristic enables the optimizer to produce a query plan much faster than with its default technique of exhaustive searching for query execution plans. For details on the greedy optimization heuristic, see the Database Administrator Guide.
[NO]HASH
Specifies whether the query optimizer should consider using hash aggregation and hash joins.
Default: WITH HASH
[NO]HASHAGG
Specifies whether the query optimizer should consider using
hash aggregation (see
[NO]HASHAGG).
Default: WITH HASHAGG
[NO]HASHJOIN
Specifies whether the query optimizer should consider using
hash joins (see
[NO]HASHJOIN).
Default: WITH HASHJOIN
[NO]PARALLEL
Controls whether the query optimizer enables the generation of parallel query execution plans.
For a discussion of parallel query plans, see the Database Administrator Guide.
Default: WITH NOPARALLEL
MAX_PARALLEL n
Sets the parallelism level for the query, where n is an integer from 1 to 256.
The value of n should not exceed the number of CPU cores visible to the operating system. Your query may run at a lower level of parallelism than requested if other parallel queries are running concurrently.
X100 WITH Clause Options
X100 tables support the following WITH clause options: [NO]QEP, [NO]GREEDY, MAX_PARALLEL, [NO]UNION_FLATTEN.