44
loading...
This website collects cookies to deliver better user experience
UNION
s can be quite confusing at first. In this quick post we are going to learn what the difference between UNION
and UNION ALL
is!UNION
it would remove the duplicate records from the two columns, where as UNION ALL
does not remove the duplicates.UNION
, your database server would need to do some extra operations in order to get rid of the duplicate values, which essentially would be slower compared to using UNION ALL
where the database server would not have to do this extra work. However UNION
is more commonly used as in most cases you do not need the duplicate records.id
, username
id
, username
SELECT id,username FROM users;
// Output:
+----+----------+
| id | username |
+----+----------+
| 1 | bobby |
| 2 | devdojo |
| 3 | tony |
| 4 | greisi |
+----+----------+
SELECT id,username FROM admins;
// Output:
+------+----------+
| id | username |
+------+----------+
| 1 | bobby |
| 4 | greisi |
+------+----------+
UNION
your database would do the extra work that we mentioned above, and get rid of the duplicate rows, in our case we have bobby
and greisi
present in both tables, so if we were to run the following query:SELECT id,username FROM users UNION SELECT * FROM admins;
// Output
+------+----------+
| id | username |
+------+----------+
| 1 | bobby |
| 2 | devdojo |
| 3 | tony |
| 4 | greisi |
+------+----------+
UNION
the UNION ALL
statement would keep the duplicates.UNION ALL
instead:SELECT id,username FROM users UNION ALL SELECT * FROM admins;
+------+----------+
| id | username |
+------+----------+
| 1 | bobby |
| 2 | devdojo |
| 3 | tony |
| 4 | greisi |
| 1 | bobby |
| 4 | greisi |
+------+----------+
admins
table were directly appended after the users
rows including the duplicated values.UNION
and UNION ALL
is!