{"id":589,"date":"2024-12-03T11:20:32","date_gmt":"2024-12-03T04:20:32","guid":{"rendered":"https:\/\/www.pgtutorial.com\/?page_id=589"},"modified":"2025-02-06T14:30:49","modified_gmt":"2025-02-06T07:30:49","slug":"postgresql-subquery","status":"publish","type":"page","link":"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-subquery\/","title":{"rendered":"PostgreSQL Subquery"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: In this tutorial, you will learn how to use PostgreSQL subquery to write more flexible queries in a more simple way.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='getting-started-with-postgresql-subquery'>Getting Started with PostgreSQL Subquery <a href=\"#getting-started-with-postgresql-subquery\" class=\"anchor\" id=\"getting-started-with-postgresql-subquery\" title=\"Anchor for Getting Started with PostgreSQL Subquery\">#<\/a><\/h2>\n\n\n\n<p>PostgreSQL allows you to embed a query within another query. This embedded query is called a <em>subquery<\/em>. The query that contains a subquery is called an <em>outer query<\/em>.<\/p>\n\n\n\n<p>In essence, a subquery is a query embedded within an outer query.<\/p>\n\n\n\n<p>The first important question is where to place the subquery inside a query. <\/p>\n\n\n\n<p>To answer this question, let&#8217;s take another look at the <code>SELECT<\/code> statement:<\/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>\n  select_list\n<span class=\"hljs-keyword\">FROM<\/span>\n  table1\n  <span class=\"hljs-keyword\">JOIN<\/span> table2 <span class=\"hljs-keyword\">ON<\/span> join_condition;\n<span class=\"hljs-keyword\">WHERE<\/span>\n  condition;<\/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 <code>SELECT<\/code> statement:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The <code>SELECT<\/code> clause can accept a single value (an expression or a column).<\/li>\n\n\n\n<li>The <code>FROM<\/code> and <code><a href=\"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-inner-join\/\">JOIN<\/a><\/code> clauses can accept table or a result set that consists of rows and columns.<\/li>\n\n\n\n<li>The <code><a href=\"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-where\/\">WHERE<\/a><\/code> clause can accept a single value or column depending on the operator of the condition.<\/li>\n<\/ul>\n\n\n\n<p>Depending on the shape of the data each clause accepts, you can use an appropriate subquery.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='postgresql-subquery-in-the-where-clause'>PostgreSQL subquery in the WHERE clause <a href=\"#postgresql-subquery-in-the-where-clause\" class=\"anchor\" id=\"postgresql-subquery-in-the-where-clause\" title=\"Anchor for PostgreSQL subquery in the WHERE clause\">#<\/a><\/h2>\n\n\n\n<p>Image you want to find the most expensive products in the <code>products<\/code> table. To do that, you might perform two queries:<\/p>\n\n\n\n<p>First, select the highest price from the <code>products<\/code> table:<\/p>\n\n\n<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\">SELECT<\/span>\n  MAX(price)\n<span class=\"hljs-keyword\">FROM<\/span>\n  products;<\/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>\n\n\n<p><a href=\"https:\/\/www.pgtutorial.com\/playground\/?q=U0VMRUNUIE1BWChwcmljZSkgRlJPTSBwcm9kdWN0czs\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>The query returns a single value:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"plaintext\" data-shcb-language-slug=\"plaintext\"><span><code class=\"hljs language-plaintext\">   max\n---------\n 2999.99<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><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>Second, query the products with the prices equal to the max price:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" 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  product_name,\n  price\n<span class=\"hljs-keyword\">FROM<\/span>\n  products\n<span class=\"hljs-keyword\">WHERE<\/span>\n  price = <span class=\"hljs-number\">2999.99<\/span>;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><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\/?q=U0VMRUNUIHByb2R1Y3RfbmFtZSwgcHJpY2UgRlJPTSBwcm9kdWN0cyBXSEVSRSBwcmljZSA9IDI5OTkuOTk7\" 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-5\" data-shcb-language-name=\"plaintext\" data-shcb-language-slug=\"plaintext\"><span><code class=\"hljs language-plaintext\">      product_name       |  price\n-------------------------+---------\n Samsung QN900C Neo QLED | 2999.99<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><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>In the second query, the condition in the <code>WHERE<\/code> clause can accept a query that returns a single value. So you can use the first query that returns a single value as a subquery in the second query like this:<\/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  product_name,\n  price\n<span class=\"hljs-keyword\">FROM<\/span>\n  products\n<span class=\"hljs-keyword\">WHERE<\/span>\n  price = (\n    <span class=\"hljs-keyword\">SELECT<\/span>\n      MAX(price)\n    <span class=\"hljs-keyword\">FROM<\/span>\n      products\n  );<\/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\/?q=U0VMRUNUIHByb2R1Y3RfbmFtZSwgcHJpY2UgRlJPTSBwcm9kdWN0cyBXSEVSRSBwcmljZSA9ICggU0VMRUNUIE1BWChwcmljZSkgRlJPTSBwcm9kdWN0cyApOw\" 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\">      product_name       |  price\n-------------------------+---------\n Samsung QN900C Neo QLED | 2999.99<\/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<p>Similarly, you can find the products with prices greater than the average price:<\/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  product_name,\n  price\n<span class=\"hljs-keyword\">FROM<\/span>\n  products\n<span class=\"hljs-keyword\">WHERE<\/span>\n  price &gt; (\n    <span class=\"hljs-keyword\">SELECT<\/span>\n      AVG(price)\n    <span class=\"hljs-keyword\">FROM<\/span>\n      products\n  );<\/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><a href=\"https:\/\/www.pgtutorial.com\/playground\/?q=U0VMRUNUIHByb2R1Y3RfbmFtZSwgcHJpY2UgRlJPTSBwcm9kdWN0cyBXSEVSRSBwcmljZSA%2BICggU0VMRUNUIEFWRyhwcmljZSkgRlJPTSBwcm9kdWN0cyApOw\" 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-9\" data-shcb-language-name=\"plaintext\" data-shcb-language-slug=\"plaintext\"><span><code class=\"hljs language-plaintext\">        product_name        |  price\n----------------------------+---------\n Samsung Galaxy Z Fold 5    | 1799.99\n Apple iPhone 15 Pro Max    | 1299.99\n LG OLED TV C3              | 1999.99\n Sony Bravia XR A95K        | 2499.99\n Samsung QN900C Neo QLED    | 2999.99\n LG G3 OLED                 | 2499.99\n Sony HT-A7000 Soundbar     | 1299.99\n Dell XPS 15                | 1499.99\n HP Spectre x360            | 1399.99\n Microsoft Surface Laptop 5 | 1299.99\n Lenovo ThinkPad X1 Carbon  | 1599.99\n Apple iMac 24\"             | 1299.99<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-9\"><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='postgresql-subquery-in-the-select-clause'>PostgreSQL subquery in the SELECT clause <a href=\"#postgresql-subquery-in-the-select-clause\" class=\"anchor\" id=\"postgresql-subquery-in-the-select-clause\" title=\"Anchor for PostgreSQL subquery in the SELECT clause\">#<\/a><\/h2>\n\n\n\n<p>The <code>SELECT<\/code> clause accepts a value. You can use a subquery that returns a single value in the <code>SELECT<\/code> clause.<\/p>\n\n\n\n<p>For example, the following query uses a subquery to retrieve product name, price, and max price of products with <code>brand_id<\/code> <code>2<\/code>:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-10\" 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  product_name,\n  price,\n  (\n    <span class=\"hljs-keyword\">SELECT<\/span>\n      MAX(price)\n    <span class=\"hljs-keyword\">FROM<\/span>\n      products\n    <span class=\"hljs-keyword\">WHERE<\/span>\n      brand_id = <span class=\"hljs-number\">2<\/span>\n  ) max_price\n<span class=\"hljs-keyword\">FROM<\/span>\n  products\n<span class=\"hljs-keyword\">WHERE<\/span>\n  brand_id = <span class=\"hljs-number\">2<\/span>;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-10\"><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\/?q=U0VMRUNUIHByb2R1Y3RfbmFtZSwgcHJpY2UsICggU0VMRUNUIE1BWChwcmljZSkgRlJPTSBwcm9kdWN0cyBXSEVSRSBicmFuZF9pZCA9IDIgKSBtYXhfcHJpY2UgRlJPTSBwcm9kdWN0cyBXSEVSRSBicmFuZF9pZCA9IDI7\" 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-11\" data-shcb-language-name=\"plaintext\" data-shcb-language-slug=\"plaintext\"><span><code class=\"hljs language-plaintext\">      product_name       |  price  | max_price\n-------------------------+---------+-----------\n Apple iPhone 15         | 1099.99 |   1299.99\n Apple iPhone 15 Pro Max | 1299.99 |   1299.99\n Apple iPad Pro 12.9     | 1099.99 |   1299.99\n Apple AirPods Pro 3     |  249.99 |   1299.99\n Apple Watch Series 9    |  399.99 |   1299.99\n Apple iMac 24\"          | 1299.99 |   1299.99<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-11\"><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 following example uses a subquery to return the product name and its inventory quantity:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-12\" 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  p.product_name,\n  (\n    <span class=\"hljs-keyword\">SELECT<\/span>\n      SUM(quantity)\n    <span class=\"hljs-keyword\">FROM<\/span>\n      inventories\n    <span class=\"hljs-keyword\">WHERE<\/span>\n      product_id = p.product_id\n  ) <span class=\"hljs-keyword\">AS<\/span> inventory_qty\n<span class=\"hljs-keyword\">FROM<\/span>\n  products p\n<span class=\"hljs-keyword\">ORDER<\/span> <span class=\"hljs-keyword\">BY<\/span>\n  product_name;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-12\"><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\/?q=U0VMRUNUIHAucHJvZHVjdF9uYW1lLCAoIFNFTEVDVCBTVU0ocXVhbnRpdHkpIEZST00gaW52ZW50b3JpZXMgV0hFUkUgcHJvZHVjdF9pZCA9IHAucHJvZHVjdF9pZCApIEFTIGludmVudG9yeV9xdHkgRlJPTSBwcm9kdWN0cyBwIE9SREVSIEJZIHByb2R1Y3RfbmFtZTs\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Partial Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-13\" data-shcb-language-name=\"plaintext\" data-shcb-language-slug=\"plaintext\"><span><code class=\"hljs language-plaintext\">        product_name        | inventory_qty\n----------------------------+---------------\n Apple AirPods Pro 3        |           180\n Apple iMac 24\"             |           320\n Apple iPad Pro 12.9        |           170\n Apple iPhone 15            |           150\n Apple iPhone 15 Pro Max    |           140\n...<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-13\"><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='postgresql-subquery-in-the-from-clause'>PostgreSQL subquery in the FROM clause <a href=\"#postgresql-subquery-in-the-from-clause\" class=\"anchor\" id=\"postgresql-subquery-in-the-from-clause\" title=\"Anchor for PostgreSQL subquery in the FROM clause\">#<\/a><\/h2>\n\n\n\n<p>You can use a subquery that returns a result set (rows &amp; columns) in the <code>FROM<\/code> clause. <\/p>\n\n\n\n<p>For example, the following statement uses a subquery in the <code>FROM<\/code> clause to return the average number of products by all brands:<\/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  AVG(product_count)\n<span class=\"hljs-keyword\">FROM<\/span>\n  (\n    <span class=\"hljs-keyword\">SELECT<\/span>\n      brand_id,\n      COUNT(*) product_count\n    <span class=\"hljs-keyword\">FROM<\/span>\n      products\n    <span class=\"hljs-keyword\">GROUP<\/span> <span class=\"hljs-keyword\">BY<\/span>\n      brand_id\n  );<\/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>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\">        avg\n--------------------\n 2.5000000000000000\n(1 row)<\/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<p>The subquery uses a <code><a href=\"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-group-by\/\">GROUP BY<\/a><\/code> clause with a <code>COUNT<\/code> function to return a result set that includes <code>brand_id<\/code> and product count:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-16\" 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_id,\n  count(*) product_count\n<span class=\"hljs-keyword\">FROM<\/span>\n  products\n<span class=\"hljs-keyword\">GROUP<\/span> <span class=\"hljs-keyword\">BY<\/span>\n  brand_id<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-16\"><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>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-17\" data-shcb-language-name=\"plaintext\" data-shcb-language-slug=\"plaintext\"><span><code class=\"hljs language-plaintext\"> brand_id | product_count\n----------+---------------\n        9 |             1\n        5 |             3\n        4 |             1\n       10 |             1\n        6 |             2\n        2 |             5\n        7 |             3\n        1 |             5\n        8 |             1<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-17\"><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 outer query uses the <code>AVG()<\/code> function to calculate the average product count for all brands.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='postgresql-subquery-in-the-join-clause'>PostgreSQL subquery in the JOIN clause <a href=\"#postgresql-subquery-in-the-join-clause\" class=\"anchor\" id=\"postgresql-subquery-in-the-join-clause\" title=\"Anchor for PostgreSQL subquery in the JOIN clause\">#<\/a><\/h2>\n\n\n\n<p>The <code>JOIN<\/code> clause accepts a result set, a collection of rows and columns.<\/p>\n\n\n\n<p>The subquery must return a result set to use a subquery in the <code><a href=\"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-inner-join\/\">JOIN<\/a><\/code> clause. Additionally, it must include columns for joining with the table in the outer query.<\/p>\n\n\n\n<p>The following statement uses a subquery in the <code>JOIN<\/code> clause to retrieve products with an inventory quantity greater than 300:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-18\" 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  product_name,\n  quantity\n<span class=\"hljs-keyword\">FROM<\/span>\n  products\n  <span class=\"hljs-keyword\">JOIN<\/span> (\n    <span class=\"hljs-keyword\">SELECT<\/span>\n      product_id,\n      quantity\n    <span class=\"hljs-keyword\">FROM<\/span>\n      inventories\n    <span class=\"hljs-keyword\">WHERE<\/span>\n      quantity &gt; <span class=\"hljs-number\">300<\/span>\n  ) <span class=\"hljs-keyword\">USING<\/span> (product_id);<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-18\"><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\/?q=U0VMRUNUIHByb2R1Y3RfbmFtZSwgcXVhbnRpdHkgRlJPTSBwcm9kdWN0cyBKT0lOICggU0VMRUNUIHByb2R1Y3RfaWQsIHF1YW50aXR5IEZST00gaW52ZW50b3JpZXMgV0hFUkUgcXVhbnRpdHkgPiAzMDAgKSBVU0lORyAocHJvZHVjdF9pZCk7\" 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-19\" data-shcb-language-name=\"plaintext\" data-shcb-language-slug=\"plaintext\"><span><code class=\"hljs language-plaintext\">       product_name        | quantity\n---------------------------+----------\n Lenovo ThinkPad X1 Carbon |      310\n Apple iMac 24\"            |      320\n Dell Inspiron 27          |      330<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-19\"><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>First, the subquery retrieves <code>product_id<\/code> and <code>quantity<\/code> from the <code>inventories<\/code> table with a quantity greater than <code>300<\/code>:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-20\" 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  product_id,\n  quantity\n<span class=\"hljs-keyword\">FROM<\/span>\n  inventories\n<span class=\"hljs-keyword\">WHERE<\/span>\n  quantity &gt; <span class=\"hljs-number\">300<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-20\"><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\/?q=U0VMRUNUIHByb2R1Y3RfaWQsIHF1YW50aXR5IEZST00gaW52ZW50b3JpZXMgV0hFUkUgcXVhbnRpdHkgPiAzMDA\" 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-21\" data-shcb-language-name=\"plaintext\" data-shcb-language-slug=\"plaintext\"><span><code class=\"hljs language-plaintext\"> product_id | quantity\n------------+----------\n         23 |      310\n         24 |      320\n         25 |      330<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-21\"><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>Second, the outer query joins the <code>products<\/code> table with the above result set based on the values in the <code>product_id<\/code> column.<\/p>\n\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>A subquery is a query nested within another query.<\/li>\n\n\n\n<li>A query that contains a subquery is called an outer query.<\/li>\n\n\n\n<li>Use a subquery in the <code>SELECT<\/code>, <code>FROM<\/code>, <code>JOIN<\/code>, and <code>WHERE<\/code>clauses of the <code>SELECT<\/code> statement.<\/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=subquery\"\n  height=\"700\"\n  width=\"600\"\n  class=\"iframe\"\n><\/iframe>\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=\"589\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-subquery\/\"\n\t\t\t\tdata-post-title=\"PostgreSQL Subquery\"\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=\"589\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-subquery\/\"\n\t\t\t\tdata-post-title=\"PostgreSQL Subquery\"\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>Summary: In this tutorial, you will learn how to use PostgreSQL subquery to write more flexible queries in a more simple way. Getting Started with PostgreSQL Subquery # PostgreSQL allows you to embed a query within another query. This embedded query is called a subquery. The query that contains a subquery is called an outer [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":13,"menu_order":49,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-589","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 Subquery<\/title>\n<meta name=\"description\" content=\"In this tutorial, you will learn how to use PostgreSQL subquery to write more flexible queries in a more simple way.\" \/>\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-subquery\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"PostgreSQL Subquery\" \/>\n<meta property=\"og:description\" content=\"In this tutorial, you will learn how to use PostgreSQL subquery to write more flexible queries in a more simple way.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-subquery\/\" \/>\n<meta property=\"og:site_name\" content=\"PostgreSQL Tutorial\" \/>\n<meta property=\"article:modified_time\" content=\"2025-02-06T07:30:49+00:00\" \/>\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-subquery\\\/\",\"url\":\"https:\\\/\\\/www.pgtutorial.com\\\/postgresql-tutorial\\\/postgresql-subquery\\\/\",\"name\":\"PostgreSQL Subquery\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.pgtutorial.com\\\/#website\"},\"datePublished\":\"2024-12-03T04:20:32+00:00\",\"dateModified\":\"2025-02-06T07:30:49+00:00\",\"description\":\"In this tutorial, you will learn how to use PostgreSQL subquery to write more flexible queries in a more simple way.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.pgtutorial.com\\\/postgresql-tutorial\\\/postgresql-subquery\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.pgtutorial.com\\\/postgresql-tutorial\\\/postgresql-subquery\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.pgtutorial.com\\\/postgresql-tutorial\\\/postgresql-subquery\\\/#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 Subquery\"}]},{\"@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 Subquery","description":"In this tutorial, you will learn how to use PostgreSQL subquery to write more flexible queries in a more simple way.","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-subquery\/","og_locale":"en_US","og_type":"article","og_title":"PostgreSQL Subquery","og_description":"In this tutorial, you will learn how to use PostgreSQL subquery to write more flexible queries in a more simple way.","og_url":"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-subquery\/","og_site_name":"PostgreSQL Tutorial","article_modified_time":"2025-02-06T07:30:49+00:00","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-subquery\/","url":"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-subquery\/","name":"PostgreSQL Subquery","isPartOf":{"@id":"https:\/\/www.pgtutorial.com\/#website"},"datePublished":"2024-12-03T04:20:32+00:00","dateModified":"2025-02-06T07:30:49+00:00","description":"In this tutorial, you will learn how to use PostgreSQL subquery to write more flexible queries in a more simple way.","breadcrumb":{"@id":"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-subquery\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-subquery\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-subquery\/#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 Subquery"}]},{"@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\/589","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=589"}],"version-history":[{"count":6,"href":"https:\/\/www.pgtutorial.com\/wp-json\/wp\/v2\/pages\/589\/revisions"}],"predecessor-version":[{"id":1946,"href":"https:\/\/www.pgtutorial.com\/wp-json\/wp\/v2\/pages\/589\/revisions\/1946"}],"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=589"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}