Let's understand Mainframe
Home Tutorials Interview Q&A Quiz Mainframe Memes Contact us About us

Module 6: DB2 SQL Functions, Joins and Subqueries


UNION and UNION ALL

What is UNION

  • Two tables, or two query results, can be combined into a single result table with UNION.
  • Both SELECT statements must return the same number of columns with compatible data types.
  • The column names of the combined result come from the first SELECT.

UNION vs UNION ALL

  • UNION removes duplicate rows. Removing duplicates needs a sort, so it is slower.
  • UNION ALL keeps duplicate rows. No sort is needed, so it is faster.
  • Choose UNION ALL when duplicates are impossible or when you want to keep them.
  • Example:-
    -- Combined list, duplicates removed SELECT EMPNO, FNAME FROM EMPS_A UNION SELECT EMPNO, FNAME FROM EMPS_B; -- Combined list, duplicates kept, runs faster SELECT EMPNO, FNAME FROM EMPS_A UNION ALL SELECT EMPNO, FNAME FROM EMPS_B;





© copyright mainframebug.com
Privacy Policy
MainframeBug Assistant