A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.w3resource.com/PostgreSQL/snippets/postgresql-union.php below:

Website Navigation


PostgreSQL UNION: Syntax, Examples, and Best Practices

PostgreSQL UNION: Syntax, Examples, and Best PracticesLast update on December 28 2024 13:05:19 (UTC/GMT +8 hours)

PostgreSQL UNION: Combining Query Results

The UNION operator in PostgreSQL combines the results of two or more SELECT queries into a single dataset. By default, it removes duplicate rows. If you want to include duplicates, you can use UNION ALL.

Syntax for Using UNION

SELECT column1, column2 
FROM table1
UNION
SELECT column1, column2 
FROM table2;

Key Points:

Examples of UNION Usage

Example 1: Simple UNION

Code:

-- Select distinct employee names from two departments
SELECT employee_name 
FROM department_a
UNION
SELECT employee_name 
FROM department_b;

Explanation:

Example 2: Using UNION ALL

Code:

-- Select all employee names, including duplicates
SELECT employee_name 
FROM department_a
UNION ALL
SELECT employee_name 
FROM department_b;

Explanation:

Example 3: UNION with Additional Conditions

Code:

-- Combine distinct salaries from two tables with conditions
SELECT salary 
FROM employees
WHERE salary > 50000
UNION
SELECT salary 
FROM contractors
WHERE salary > 50000;

Explanation:

Example 4: Ordering Results in UNION

Code:

-- Combine results and sort the output
SELECT column1 
FROM table1
UNION
SELECT column1 
FROM table2
ORDER BY column1 ASC;

Explanation of code Examples:

Explanation of Code Examples

Best Practices for Using UNION


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4