What is union and minus in sql
In SQL, `UNION` and `MINUS` are set operators used to combine or compare the results of two or more queries.
1. UNION: The `UNION` operator is used to combine the results of two or more `SELECT` statements into a single result set. It removes duplicate rows from the result set by default. The column names and data types of the result columns must match in all `SELECT` statements being combined. Here's a basic syntax:
-----sql
SELECT column1, column2, ...
FROM table1
UNION
SELECT column1, column2, ...
FROM table2;
-----
This query retrieves rows from `table1` and `table2`, combines the results, and removes any duplicate rows.
2. MINUS (also known as `EXCEPT` in some database systems): The `MINUS` operator is used to subtract the result set of one `SELECT` statement from the result set of another `SELECT` statement. It returns rows that are present in the first query result set but not in the second query result set. Like `UNION`, the column names and data types of the result columns must match in both queries. Here's a basic syntax:
----sql
SELECT column1, column2, ...
FROM table1
MINUS
SELECT column1, column2, ...
FROM table2;
-----
This query retrieves rows from `table1` that do not exist in `table2`.
These set operators are useful for combining or comparing data from multiple tables or queries and are commonly used in SQL queries to achieve specific result set requirements.
Comments
Post a Comment