DB2 - Exemplos simples - UNION vs UNION ALL



Desenvolvido por DORNELLES Carlos Alberto - Analista de Sistemas - Brasília DF. - cad_cobol@hotmail.com

DB2 - Exemplos simples - UNION vs UNION ALL


A UNION operation combines two sets of columns and removes duplicates.
The UNION ALL expression does the same but does not remove the duplicates.
When DB2 encounters the keyword, it processes each select/sub-select to form an interim result table, then it combines the interim result table and deletes duplicate rows to form a combined result table working similar as a JOIN.


To use this clause, each SELECT statement must have

  • The same number of columns selected.
  • The same number of column expressions.
  • The same data type and have them in the same order.

Uma operação UNION combina dois conjuntos de colunas e remove duplicatas.
A expressão UNION ALL faz o mesmo, mas não remove as duplicatas.
Quando o DB2 encontra a palavra-chave, ele processa cada seleção/sub-seleção para formar uma tabela de resultados provisória e, em seguida, combina a tabela de resultados provisória e exclui linhas duplicadas para formar uma tabela de resultados combinada funcionando de maneira semelhante a JOIN.

Para usar esta cláusula, cada instrução SELECT deve ter

  • O mesmo número de colunas selecionadas.
  • O mesmo número de expressões de coluna.
  • O mesmo tipo de dados e na mesma ordem.

    Syntax:

    SELECT column1 [, column2 ]
      FROM table1 [, table2 ]
    [WHERE condition]
     UNION / UNION ALL
    SELECT column1 [, column2 ]
      FROM table1 [, table2 ]
    [WHERE condition]	 

Note:

When including the UNION ALL in the same SQL statement as a UNION operator, however, the result of the operation depends on the order of evaluation.
Where there are no parentheses, evaluation is from left to right.
Where parentheses are included, the parenthesized sub-select is evaluated first, followed, from left to right, by the other parts of the statement.

Recursive SQL requires that there be a UNION ALL phrase between the two main parts of the statement.
As UNION ALL, unlike the UNION, allows for duplicate output rows which is what often comes out of recursive processing.
Let’s consider below example.

Nota:

Ao incluir UNION ALL na mesma instrução SQL como um operador UNION, no entanto, o resultado da operação depende da ordem de avaliação.
Onde não há parênteses, a avaliação é da esquerda para a direita.
Onde os parênteses são incluídos, a sub-seleção entre parênteses é avaliada primeiro, seguida, da esquerda para a direita, pelas outras partes da instrução.

O SQL recursivo requer que haja uma frase UNION ALL entre as duas partes principais da instrução.
Como UNION ALL, ao contrário de UNION, permite linhas de saída duplicadas, o que geralmente resulta do processamento recursivo.
Vamos considerar o exemplo abaixo



    ------------------------------------------ 
    Table R1                          Table R2
    ------------------------------------------ 
 
    Abhi                              Abhi
    Abhi                              Abhi
    Abhi                              Baby
    Baby                              Baby
    Baby                              Baby
    Cat                               Cat
    Cat                               Dan
    Cat
    Elie
 
    SELECT R1
      FROM R1
     UNION / UNION ALL
    SELECT R2
      FROM R2
     ORDER BY 1;

    ------------------------------------------ 
    UNION              UNION ALL
    ------------------------------------------ 
 
    Abhi               Abhi      
    Baby               Abhi      
    Cat                Abhi      
    Dan                Abhi      
    Elie               Abhi      
                       Baby
                       Baby
                       Baby
                       Baby
                       Baby
                       Cat
                       Cat
                       Cat
                       Cat
                       Dan
                      Elie

When you use :

  • Any ORDER BY clause must appear after the last sub-select that is part of the union.
    In this example, the results are sequenced on the basis of the first selected column, R1.
    The ORDER BY clause specifies that the combined result table is to be in a collated sequence.
    ORDER BY is not allowed in a view.



  • A name may be specified on the ORDER BY clause if the result columns are named.
    A result column is named if the corresponding columns in each of the unioned select-statements have the same name.
    An AS clause can be used to assign a name to columns in the select list.

Quando você usa:

  • Qualquer cláusula ORDER BY deve aparecer após a última sub-seleção que faz parte da união.
    Neste exemplo, os resultados são sequenciados com base na primeira coluna selecionada, R1.
    A cláusula ORDER BY especifica que a tabela de resultados combinados deve estar em uma sequência agrupada.
    ORDER BY não é permitido em uma visualização.

  • Um nome pode ser especificado na cláusula ORDER BY se as colunas de resultado forem nomeadas.
    Uma coluna de resultado será nomeada se as colunas correspondentes em cada uma das instruções de seleção unidas tiverem o mesmo nome.
    Uma cláusula AS pode ser usada para atribuir um nome às colunas na lista de seleção.

    SELECT A + B AS X …
     UNION
    SELECT X … ORDER BY X

If the result columns are unnamed, use a positive integer to order the result.


The number refers to the position of the expression in the list of expressions you include in your sub-selects.

Se as colunas de resultado não tiverem nome, use um número inteiro positivo para ordenar o resultado.

O número refere-se à posição da expressão na lista de expressões que você inclui em suas sub-seleções.


    SELECT A + B …
     UNION
    SELECT X 
    ........
     ORDER BY 1