[SQL Must Know and Know] - Lesson 14 Combined Query

Table of contents

Composite query

Create composite queries

        Use UNION

        UNION rules

        Include or suppress duplicate rows

        Sort combined query results

        Other types of UNION

        operate on multiple tables


Composite query

        Most SQL queries consist of a single SELECT statement that returns data from one or more tables. However, SQL also allows multiple queries (multiple SELECT statements) to be executed and the results returned as one query result set. These combined queries are often called union or compound queries.

        There are two main situations where you need to use combined queries:

  • return structured data from different tables in one query;
  • Execute multiple queries against a table, returning data as a single query.

        In most cases, two queries combining the same tables accomplish the same work as one query with multiple WHERE clause conditions. In other words, any SELECT statement with multiple WHERE clauses can be used as a composite query.


Create composite queries

        Several SQL queries can be combined using the UNION operator.


        Use UNION

        Using UNION is very simple, all you have to do is give each SELECT statement and put the keyword UNION between each statement.

        Creating a UNION involves writing multiple SELECT statements. First look at a single statement:

SELECT cust_name, cust_contact, cust_email
FROM Customers
WHERE cust_state IN ('IL','IN','MI');
SELECT cust_name, cust_contact, cust_email
FROM Customers
WHERE cust_name = 'Fun4All';

        The first SELECT passes the state abbreviations for Illinois, Indiana, Michigan, etc. to the IN clause, which retrieves all the rows for those states. The second SELECT finds all Fun4All using a simple equality test.

        Combining these two statements can be done as follows:

SELECT cust_name, cust_contact, cust_email
FROM Customers
WHERE cust_state IN ('IL','IN','MI')
UNION
SELECT cust_name, cust_contact, cust_email
FROM Customers
WHERE cust_name = 'Fun4All';

        For reference, here is the same query using multiple WHERE clauses instead of UNION:

SELECT cust_name, cust_contact, cust_email
FROM Customers
WHERE cust_state IN ('IL','IN','MI')
OR cust_name = 'Fun4All';

        UNION rules

        As you can see, UNION is very easy to use, but there are a few rules to be aware of when combining them.

  • UNION must consist of two or more SELECT statements separated by the keyword UNION (so if you combine four SELECT statements, you will use three UNION keywords).
  • Each query in the UNION must contain the same columns, expressions, or aggregate functions (however, the individual columns do not need to be listed in the same order).
  • The column data types must be compatible: the types do not have to be identical, but must be types that the DBMS can convert implicitly (for example, different numeric types or different date types).

        As long as the query fields are the same, there is no strict requirement on the sequence.

        Provided these basic rules or restrictions are followed, UNION can be used for any data retrieval operation.


        Include or suppress duplicate rows

        When using UNION, duplicate rows are automatically canceled. This is the default behavior of UNION, you can change it if you wish. In fact, if you want to return all matching rows, you can use UNION ALL instead of UNION.

        simply put:

  •    union : remove duplicate rows
  • union all: keep duplicate rows

        Note what repetition means here:

        Duplication means whether the field you inquired is repeated or not. Whether the field you have not inquired is repeated or not does not affect the result. Only the field you inquired affects your result.

        If you use where, repetition means that all columns are repeated, and whether the fields you have not queried are repeated will affect the result.


        Sort combined query results

        The output of the SELECT statement is ordered using the ORDER BY clause. When combining queries with UNION, only one ORDER BY clause can be used, and it must be located after the last SELECT statement. For result sets, there is no case where one part is sorted one way and another part is sorted another way, so multiple ORDER BY clauses are not allowed .

SELECT cust_name, cust_contact, cust_email
FROM Customers
WHERE cust_state IN ('IL','IN','MI')
UNION
SELECT cust_name, cust_contact, cust_email
FROM Customers
WHERE cust_name = 'Fun4All'
ORDER BY cust_name, cust_contact;

        This UNION uses an ORDER BY clause after the last SELECT statement. Although the ORDER BY clause appears to be only part of the last SELECT statement, it is actually used by the DBMS to order all the results returned by all SELECT statements .


        Other types of UNION

        Some DBMSs also support two other kinds of UNION: EXCEPT (sometimes called MINUS) can be used to retrieve rows that exist only in the first table but not in the second table; Existing row. In practice, these UNIONs are rarely used, since the same result can be obtained with joins.


        operate on multiple tables

        For simplicity, the examples in this lesson use UNION to combine multiple queries against the same table. In fact, UNION is also useful when you need to combine data from multiple tables, even tables with mismatching column names, in which case you can combine UNION with aliases to retrieve a single result set.

Guess you like

Origin blog.csdn.net/qq_57163366/article/details/130102099