Difference Between Union Vs Union ALL In Sql


What Is Union In SQL?

The UNION operator is used to combine the result-set of two or more data set .
  • Each SELECT statement within UNION must have the same number of columns
  • The columns must also have similar data types
  • The columns in each SELECT statement must also be in the same order

Difference Between Union and Union ALL In SQL ?


/*Union Removes Duplicate Rows,So it Apply expensive Distinct sort opertaion */

SELECT 1 AS ID,'Anoop' AS Name
UNION
SELECT 1 AS ID,'Anoop' AS Name
UNION
SELECT 2 AS ID,'Manu' AS Name

/*Union ALL Returs All Rows, So it is better to use unionAll instead of union*/

SELECT 1 AS ID,'Anoop' AS Name
UNION ALL
SELECT 1 AS ID,'Anoop' AS Name
UNION ALL
SELECT 2 AS ID,'Manu' AS Name



 

No comments:

Post a comment