The UNION ALL query allows you to combine the result sets of 2 or more "select" queries. It returns all rows (even if the row exists in more than one of the "select" statements).
Each SQL statement within the UNION ALL query must have the same number of fields in the result sets with similar data types.
The syntax for a UNION ALL query is:
select field1, field2, . field_n
from tables
UNION ALL
select field1, field2, . field_n
from tables;
Example #1
The following is an example of a UNION ALL query:
select supplier_id
from suppliers
UNION ALL
select supplier_id
from orders;
If a supplier_id appeared in both the suppliers and orders table, it would appear multiple times in your result set. The UNION ALL does not remove duplicates.
Example #2 - With ORDER BY Clause
The following is a UNION query that uses an ORDER BY clause:
select supplier_id, supplier_name
from suppliers
where supplier_id > 2000
UNION ALL
select company_id, company_name
from companies
where company_id > 1000
ORDER BY 2;
Since the column names are different between the two "select" statements, it is more advantageous to reference the columns in the ORDER BY clause by their position in the result set. In this example, we've sorted the results by supplier_name / company_name in ascending order, as denoted by the "ORDER BY 2".
The supplier_name / company_name fields are in position #2 in the result set.
SQL: UNION ALL Query
·
Recent Tutorials
Categories
- Learning PL/SQL (13)
- Oracle 10g (34)
- Oracle PL/SQL (12)
- Oracle SQL (9)
- SQL and PL/SQL (2)
Blog Archive
-
▼
2008
(134)
-
▼
February
(52)
- Transaction Management
- Oracle Commands
- Oracle concepts
- Oracle Concepts - grant user privileges
- SQL: VIEWS
- SQL: Local Temporary tables
- SQL: Global Temporary tables
- SQL: DROP Table
- SQL: ALTER Table
- SQL: CREATE Table from another table
- SQL: CREATE Table
- SQL Topics: Tables
- SQL: DELETE Statement
- SQL: INSERT Statement
- SQL: UPDATE Statement
- SQL: MINUS Query
- SQL: INTERSECT Query
- SQL: UNION ALL Query
- SQL: UNION Query
- SQL: Joins
- SQL: ORDER BY Clause
- SQL: HAVING Clause
- SQL: GROUP BY Clause
- SQL: EXISTS Condition
- SQL: BETWEEN Condition
- SQL: "IN" Function
- SQL: LIKE Condition
- SQL: Combining the "AND" and "OR" Conditions
- SQL: "OR" Condition
- SQL: "AND" Condition
- SQL: WHERE Clause
- SQL: MAX Function
- SQL: MIN Function
- SQL: SUM Function
- SQL: COUNT Function
- SQL: DISTINCT Clause
- SQL: SELECT Statement
- SQL: Data Types
- SQL Topics
- ORACLE Architecture
- Oracle FAQ's Part-12
- Oracle FAQ's Part-11
- Oracle FAQ's Part-10
- Oracle FAQ's Part-9
- Oracle FAQ's Part-8
- Oracle FAQ's Part-7
- Oracle FAQ's Part-6
- Oracle FAQ's Part-5
- Oracle FAQ's Part-4
- Oracle FAQ's Part-3
- Oracle FAQ's Part-2
- Oracle FAQ's Part-1
-
▼
February
(52)