{"id":478,"date":"2024-11-29T10:52:32","date_gmt":"2024-11-29T03:52:32","guid":{"rendered":"https:\/\/www.pgtutorial.com\/?page_id=478"},"modified":"2025-01-02T10:30:35","modified_gmt":"2025-01-02T03:30:35","slug":"postgresql-union","status":"publish","type":"page","link":"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-union\/","title":{"rendered":"PostgreSQL UNION Operator"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you&#8217;ll learn how to use the PostgreSQL <code>UNION<\/code> operator to combine result sets of two queries into a single result set.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='getting-started-with-the-postgresql-union-operator'>Getting started with the PostgreSQL UNION operator <a href=\"#getting-started-with-the-postgresql-union-operator\" class=\"anchor\" id=\"getting-started-with-the-postgresql-union-operator\" title=\"Anchor for Getting started with the PostgreSQL UNION operator\">#<\/a><\/h2>\n\n\n\n<p>The <code>UNION<\/code> operator allows you to combine the result sets of two or more <a href=\"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-select\/\">queries<\/a> into a single result set. Here&#8217;s the syntax of the <code>UNION<\/code> operator:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"PostgreSQL SQL dialect and PL\/pgSQL\" data-shcb-language-slug=\"pgsql\"><span><code class=\"hljs language-pgsql\"><span class=\"hljs-keyword\">SELECT<\/span> column1, column2 \n<span class=\"hljs-keyword\">FROM<\/span> tableA;\n<span class=\"hljs-keyword\">UNION<\/span>\n<span class=\"hljs-keyword\">SELECT<\/span> column1, column2 \n<span class=\"hljs-keyword\">FROM<\/span> tableB;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PostgreSQL SQL dialect and PL\/pgSQL<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">pgsql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this syntax:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>First, provide two <code><a href=\"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-select\/\">SELECT<\/a><\/code> statements that you want to combine the result sets.<\/li>\n\n\n\n<li>Second, use the <code>UNION<\/code> keyword between the two queries.<\/li>\n<\/ul>\n\n\n\n<p>The <code>UNION<\/code> operator appends the result set of the second <code>SELECT<\/code> statement to the result set of the first <code>SELECT<\/code> statement. Additionally, it removes <em>duplicate rows<\/em> from the final result set:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"973\" height=\"264\" src=\"https:\/\/www.pgtutorial.com\/wp-content\/uploads\/2024\/11\/postgresql-union.png\" alt=\"postgresql union\" class=\"wp-image-513\" srcset=\"https:\/\/www.pgtutorial.com\/wp-content\/uploads\/2024\/11\/postgresql-union.png 973w, https:\/\/www.pgtutorial.com\/wp-content\/uploads\/2024\/11\/postgresql-union-300x81.png 300w, https:\/\/www.pgtutorial.com\/wp-content\/uploads\/2024\/11\/postgresql-union-768x208.png 768w\" sizes=\"auto, (max-width: 973px) 100vw, 973px\" \/><\/figure>\n\n\n\n<p>Both <code>SELECT<\/code> statements must adhere to the following rules:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Return the same number of columns.<\/li>\n\n\n\n<li>The column data types of the corresponding columns must be compatible.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id='setting-up-sample-tables'>Setting up sample tables <a href=\"#setting-up-sample-tables\" class=\"anchor\" id=\"setting-up-sample-tables\" title=\"Anchor for Setting up sample tables\">#<\/a><\/h2>\n\n\n\n<p>Suppose we have two tables:&nbsp;<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The&nbsp;<code>slow_movings<\/code>&nbsp;table stores the slow moving products <\/li>\n\n\n\n<li>The&nbsp;<code>flagships<\/code>&nbsp;table stores the flagship products.<\/li>\n<\/ul>\n\n\n\n<details class=\"wp-block-details is-layout-flow wp-block-details-is-layout-flow\"><summary>The slow_movings and flagships tables:<\/summary><pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"PostgreSQL SQL dialect and PL\/pgSQL\" data-shcb-language-slug=\"pgsql\"><span><code class=\"hljs language-pgsql\"><span class=\"hljs-keyword\">CREATE<\/span> <span class=\"hljs-keyword\">TABLE<\/span> slow_movings (\n  id <span class=\"hljs-type\">INT<\/span> <span class=\"hljs-keyword\">GENERATED<\/span> <span class=\"hljs-keyword\">ALWAYS<\/span> <span class=\"hljs-keyword\">AS<\/span> <span class=\"hljs-keyword\">IDENTITY<\/span> <span class=\"hljs-keyword\">PRIMARY KEY<\/span>,\n  <span class=\"hljs-type\">name<\/span> <span class=\"hljs-type\">VARCHAR<\/span>(<span class=\"hljs-number\">255<\/span>) <span class=\"hljs-keyword\">NOT<\/span> <span class=\"hljs-keyword\">NULL<\/span>,\n  brand <span class=\"hljs-type\">VARCHAR<\/span>(<span class=\"hljs-number\">50<\/span>) <span class=\"hljs-keyword\">NOT<\/span> <span class=\"hljs-keyword\">NULL<\/span>\n);\n\n<span class=\"hljs-keyword\">CREATE<\/span> <span class=\"hljs-keyword\">TABLE<\/span> flagships (\n  id <span class=\"hljs-type\">INT<\/span> <span class=\"hljs-keyword\">GENERATED<\/span> <span class=\"hljs-keyword\">ALWAYS<\/span> <span class=\"hljs-keyword\">AS<\/span> <span class=\"hljs-keyword\">IDENTITY<\/span> <span class=\"hljs-keyword\">PRIMARY KEY<\/span>,\n  <span class=\"hljs-type\">name<\/span> <span class=\"hljs-type\">VARCHAR<\/span>(<span class=\"hljs-number\">255<\/span>) <span class=\"hljs-keyword\">NOT<\/span> <span class=\"hljs-keyword\">NULL<\/span>,\n  brand <span class=\"hljs-type\">VARCHAR<\/span>(<span class=\"hljs-number\">50<\/span>) <span class=\"hljs-keyword\">NOT<\/span> <span class=\"hljs-keyword\">NULL<\/span>\n);\n\n<span class=\"hljs-keyword\">INSERT<\/span> <span class=\"hljs-keyword\">INTO<\/span>\n  slow_movings (<span class=\"hljs-type\">name<\/span>, brand)\n<span class=\"hljs-keyword\">VALUES<\/span>\n  (<span class=\"hljs-string\">'iPhone 16'<\/span>, <span class=\"hljs-string\">'Apple'<\/span>),\n  (<span class=\"hljs-string\">'Galaxy S24'<\/span>, <span class=\"hljs-string\">'Samsung'<\/span>),\n  (<span class=\"hljs-string\">'Pixel 9'<\/span>, <span class=\"hljs-string\">'Google'<\/span>),\n  (<span class=\"hljs-string\">'iPhone 16 Plus'<\/span>, <span class=\"hljs-string\">'Apple'<\/span>),\n  (<span class=\"hljs-string\">'Galaxy Z Flip 6'<\/span>, <span class=\"hljs-string\">'Samsung'<\/span>);\n\n<span class=\"hljs-keyword\">INSERT<\/span> <span class=\"hljs-keyword\">INTO<\/span>\n  flagships (<span class=\"hljs-type\">name<\/span>, brand)\n<span class=\"hljs-keyword\">VALUES<\/span>\n  (<span class=\"hljs-string\">'iPhone 16'<\/span>, <span class=\"hljs-string\">'Apple'<\/span>),\n  (<span class=\"hljs-string\">'Galaxy S24'<\/span>, <span class=\"hljs-string\">'Samsung'<\/span>),\n  (<span class=\"hljs-string\">'Pixel 9'<\/span>, <span class=\"hljs-string\">'Google'<\/span>),\n  (<span class=\"hljs-string\">'iPhone 16 Pro'<\/span>, <span class=\"hljs-string\">'Apple'<\/span>),\n  (<span class=\"hljs-string\">'Galaxy S24 Ultra'<\/span>, <span class=\"hljs-string\">'Samsung'<\/span>);<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PostgreSQL SQL dialect and PL\/pgSQL<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">pgsql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre><\/details>\n\n\n\n<h2 class=\"wp-block-heading\" id='postgresql-union-operator-example'>PostgreSQL UNION operator example <a href=\"#postgresql-union-operator-example\" class=\"anchor\" id=\"postgresql-union-operator-example\" title=\"Anchor for PostgreSQL UNION operator example\">#<\/a><\/h2>\n\n\n\n<p>Suppose you want to get a list of all flagship and slow-moving products.<\/p>\n\n\n\n<p>You can use two <code>SELECT<\/code> statements to retrieve data from the <code>slow_movings<\/code> and <code>flagships<\/code> tables. Then, use the <code>UNION<\/code> operator to append the result set of the second query to the result set of the first query:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"PostgreSQL SQL dialect and PL\/pgSQL\" data-shcb-language-slug=\"pgsql\"><span><code class=\"hljs language-pgsql\"><span class=\"hljs-keyword\">SELECT<\/span>\n  <span class=\"hljs-type\">name<\/span>,\n  brand\n<span class=\"hljs-keyword\">FROM<\/span>\n  slow_movings\n<span class=\"hljs-keyword\">UNION<\/span>\n<span class=\"hljs-keyword\">SELECT<\/span>\n  <span class=\"hljs-type\">name<\/span>,\n  brand\n<span class=\"hljs-keyword\">FROM<\/span>\n  flagships;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PostgreSQL SQL dialect and PL\/pgSQL<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">pgsql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.pgtutorial.com\/playground\/?db=sets&amp;q=U0VMRUNUIG5hbWUsIGJyYW5kIEZST00gc2xvd19tb3ZpbmdzIFVOSU9OIFNFTEVDVCBuYW1lLCBicmFuZCBGUk9NIGZsYWdzaGlwczs\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"plaintext\" data-shcb-language-slug=\"plaintext\"><span><code class=\"hljs language-plaintext\">       name       |  brand\n------------------+---------\n iPhone 16        | Apple\n iPhone 16 Plus   | Apple\n Galaxy Z Flip 6  | Samsung\n Galaxy S24 Ultra | Samsung\n iPhone 16 Pro    | Apple\n Galaxy S24       | Samsung\n Pixel 9          | Google<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">plaintext<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">plaintext<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\" id='using-postgresql-union-with-order-by-clause'>Using PostgreSQL UNION with ORDER BY clause <a href=\"#using-postgresql-union-with-order-by-clause\" class=\"anchor\" id=\"using-postgresql-union-with-order-by-clause\" title=\"Anchor for Using PostgreSQL UNION with ORDER BY clause\">#<\/a><\/h2>\n\n\n\n<p>To sort the result set returned by the <code>UNION<\/code> operator, you can use an <code><a href=\"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-order-by\/\">ORDER BY<\/a><\/code> clause. However, you need to place the <code>ORDER BY<\/code> clause at the end of the second query:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"PostgreSQL SQL dialect and PL\/pgSQL\" data-shcb-language-slug=\"pgsql\"><span><code class=\"hljs language-pgsql\"><span class=\"hljs-keyword\">SELECT<\/span> column1, column2 \n<span class=\"hljs-keyword\">FROM<\/span> tableA;\n<span class=\"hljs-keyword\">UNION<\/span>\n<span class=\"hljs-keyword\">SELECT<\/span> column1, column2 \n<span class=\"hljs-keyword\">FROM<\/span> tableB\n<span class=\"hljs-keyword\">ORDER<\/span> <span class=\"hljs-keyword\">BY<\/span> column1, column2;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PostgreSQL SQL dialect and PL\/pgSQL<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">pgsql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>For example, the following statement uses the <code>UNION<\/code> operator to combine the employee and contractor result sets and uses the <code>ORDER BY<\/code> clause to sort the list by names:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"PostgreSQL SQL dialect and PL\/pgSQL\" data-shcb-language-slug=\"pgsql\"><span><code class=\"hljs language-pgsql\"><span class=\"hljs-keyword\">SELECT<\/span>\n  <span class=\"hljs-type\">name<\/span>,\n  brand\n<span class=\"hljs-keyword\">FROM<\/span>\n  slow_movings\n<span class=\"hljs-keyword\">UNION<\/span>\n<span class=\"hljs-keyword\">SELECT<\/span>\n  <span class=\"hljs-type\">name<\/span>,\n  brand\n<span class=\"hljs-keyword\">FROM<\/span>\n  flagships\n<span class=\"hljs-keyword\">ORDER<\/span> <span class=\"hljs-keyword\">BY<\/span> <span class=\"hljs-type\">name<\/span>;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PostgreSQL SQL dialect and PL\/pgSQL<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">pgsql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.pgtutorial.com\/playground\/?db=sets&amp;q=U0VMRUNUIG5hbWUsIGJyYW5kIEZST00gc2xvd19tb3ZpbmdzIFVOSU9OIFNFTEVDVCBuYW1lLCBicmFuZCBGUk9NIGZsYWdzaGlwcyBPUkRFUiBCWSBuYW1lOw\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"plaintext\" data-shcb-language-slug=\"plaintext\"><span><code class=\"hljs language-plaintext\">       name       |  brand\n------------------+---------\n Galaxy S24       | Samsung\n Galaxy S24 Ultra | Samsung\n Galaxy Z Flip 6  | Samsung\n iPhone 16        | Apple\n iPhone 16 Plus   | Apple\n iPhone 16 Pro    | Apple\n Pixel 9          | Google<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">plaintext<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">plaintext<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\" id='adding-columns-to-result-sets'>Adding columns to result sets <a href=\"#adding-columns-to-result-sets\" class=\"anchor\" id=\"adding-columns-to-result-sets\" title=\"Anchor for Adding columns to result sets\">#<\/a><\/h2>\n\n\n\n<p>Sometimes, you may want an additional column to label where a row comes from which result set. To do that, you specify the fixed value and a column alias as follows:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"PostgreSQL SQL dialect and PL\/pgSQL\" data-shcb-language-slug=\"pgsql\"><span><code class=\"hljs language-pgsql\"><span class=\"hljs-keyword\">SELECT<\/span>\n  column1,\n  column2,\n  <span class=\"hljs-keyword\">value<\/span> <span class=\"hljs-keyword\">AS<\/span> column3\n<span class=\"hljs-keyword\">FROM<\/span>\n  table1\n<span class=\"hljs-keyword\">UNION<\/span>\n<span class=\"hljs-keyword\">SELECT<\/span>\n  column1,\n  column2,\n  <span class=\"hljs-keyword\">value<\/span> <span class=\"hljs-keyword\">AS<\/span> column3\n<span class=\"hljs-keyword\">FROM<\/span>\n  table2\n<span class=\"hljs-keyword\">ORDER<\/span> <span class=\"hljs-keyword\">BY<\/span>\n  sort_expression;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PostgreSQL SQL dialect and PL\/pgSQL<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">pgsql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>For example, you can add the <code>inventory_type<\/code> column to the result set as follows:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-9\" data-shcb-language-name=\"PostgreSQL SQL dialect and PL\/pgSQL\" data-shcb-language-slug=\"pgsql\"><span><code class=\"hljs language-pgsql\"><span class=\"hljs-keyword\">SELECT<\/span>\n  <span class=\"hljs-type\">name<\/span>,\n  brand,\n  <span class=\"hljs-string\">'Slow moving'<\/span> inventory_type\n<span class=\"hljs-keyword\">FROM<\/span>\n  slow_movings\n<span class=\"hljs-keyword\">UNION<\/span>\n<span class=\"hljs-keyword\">SELECT<\/span>\n  <span class=\"hljs-type\">name<\/span>,\n  brand,\n  <span class=\"hljs-string\">'Flagship'<\/span> inventory_type\n<span class=\"hljs-keyword\">FROM<\/span>\n  flagships\n<span class=\"hljs-keyword\">ORDER<\/span> <span class=\"hljs-keyword\">BY<\/span> <span class=\"hljs-type\">name<\/span>;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-9\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PostgreSQL SQL dialect and PL\/pgSQL<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">pgsql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.pgtutorial.com\/playground\/?db=sets&amp;q=U0VMRUNUIG5hbWUsIGJyYW5kLCAnU2xvdyBtb3ZpbmcnIGludmVudG9yeV90eXBlIEZST00gc2xvd19tb3ZpbmdzIFVOSU9OIFNFTEVDVCBuYW1lLCBicmFuZCwgJ0ZsYWdzaGlwJyBpbnZlbnRvcnlfdHlwZSBGUk9NIGZsYWdzaGlwcyBPUkRFUiBCWSBuYW1lOw\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-10\" data-shcb-language-name=\"plaintext\" data-shcb-language-slug=\"plaintext\"><span><code class=\"hljs language-plaintext\">       name       |  brand  | inventory_type\n------------------+---------+----------------\n Galaxy S24       | Samsung | Flagship\n Galaxy S24       | Samsung | Slow moving\n Galaxy S24 Ultra | Samsung | Flagship\n Galaxy Z Flip 6  | Samsung | Slow moving\n iPhone 16        | Apple   | Flagship\n iPhone 16        | Apple   | Slow moving\n iPhone 16 Plus   | Apple   | Slow moving\n iPhone 16 Pro    | Apple   | Flagship\n Pixel 9          | Google  | Flagship\n Pixel 9          | Google  | Slow moving<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-10\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">plaintext<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">plaintext<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\" id='including-duplicate-records-with-union-all-operator'>Including duplicate records with UNION ALL operator <a href=\"#including-duplicate-records-with-union-all-operator\" class=\"anchor\" id=\"including-duplicate-records-with-union-all-operator\" title=\"Anchor for Including duplicate records with UNION ALL operator\">#<\/a><\/h2>\n\n\n\n<p>The following statement uses the <code>UNION<\/code>  operator to combine brand names of flagship and slow moving products:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-11\" data-shcb-language-name=\"PostgreSQL SQL dialect and PL\/pgSQL\" data-shcb-language-slug=\"pgsql\"><span><code class=\"hljs language-pgsql\"><span class=\"hljs-keyword\">SELECT<\/span>\n  brand\n<span class=\"hljs-keyword\">FROM<\/span>\n  slow_movings\n<span class=\"hljs-keyword\">UNION<\/span>\n<span class=\"hljs-keyword\">SELECT<\/span>\n  brand\n<span class=\"hljs-keyword\">FROM<\/span>\n  flagships\n<span class=\"hljs-keyword\">ORDER<\/span> <span class=\"hljs-keyword\">BY<\/span> \n  brand;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-11\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PostgreSQL SQL dialect and PL\/pgSQL<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">pgsql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.pgtutorial.com\/playground\/?db=sets&amp;q=U0VMRUNUIGJyYW5kIEZST00gc2xvd19tb3ZpbmdzIFVOSU9OIFNFTEVDVCBicmFuZCBGUk9NIGZsYWdzaGlwcyBPUkRFUiBCWSBicmFuZDs\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-12\" data-shcb-language-name=\"plaintext\" data-shcb-language-slug=\"plaintext\"><span><code class=\"hljs language-plaintext\">  brand\n---------\n Apple\n Google\n Samsung<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-12\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">plaintext<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">plaintext<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The final result set includes only three distinct brand names. <\/p>\n\n\n\n<p>The reason is that the <code>UNION<\/code> operator removes one duplicate brands names. To keep the duplicate rows, you can use the <code>UNION ALL<\/code> operator.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='postgresql-union-all-operator'>PostgreSQL UNION ALL operator <a href=\"#postgresql-union-all-operator\" class=\"anchor\" id=\"postgresql-union-all-operator\" title=\"Anchor for PostgreSQL UNION ALL operator\">#<\/a><\/h2>\n\n\n\n<p>The <code>UNION ALL<\/code> operator appends the second query&#8217;s result set to the first query&#8217;s result set and keep the duplicate row in the final result set:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-13\" data-shcb-language-name=\"PostgreSQL SQL dialect and PL\/pgSQL\" data-shcb-language-slug=\"pgsql\"><span><code class=\"hljs language-pgsql\"><span class=\"hljs-keyword\">SELECT<\/span> column1, column2 \n<span class=\"hljs-keyword\">FROM<\/span> tableA;\n<span class=\"hljs-keyword\">UNION<\/span> <span class=\"hljs-keyword\">ALL<\/span>\n<span class=\"hljs-keyword\">SELECT<\/span> column1, column2 \n<span class=\"hljs-keyword\">FROM<\/span> tableB;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-13\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PostgreSQL SQL dialect and PL\/pgSQL<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">pgsql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"973\" height=\"305\" src=\"https:\/\/www.pgtutorial.com\/wp-content\/uploads\/2024\/11\/postgresql-union-all.png\" alt=\"postgresql union all\" class=\"wp-image-515\" srcset=\"https:\/\/www.pgtutorial.com\/wp-content\/uploads\/2024\/11\/postgresql-union-all.png 973w, https:\/\/www.pgtutorial.com\/wp-content\/uploads\/2024\/11\/postgresql-union-all-300x94.png 300w, https:\/\/www.pgtutorial.com\/wp-content\/uploads\/2024\/11\/postgresql-union-all-768x241.png 768w\" sizes=\"auto, (max-width: 973px) 100vw, 973px\" \/><\/figure>\n\n\n\n<p>For example, the following statement uses the <code>UNION ALL<\/code> operator to retrieve all employee and contractor names:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-14\" data-shcb-language-name=\"PostgreSQL SQL dialect and PL\/pgSQL\" data-shcb-language-slug=\"pgsql\"><span><code class=\"hljs language-pgsql\"><span class=\"hljs-keyword\">SELECT<\/span>\n  brand\n<span class=\"hljs-keyword\">FROM<\/span>\n  slow_movings\n<span class=\"hljs-keyword\">UNION<\/span> <span class=\"hljs-keyword\">ALL<\/span>\n<span class=\"hljs-keyword\">SELECT<\/span>\n  brand\n<span class=\"hljs-keyword\">FROM<\/span>\n  flagships\n<span class=\"hljs-keyword\">ORDER<\/span> <span class=\"hljs-keyword\">BY<\/span> \n  brand;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-14\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PostgreSQL SQL dialect and PL\/pgSQL<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">pgsql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.pgtutorial.com\/playground\/?db=sets&amp;q=U0VMRUNUIGJyYW5kIEZST00gc2xvd19tb3ZpbmdzIFVOSU9OIEFMTCBTRUxFQ1QgYnJhbmQgRlJPTSBmbGFnc2hpcHMgT1JERVIgQlkgYnJhbmQ7\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-15\" data-shcb-language-name=\"plaintext\" data-shcb-language-slug=\"plaintext\"><span><code class=\"hljs language-plaintext\">  brand\n---------\n Apple\n Apple\n Apple\n Apple\n Google\n Google\n Samsung\n Samsung\n Samsung\n Samsung<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-15\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">plaintext<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">plaintext<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\" id='summary'>Summary <a href=\"#summary\" class=\"anchor\" id=\"summary\" title=\"Anchor for Summary\">#<\/a><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use the <code>UNION<\/code> operator to append the result set of a query to the result set of another query and remove the duplicate rows in the final result set.<\/li>\n\n\n\n<li>Use the <code>UNION ALL<\/code> operator to keep the duplicate rows<\/li>\n\n\n\n<li>Place the <code>ORDER BY<\/code> clause at the end of the second query to sort the rows in the final result set.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id='quiz'>Quiz <a href=\"#quiz\" class=\"anchor\" id=\"quiz\" title=\"Anchor for Quiz\">#<\/a><\/h2>\n\n\n\n<iframe loading=\"lazy\"\n  name=\"quiz\"\n  src=\"\/quiz\/?quiz=union\"\n  height=\"700\"\n  width=\"600\"\n  class=\"iframe\"\n><\/iframe>\n\n<div class=\"helpful-block-content\" data-title=\"\">\n\t<header>\n\t\t<div class=\"wth-question\">Was this tutorial helpful ?<\/div>\n\t\t<div class=\"wth-thumbs\">\n\t\t\t<button\n\t\t\t\tdata-post=\"478\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-union\/\"\n\t\t\t\tdata-post-title=\"PostgreSQL UNION Operator\"\n\t\t\t\tdata-response=\"1\"\n\t\t\t\tclass=\"wth-btn-rounded wth-yes-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\tclass=\"feather feather-thumbs-up block w-full h-full\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> Yes <\/span>\n\t\t\t<\/button>\n\n\t\t\t<button\n\t\t\t\tdata-response=\"0\"\n\t\t\t\tdata-post=\"478\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-union\/\"\n\t\t\t\tdata-post-title=\"PostgreSQL UNION Operator\"\n\t\t\t\tclass=\"wth-btn-rounded wth-no-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> No <\/span>\n\t\t\t<\/button>\n\t\t<\/div>\n\t<\/header>\n\n\t<div class=\"wth-form hidden\">\n\t\t<div class=\"wth-form-wrapper\">\n\t\t\t<div class=\"wth-title\"><\/div>\n\t\t\t\n\t\t\t<textarea class=\"wth-message\"><\/textarea>\n\n\t\t\t<button class=\"btn btn-primary wth-btn-submit\">Send<\/button>\n\t\t\t<button class=\"btn wth-btn-cancel\">Cancel<\/button>\n\t\t\n\t\t<\/div>\n\t<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, you&#8217;ll learn how to use the PostgreSQL UNION operator to combine result sets of two queries into a single result set.<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":13,"menu_order":34,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-478","page","type-page","status-publish","hentry"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.5 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>PostgreSQL UNION Operator<\/title>\n<meta name=\"description\" content=\"In this tutorial, you&#039;ll learn how to use the PostgreSQL UNION operator to combine result sets of two queries into a single result set.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-union\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"PostgreSQL UNION Operator\" \/>\n<meta property=\"og:description\" content=\"In this tutorial, you&#039;ll learn how to use the PostgreSQL UNION operator to combine result sets of two queries into a single result set.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-union\/\" \/>\n<meta property=\"og:site_name\" content=\"PostgreSQL Tutorial\" \/>\n<meta property=\"article:modified_time\" content=\"2025-01-02T03:30:35+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.pgtutorial.com\/wp-content\/uploads\/2024\/11\/postgresql-union.png\" \/>\n\t<meta property=\"og:image:width\" content=\"973\" \/>\n\t<meta property=\"og:image:height\" content=\"264\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data1\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.pgtutorial.com\\\/postgresql-tutorial\\\/postgresql-union\\\/\",\"url\":\"https:\\\/\\\/www.pgtutorial.com\\\/postgresql-tutorial\\\/postgresql-union\\\/\",\"name\":\"PostgreSQL UNION Operator\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.pgtutorial.com\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/www.pgtutorial.com\\\/postgresql-tutorial\\\/postgresql-union\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/www.pgtutorial.com\\\/postgresql-tutorial\\\/postgresql-union\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.pgtutorial.com\\\/wp-content\\\/uploads\\\/2024\\\/11\\\/postgresql-union.png\",\"datePublished\":\"2024-11-29T03:52:32+00:00\",\"dateModified\":\"2025-01-02T03:30:35+00:00\",\"description\":\"In this tutorial, you'll learn how to use the PostgreSQL UNION operator to combine result sets of two queries into a single result set.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.pgtutorial.com\\\/postgresql-tutorial\\\/postgresql-union\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.pgtutorial.com\\\/postgresql-tutorial\\\/postgresql-union\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.pgtutorial.com\\\/postgresql-tutorial\\\/postgresql-union\\\/#primaryimage\",\"url\":\"https:\\\/\\\/www.pgtutorial.com\\\/wp-content\\\/uploads\\\/2024\\\/11\\\/postgresql-union.png\",\"contentUrl\":\"https:\\\/\\\/www.pgtutorial.com\\\/wp-content\\\/uploads\\\/2024\\\/11\\\/postgresql-union.png\",\"width\":973,\"height\":264,\"caption\":\"postgresql union\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.pgtutorial.com\\\/postgresql-tutorial\\\/postgresql-union\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.pgtutorial.com\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"PostgreSQL Tutorial\",\"item\":\"https:\\\/\\\/www.pgtutorial.com\\\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"PostgreSQL UNION Operator\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.pgtutorial.com\\\/#website\",\"url\":\"https:\\\/\\\/www.pgtutorial.com\\\/\",\"name\":\"PostgreSQL Tutorial\",\"description\":\"Learn PostgreSQL from Scratch\",\"alternateName\":\"PostgreSQL\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.pgtutorial.com\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"PostgreSQL UNION Operator","description":"In this tutorial, you'll learn how to use the PostgreSQL UNION operator to combine result sets of two queries into a single result set.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-union\/","og_locale":"en_US","og_type":"article","og_title":"PostgreSQL UNION Operator","og_description":"In this tutorial, you'll learn how to use the PostgreSQL UNION operator to combine result sets of two queries into a single result set.","og_url":"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-union\/","og_site_name":"PostgreSQL Tutorial","article_modified_time":"2025-01-02T03:30:35+00:00","og_image":[{"width":973,"height":264,"url":"https:\/\/www.pgtutorial.com\/wp-content\/uploads\/2024\/11\/postgresql-union.png","type":"image\/png"}],"twitter_card":"summary_large_image","twitter_misc":{"Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-union\/","url":"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-union\/","name":"PostgreSQL UNION Operator","isPartOf":{"@id":"https:\/\/www.pgtutorial.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-union\/#primaryimage"},"image":{"@id":"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-union\/#primaryimage"},"thumbnailUrl":"https:\/\/www.pgtutorial.com\/wp-content\/uploads\/2024\/11\/postgresql-union.png","datePublished":"2024-11-29T03:52:32+00:00","dateModified":"2025-01-02T03:30:35+00:00","description":"In this tutorial, you'll learn how to use the PostgreSQL UNION operator to combine result sets of two queries into a single result set.","breadcrumb":{"@id":"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-union\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-union\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-union\/#primaryimage","url":"https:\/\/www.pgtutorial.com\/wp-content\/uploads\/2024\/11\/postgresql-union.png","contentUrl":"https:\/\/www.pgtutorial.com\/wp-content\/uploads\/2024\/11\/postgresql-union.png","width":973,"height":264,"caption":"postgresql union"},{"@type":"BreadcrumbList","@id":"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-union\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.pgtutorial.com\/"},{"@type":"ListItem","position":2,"name":"PostgreSQL Tutorial","item":"https:\/\/www.pgtutorial.com\/"},{"@type":"ListItem","position":3,"name":"PostgreSQL UNION Operator"}]},{"@type":"WebSite","@id":"https:\/\/www.pgtutorial.com\/#website","url":"https:\/\/www.pgtutorial.com\/","name":"PostgreSQL Tutorial","description":"Learn PostgreSQL from Scratch","alternateName":"PostgreSQL","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.pgtutorial.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"}]}},"_links":{"self":[{"href":"https:\/\/www.pgtutorial.com\/wp-json\/wp\/v2\/pages\/478","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.pgtutorial.com\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.pgtutorial.com\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.pgtutorial.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.pgtutorial.com\/wp-json\/wp\/v2\/comments?post=478"}],"version-history":[{"count":11,"href":"https:\/\/www.pgtutorial.com\/wp-json\/wp\/v2\/pages\/478\/revisions"}],"predecessor-version":[{"id":1349,"href":"https:\/\/www.pgtutorial.com\/wp-json\/wp\/v2\/pages\/478\/revisions\/1349"}],"up":[{"embeddable":true,"href":"https:\/\/www.pgtutorial.com\/wp-json\/wp\/v2\/pages\/13"}],"wp:attachment":[{"href":"https:\/\/www.pgtutorial.com\/wp-json\/wp\/v2\/media?parent=478"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}