0 votes
in Sql by
What are UNION, MINUS and INTERSECT commands?

1 Answer

0 votes
by

The UNION operator combines and returns the result-set retrieved by two or more SELECT statements.

The MINUS operator in SQL is used to remove duplicates from the result-set obtained by the second SELECT query from the result-set obtained by the first SELECT query and then return the filtered results from the first.

The INTERSECT clause in SQL combines the result-set fetched by the two SELECT statements where records from one match the other and then returns this intersection of result-sets.

Certain conditions need to be met before executing either of the above statements in SQL -

Each SELECT statement within the clause must have the same number of columns

The columns must also have similar data types

The columns in each SELECT statement should necessarily have the same order

SELECT name FROM Students /* Fetch the union of queries */

UNION

SELECT name FROM Contacts;

SELECT name FROM Students /* Fetch the union of queries with duplicates*/

UNION ALL

SELECT name FROM Contacts;

SELECT name FROM Students /* Fetch names from students */

MINUS /* that aren't present in contacts */

SELECT name FROM Contacts;

SELECT name FROM Students /* Fetch names from students */

INTERSECT /* that are present in contacts as well */

SELECT name FROM Contacts;

Q   =>   Write a SQL query to fetch "names" that are present in either table "accounts" or in table "registry".

Q   =>   Write a SQL query to fetch "names" that are present in "accounts" but not in table "registry".

Q   =>   Write a SQL query to fetch "names" from table "contacts" that are neither present in "accounts.name" nor in "registry.name".

...