From 673dcbfac1c54103d6183473b763779a141341e6 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Tue, 29 Jun 2021 10:16:01 -0500 Subject: [PATCH] Add Union All Rows Including Duplicates as a Postgres til --- README.md | 3 +- .../union-all-rows-including-duplicates.md | 53 +++++++++++++++++++ 2 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 postgres/union-all-rows-including-duplicates.md diff --git a/README.md b/README.md index c87020d..18066f3 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_1133 TILs and counting..._ +_1134 TILs and counting..._ --- @@ -630,6 +630,7 @@ _1133 TILs and counting..._ - [Turning Timing On](postgres/turn-timing-on.md) - [Two Ways To Compute Factorial](postgres/two-ways-to-compute-factorial.md) - [Types By Category](postgres/types-by-category.md) +- [Union All Rows Including Duplicates](postgres/union-all-rows-including-duplicates.md) - [Use A psqlrc File For Common Settings](postgres/use-a-psqlrc-file-for-common-settings.md) - [Use Argument Indexes](postgres/use-argument-indexes.md) - [Use Not Valid To Immediately Enforce A Constraint](postgres/use-not-valid-to-immediately-enforce-a-constraint.md) diff --git a/postgres/union-all-rows-including-duplicates.md b/postgres/union-all-rows-including-duplicates.md new file mode 100644 index 0000000..4b04111 --- /dev/null +++ b/postgres/union-all-rows-including-duplicates.md @@ -0,0 +1,53 @@ +# Union All Rows Including Duplicates + +Two tables or sets of results can be joined together into a single result set +using [the `union` +operator](https://www.postgresql.org/docs/current/queries-union.html). When +combining results with `union`, all duplicate rows will be removed from its +result. + +```sql +> select generate_series(1,4) + union + select generate_series(3,6) + order by 1 asc; + + generate_series +----------------- + 1 + 2 + 3 + 4 + 5 + 6 +(6 rows) +``` + +Notice that despite both sides of the `union` having their own 3 and 4, those +values each only show up once in the result. + +If we don't want duplicates to be excluded, we can use `union all`. + +```sql +> select generate_series(1,4) + union all + select generate_series(3,6) + order by 1 asc; + + generate_series +----------------- + 1 + 2 + 3 + 3 + 4 + 4 + 5 + 6 +(8 rows) +``` + +In this case we have 8 rows instead of 6 with the values 3 and 4 each appearing +twice. + +[source](https://www.postgresqltutorial.com/postgresql-union/)