
- •Contents
- •Send Us Your Comments
- •Preface
- •What’s New in SQL Reference?
- •1 Introduction to Oracle SQL
- •History of SQL
- •SQL Standards
- •Embedded SQL
- •Lexical Conventions
- •Tools Support
- •2 Basic Elements of Oracle SQL
- •Datatypes
- •Oracle Built-in Datatypes
- •ANSI, DB2, and SQL/DS Datatypes
- •Oracle-Supplied Types
- •"Any" Types
- •XML Types
- •Spatial Type
- •Media Types
- •Datatype Comparison Rules
- •Data Conversion
- •Literals
- •Text Literals
- •Integer Literals
- •Number Literals
- •Interval Literals
- •Format Models
- •Number Format Models
- •Date Format Models
- •String-to-Date Conversion Rules
- •XML Format Model
- •Nulls
- •Nulls in SQL Functions
- •Nulls with Comparison Conditions
- •Nulls in Conditions
- •Pseudocolumns
- •CURRVAL and NEXTVAL
- •LEVEL
- •ROWID
- •ROWNUM
- •XMLDATA
- •Comments
- •Comments Within SQL Statements
- •Comments on Schema Objects
- •Hints
- •Database Objects
- •Schema Objects
- •Nonschema Objects
- •Parts of Schema Objects
- •Schema Object Names and Qualifiers
- •Schema Object Naming Rules
- •Schema Object Naming Examples
- •Schema Object Naming Guidelines
- •Syntax for Schema Objects and Parts in SQL Statements
- •How Oracle Resolves Schema Object References
- •Referring to Objects in Other Schemas
- •Referring to Objects in Remote Databases
- •Referencing Object Type Attributes and Methods
- •3 Operators
- •About SQL Operators
- •Unary and Binary Operators
- •Operator Precedence
- •Arithmetic Operators
- •Concatenation Operator
- •Set Operators
- •4 Expressions
- •About SQL Expressions
- •Simple Expressions
- •Compound Expressions
- •CASE Expressions
- •CURSOR Expressions
- •Datetime Expressions
- •Function Expressions
- •INTERVAL Expressions
- •Object Access Expressions
- •Scalar Subquery Expressions
- •Type Constructor Expressions
- •Variable Expressions
- •Expression Lists
- •5 Conditions
- •About SQL Conditions
- •Condition Precedence
- •Comparison Conditions
- •Simple Comparison Conditions
- •Group Comparison Conditions
- •Logical Conditions
- •Membership Conditions
- •Range Conditions
- •Null Conditions
- •EQUALS_PATH
- •EXISTS Conditions
- •LIKE Conditions
- •IS OF type Conditions
- •UNDER_PATH
- •Compound Conditions
- •6 Functions
- •SQL Functions
- •Single-Row Functions
- •Aggregate Functions
- •Analytic Functions
- •Object Reference Functions
- •Alphabetical Listing of SQL Functions
- •ACOS
- •ADD_MONTHS
- •ASCII
- •ASCIISTR
- •ASIN
- •ATAN
- •ATAN2
- •BFILENAME
- •BITAND
- •CAST
- •CEIL
- •CHARTOROWID
- •COALESCE
- •COMPOSE
- •CONCAT
- •CONVERT
- •CORR
- •COSH
- •COUNT
- •COVAR_POP
- •COVAR_SAMP
- •CUME_DIST
- •CURRENT_DATE
- •CURRENT_TIMESTAMP
- •DBTIMEZONE
- •DECODE
- •DECOMPOSE
- •DENSE_RANK
- •DEPTH
- •DEREF
- •DUMP
- •EMPTY_BLOB, EMPTY_CLOB
- •EXISTSNODE
- •EXTRACT (datetime)
- •EXTRACT (XML)
- •EXTRACTVALUE
- •FIRST
- •FIRST_VALUE
- •FLOOR
- •FROM_TZ
- •GREATEST
- •GROUP_ID
- •GROUPING
- •GROUPING_ID
- •HEXTORAW
- •INITCAP
- •INSTR
- •LAST
- •LAST_DAY
- •LAST_VALUE
- •LEAD
- •LEAST
- •LENGTH
- •LOCALTIMESTAMP
- •LOWER
- •LPAD
- •LTRIM
- •MAKE_REF
- •MONTHS_BETWEEN
- •NCHR
- •NEW_TIME
- •NEXT_DAY
- •NLS_CHARSET_DECL_LEN
- •NLS_CHARSET_ID
- •NLS_CHARSET_NAME
- •NLS_INITCAP
- •NLS_LOWER
- •NLSSORT
- •NLS_UPPER
- •NTILE
- •NULLIF
- •NUMTODSINTERVAL
- •NUMTOYMINTERVAL
- •PATH
- •PERCENT_RANK
- •PERCENTILE_CONT
- •PERCENTILE_DISC
- •POWER
- •RANK
- •RATIO_TO_REPORT
- •RAWTOHEX
- •RAWTONHEX
- •REFTOHEX
- •REGR_ (Linear Regression) Functions
- •REPLACE
- •ROUND (number)
- •ROUND (date)
- •ROW_NUMBER
- •ROWIDTOCHAR
- •ROWIDTONCHAR
- •RPAD
- •RTRIM
- •SESSIONTIMEZONE
- •SIGN
- •SINH
- •SOUNDEX
- •SQRT
- •STDDEV
- •STDDEV_POP
- •STDDEV_SAMP
- •SUBSTR
- •SYS_CONNECT_BY_PATH
- •SYS_CONTEXT
- •SYS_DBURIGEN
- •SYS_EXTRACT_UTC
- •SYS_GUID
- •SYS_TYPEID
- •SYS_XMLAGG
- •SYS_XMLGEN
- •SYSDATE
- •SYSTIMESTAMP
- •TANH
- •TO_CHAR (character)
- •TO_CHAR (datetime)
- •TO_CHAR (number)
- •TO_CLOB
- •TO_DATE
- •TO_DSINTERVAL
- •TO_MULTI_BYTE
- •TO_NCHAR (character)
- •TO_NCHAR (datetime)
- •TO_NCHAR (number)
- •TO_NCLOB
- •TO_NUMBER
- •TO_SINGLE_BYTE
- •TO_TIMESTAMP
- •TO_TIMESTAMP_TZ
- •TO_YMINTERVAL
- •TRANSLATE
- •TRANSLATE ... USING
- •TREAT
- •TRIM
- •TRUNC (number)
- •TRUNC (date)
- •TZ_OFFSET
- •UNISTR
- •UPDATEXML
- •UPPER
- •USER
- •USERENV
- •VALUE
- •VAR_SAMP
- •VARIANCE
- •VSIZE
- •WIDTH_BUCKET
- •XMLAGG
- •XMLCOLATTVAL
- •XMLCONCAT
- •XMLELEMENT
- •XMLFOREST
- •XMLSEQUENCE
- •XMLTRANSFORM
- •ROUND and TRUNC Date Functions
- •User-Defined Functions
- •Prerequisites
- •Name Precedence
- •7 Common SQL DDL Clauses
- •allocate_extent_clause
- •constraints
- •deallocate_unused_clause
- •file_specification
- •logging_clause
- •parallel_clause
- •physical_attributes_clause
- •storage_clause
- •8 SQL Queries and Subqueries
- •About Queries and Subqueries
- •Creating Simple Queries
- •Hierarchical Queries
- •The UNION [ALL], INTERSECT, MINUS Operators
- •Sorting Query Results
- •Joins
- •Using Subqueries
- •Unnesting of Nested Subqueries
- •Selecting from the DUAL Table
- •Distributed Queries
- •9 SQL Statements: ALTER CLUSTER to ALTER SEQUENCE
- •Types of SQL Statements
- •Organization of SQL Statements
- •ALTER CLUSTER
- •ALTER DATABASE
- •ALTER DIMENSION
- •ALTER FUNCTION
- •ALTER INDEX
- •ALTER INDEXTYPE
- •ALTER JAVA
- •ALTER MATERIALIZED VIEW
- •ALTER MATERIALIZED VIEW LOG
- •ALTER OPERATOR
- •ALTER OUTLINE
- •ALTER PACKAGE
- •ALTER PROCEDURE
- •ALTER PROFILE
- •ALTER RESOURCE COST
- •ALTER ROLE
- •ALTER ROLLBACK SEGMENT
- •ALTER SEQUENCE
- •10 SQL Statements: ALTER SESSION to ALTER SYSTEM
- •ALTER SESSION
- •ALTER SYSTEM
- •ALTER TABLE
- •ALTER TABLESPACE
- •ALTER TRIGGER
- •ALTER TYPE
- •ALTER USER
- •ALTER VIEW
- •ANALYZE
- •ASSOCIATE STATISTICS
- •AUDIT
- •CALL
- •COMMENT
- •COMMIT
- •13 SQL Statements: CREATE CLUSTER to CREATE JAVA
- •CREATE CLUSTER
- •CREATE CONTEXT
- •CREATE CONTROLFILE
- •CREATE DATABASE
- •CREATE DATABASE LINK
- •CREATE DIMENSION
- •CREATE DIRECTORY
- •CREATE FUNCTION
- •CREATE INDEX
- •CREATE INDEXTYPE
- •CREATE JAVA
- •14 SQL Statements: CREATE LIBRARY to CREATE SPFILE
- •CREATE LIBRARY
- •CREATE MATERIALIZED VIEW
- •CREATE MATERIALIZED VIEW LOG
- •CREATE OPERATOR
- •CREATE OUTLINE
- •CREATE PACKAGE
- •CREATE PACKAGE BODY
- •CREATE PFILE
- •CREATE PROCEDURE
- •CREATE PROFILE
- •CREATE ROLE
- •CREATE ROLLBACK SEGMENT
- •CREATE SCHEMA
- •CREATE SEQUENCE
- •CREATE SPFILE
- •15 SQL Statements: CREATE SYNONYM to CREATE TRIGGER
- •CREATE SYNONYM
- •CREATE TABLE
- •CREATE TABLESPACE
- •CREATE TEMPORARY TABLESPACE
- •CREATE TRIGGER
- •CREATE TYPE
- •CREATE TYPE BODY
- •CREATE USER
- •CREATE VIEW
- •DELETE
- •DISASSOCIATE STATISTICS
- •DROP CLUSTER
- •DROP CONTEXT
- •DROP DATABASE LINK
- •DROP DIMENSION
- •DROP DIRECTORY
- •DROP FUNCTION
- •DROP INDEX
- •DROP INDEXTYPE
- •DROP JAVA
- •DROP LIBRARY
- •DROP MATERIALIZED VIEW
- •DROP MATERIALIZED VIEW LOG
- •DROP OPERATOR
- •DROP OUTLINE
- •DROP PACKAGE
- •DROP PROCEDURE
- •DROP PROFILE
- •DROP ROLE
- •DROP ROLLBACK SEGMENT
- •17 SQL Statements: DROP SEQUENCE to ROLLBACK
- •DROP SEQUENCE
- •DROP SYNONYM
- •DROP TABLE
- •DROP TABLESPACE
- •DROP TRIGGER
- •DROP TYPE
- •DROP TYPE BODY
- •DROP USER
- •DROP VIEW
- •EXPLAIN PLAN
- •GRANT
- •INSERT
- •LOCK TABLE
- •MERGE
- •NOAUDIT
- •RENAME
- •REVOKE
- •ROLLBACK
- •18 SQL Statements: SAVEPOINT to UPDATE
- •SAVEPOINT
- •SELECT
- •SET CONSTRAINT[S]
- •SET ROLE
- •SET TRANSACTION
- •TRUNCATE
- •UPDATE
- •Required Keywords and Parameters
- •Optional Keywords and Parameters
- •Syntax Loops
- •Multipart Diagrams
- •Database Objects
- •ANSI Standards
- •ISO Standards
- •Oracle Compliance
- •FIPS Compliance
- •Oracle Extensions to Standard SQL
- •Character Set Support
- •Using Extensible Indexing
- •Using XML in SQL Statements
- •Index

8
SQL Queries and Subqueries
This chapter describes SQL queries and subqueries.
This chapter contains these sections:
■About Queries and Subqueries
■Creating Simple Queries
■Hierarchical Queries
■The UNION [ALL], INTERSECT, MINUS Operators
■Sorting Query Results
■Joins
■Using Subqueries
■Unnesting of Nested Subqueries
■Selecting from the DUAL Table
■Distributed Queries
SQL Queries and Subqueries 8-1

About Queries and Subqueries
About Queries and Subqueries
A query is an operation that retrieves data from one or more tables or views. In this reference, a top-level SELECT statement is called a query, and a query nested within another SQL statement is called a subquery.
This section describes some types of queries and subqueries and how to use them. The top level of the syntax is shown in this chapter.
See Also: SELECT on page 18-4 for the full syntax of all the clauses and the semantics of this statement
select::=
|
for_update_clause |
subquery |
; |
subquery::=
|
|
|
|
DISTINCT |
|
|
|
|
|
UNIQUE |
|
subquery_factoring_clause |
hint |
|
ALL |
|
|
|
|
SELECT |
|
|
select_list |
|
, |
where_clause |
hierarchical_query_clause |
group_by_clause |
|
|
|
||||
FROM |
table_reference |
|
|
|
|
|
|
ALL |
|
|
|
|
|
UNION |
|
|
|
|
|
INTERSECT |
( |
subquery |
) |
HAVING |
condition |
MINUS |
|
|
order_by_clause |
Creating Simple Queries
The list of expressions that appears after the SELECT keyword and before the FROM clause is called the select list. Within the select list, you specify one or more columns in the set of rows you want Oracle to return from one or more tables, views, or materialized views. The number of columns, as well as their datatype and length, are determined by the elements of the select list.
8-2 Oracle9i SQL Reference

Hierarchical Queries
If two or more tables have some column names in common, then you must qualify column names with names of tables. Otherwise, fully qualified column names are optional. However, it is always a good idea to qualify table and column references explicitly. Oracle often does less work with fully qualified table and column names.
You can use a column alias, c_alias, to label the preceding expression in the select list so that the column is displayed with a new heading. The alias effectively renames the select list item for the duration of the query. The alias can be used in the ORDER BY clause, but not other clauses in the query.
You can use comments in a SELECT statement to pass instructions, or hints, to the Oracle optimizer. The optimizer uses hints to choose an execution plan for the statement.
See Also: "Hints" on page 2-91 and Oracle9i Database Performance
Tuning Guide and Reference for more information on hints
Hierarchical Queries
If a table contains hierarchical data, then you can select rows in a hierarchical order using the hierarchical query clause:
hierarchical_query_clause::=
START WITH
condition
CONNECT BY
condition
■START WITH specifies the root row(s) of the hierarchy.
■CONNECT BY specifies the relationship between parent rows and child rows of the hierarchy. In a hierarchical query, one expression in condition must be qualified with the PRIOR operator to refer to the parent row. For example,
... PRIOR expr = expr or
... expr = PRIOR expr
If the CONNECT BY condition is compound, then only one condition requires the PRIOR operator. For example:
CONNECT BY last_name != ’King’ AND PRIOR employee_id = manager_id
In addition, the CONNECT BY condition cannot contain a subquery.
SQL Queries and Subqueries 8-3

Hierarchical Queries
PRIOR is a unary operator and has the same precedence as the unary + and - arithmetic operators. It evaluates the immediately following expression for the parent row of the current row in a hierarchical query.
PRIOR is most commonly used when comparing column values with the equality operator. (The PRIOR keyword can be on either side of the operator.) PRIOR causes Oracle to use the value of the parent row in the column. Operators other than the equal sign (=) are theoretically possible in CONNECT BY clauses. However, the conditions created by these other operators can result in an infinite loop through the possible combinations. In this case Oracle detects the loop at run time and returns an error.
See Also: "Examples" on page 8-5
The manner in which Oracle processes a WHERE clause (if any) in a hierarchical query depends on whether the WHERE clause contains a join:
■If the WHERE predicate contains a join, Oracle applies the join predicates before doing the CONNECT BY processing.
■If the WHERE clause does not contain a join, Oracle applies all predicates other than the CONNECT BY predicates after doing the CONNECT BY processing without affecting the other rows of the hierarchy.
Oracle uses the information from the hierarchical query clause to form the hierarchy using the following steps:
1.Oracle processes the WHERE clause either before or after the CONNECT BY clause depending on whether the WHERE clause contains any join predicates (as described in the preceding bullet list).
2.Oracle selects the root row(s) of the hierarchy—those rows that satisfy the START WITH condition.
3.Oracle selects the child rows of each root row. Each child row must satisfy the condition of the CONNECT BY condition with respect to one of the root rows.
4.Oracle selects successive generations of child rows. Oracle first selects the children of the rows returned in step 3, and then the children of those children, and so on. Oracle always selects children by evaluating the CONNECT BY condition with respect to a current parent row.
5.If the query contains a WHERE clause without a join, then Oracle eliminates all rows from the hierarchy that do not satisfy the condition of the WHERE clause. Oracle evaluates this condition for each row individually, rather than removing all the children of a row that does not satisfy the condition.
8-4 Oracle9i SQL Reference

Hierarchical Queries
6.Oracle returns the rows in the order shown in Figure 8–1. In the diagram, children appear below their parents. For an explanation of hierarchical trees, see Figure 2–1, "Hierarchical Tree" on page 2-86.
Figure 8–1 Hierarchical Queries
ROOT
1
2 |
|
7 |
|
9 |
3 |
4 |
8 |
10 |
12 |
5 |
6 |
|
11 |
|
To find the children of a parent row, Oracle evaluates the PRIOR expression of the CONNECT BY condition for the parent row and the other expression for each row in the table. Rows for which the condition is true are the children of the parent. The CONNECT BY condition can contain other conditions to further filter the rows selected by the query. The CONNECT BY condition cannot contain a subquery.
If the CONNECT BY condition results in a loop in the hierarchy, then Oracle returns an error. A loop occurs if one row is both the parent (or grandparent or direct ancestor) and a child (or a grandchild or a direct descendent) of another row.
Note: In a hierarchical query, do not specify either ORDER BY or GROUP BY, as they will destroy the hierarchical order of the CONNECT BY results. If you want to order rows of siblings of the same parent, then use the ORDER SIBLINGS BY clause. See order_ by_clause on page 18-25.
Examples
The following hierarchical query uses the CONNECT BY clause to define the relationship between employees and managers:
SQL Queries and Subqueries 8-5

Hierarchical Queries
SELECT employee_id, last_name, manager_id
FROM employees
CONNECT BY PRIOR employee_id = manager_id;
EMPLOYEE_ID |
LAST_NAME |
MANAGER_ID |
----------- |
------------------------- ---------- |
|
101 |
Kochhar |
100 |
108 |
Greenberg |
101 |
109 |
Faviet |
108 |
110 |
Chen |
108 |
111 |
Sciarra |
108 |
112 |
Urman |
108 |
113 |
Popp |
108 |
200 |
Whalen |
101 |
. |
|
|
. |
|
|
. |
|
|
The next example is similar to the preceding example, but uses the LEVEL pseudocolumn to show parent and child rows:
SELECT employee_id, last_name, manager_id, LEVEL
FROM employees
CONNECT BY PRIOR employee_id = manager_id;
EMPLOYEE_ID |
LAST_NAME |
MANAGER_ID |
LEVEL |
----------- |
------------------------- ---------- ---------- |
||
101 |
Kochhar |
100 |
1 |
108 |
Greenberg |
101 |
2 |
109 |
Faviet |
108 |
3 |
110 |
Chen |
108 |
3 |
111 |
Sciarra |
108 |
3 |
112 |
Urman |
108 |
3 |
113 |
Popp |
108 |
3 |
... |
|
|
|
Finally, the next example adds a START WITH clause to specify a root row for the hierarchy, and an ORDER BY clause using the SIBLINGS keyword to preserve ordering within the hierarchy:
SELECT last_name, employee_id, manager_id, LEVEL
FROM employees
START WITH employee_id = 100
CONNECT BY PRIOR employee_id = manager_id
ORDER SIBLINGS BY last_name;
8-6 Oracle9i SQL Reference