Amineste

SQL Server UNION vs UNION ALL

Sep 17th, 2014
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
SQL 1.53 KB | None | 0 0
  1. SQL Server UNION vs UNION ALL
  2.  
  3. Hi Friends,
  4.  
  5. Probably, a zillion blog posts AND articles must have been written ON SQL Server UNION vs UNION ALL AND the performance consideration BETWEEN them.
  6.  
  7. Let this one be one OF them too. AND treat this post AS a reminder :)
  8.  
  9. I was at a customer site today reviewing SOME T-SQL code AND I came across a couple OF scripts that used UNION operator instead OF UNION ALL.
  10.  
  11. FROM MSDN:
  12.  
  13. Combines the results OF two OR more queries INTO a single RESULT SET that includes ALL the ROWS that belong TO ALL queries IN the UNION. The UNION operation IS different FROM USING joins that combine COLUMNS FROM two TABLES.
  14.  
  15. The following are basic rules FOR combining the RESULT sets OF two queries BY USING UNION:
  16.  
  17.     The NUMBER AND the ORDER OF the COLUMNS must be the same IN ALL queries.
  18.     The DATA types must be compatible.
  19.  
  20. Further,
  21.  
  22. UNION
  23.  
  24.     Specifies that multiple RESULT sets are TO be combined AND returned AS a single RESULT SET.
  25.  
  26. ALL
  27.  
  28.     Incorporates ALL ROWS INTO the results. This includes duplicates. IF NOT specified, duplicate ROWS are removed.
  29.  
  30. WHEN I asked the developer, why has he used UNION AND IF he specifically wanted the duplicates TO be removed, he looked at me AS IF I just spoke IN Greek. I was stunned too.
  31.  
  32. So WITH this simple example I explained him that UNION ALL performs faster than UNION, simply because UNION ALL does NOT remove duplicates. So IF has no need OF explicitly removing duplicates, he can USE UNION ALL instead.
  33. Link OF picture OF the example
  34. http://adf.ly/s8YIf
Add Comment
Please, Sign In to add comment