{"id":576,"date":"2024-12-03T08:59:27","date_gmt":"2024-12-03T01:59:27","guid":{"rendered":"https:\/\/www.pgtutorial.com\/?page_id=576"},"modified":"2025-01-02T19:53:24","modified_gmt":"2025-01-02T12:53:24","slug":"postgresql-recursive-cte","status":"publish","type":"page","link":"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-recursive-cte\/","title":{"rendered":"PostgreSQL Recursive CTE"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you&#8217;ll learn how to use the PostgreSQL recursive CTE to query hierarchical data such as organization charts and category trees.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='getting-started-with-the-postgresql-recursive-cte'>Getting Started with the PostgreSQL Recursive CTE <a href=\"#getting-started-with-the-postgresql-recursive-cte\" class=\"anchor\" id=\"getting-started-with-the-postgresql-recursive-cte\" title=\"Anchor for Getting Started with the PostgreSQL Recursive CTE\">#<\/a><\/h2>\n\n\n\n<p><a href=\"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-cte\/\">CTE<\/a> provides a way to define a temporary table within a query. A recursive CTE is a type of CTE that references itself in its CTE query definition.<\/p>\n\n\n\n<p class=\"note\">In programming, a recursive function is a function that calls itself until it doesn&#8217;t. Similarly, a recursive CTE is a CTE that references itself in the CTE query.<\/p>\n\n\n\n<p>A recursive CTE has two main parts:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Anchor member<\/strong> is a query that provides the base result set.<\/li>\n\n\n\n<li><strong>Recursive member<\/strong> is a query referencing the CTE itself. It will execute repeatedly and build up the final result set. The recursive member has a termination condition that stops execution when it returns no row.<\/li>\n<\/ul>\n\n\n\n<p>A recursive CTE uses <code><a href=\"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-union\/\">UNION<\/a><\/code> or <code>UNION ALL<\/code> to combine result sets returned by the anchor member and recursive member.<\/p>\n\n\n\n<p>Here&#8217;s the syntax of a recursive CTE:<\/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\">WITH<\/span> <span class=\"hljs-keyword\">RECURSIVE<\/span> cte_name (column1, column2, ...) <span class=\"hljs-keyword\">AS<\/span> (\n\u00a0 \u00a0\u00a0<span class=\"hljs-comment\">-- Anchor member<\/span>\n\u00a0 \u00a0\u00a0<span class=\"hljs-keyword\">SELECT<\/span> ...\n\u00a0 \u00a0\u00a0<span class=\"hljs-keyword\">UNION<\/span> <span class=\"hljs-keyword\">ALL<\/span>\n\u00a0 \u00a0\u00a0<span class=\"hljs-comment\">-- Recursive member<\/span>\n\u00a0 \u00a0\u00a0<span class=\"hljs-keyword\">SELECT<\/span> ...\n\u00a0 \u00a0\u00a0<span class=\"hljs-keyword\">FROM<\/span> cte_name\n\u00a0 \u00a0\u00a0<span class=\"hljs-keyword\">WHERE<\/span> ...\n)\n<span class=\"hljs-keyword\">SELECT<\/span> *\n<span class=\"hljs-keyword\">FROM<\/span> cte_name;<\/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>The <code>WITH RECURSIVE<\/code> keyword defines a recursive CTE with a name (<code>cte_name<\/code>).<\/li>\n\n\n\n<li>An anchor member forms the base result set.<\/li>\n\n\n\n<li>A recursive member takes the base result set and starts the recursion until it returns no rows.<\/li>\n\n\n\n<li>The <code>UNION<\/code> (or <code>UNION ALL<\/code>) operator combines the result sets of the anchor member and recursive member into a final result set.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id='postgresql-recursive-cte-example'>PostgreSQL Recursive CTE example <a href=\"#postgresql-recursive-cte-example\" class=\"anchor\" id=\"postgresql-recursive-cte-example\" title=\"Anchor for PostgreSQL Recursive CTE example\">#<\/a><\/h2>\n\n\n\n<p>The following example uses a recursive CTE to generate a countdown from 3 to 1:<\/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\">WITH<\/span> <span class=\"hljs-keyword\">RECURSIVE<\/span> count_down (counter) <span class=\"hljs-keyword\">AS<\/span> (\n    <span class=\"hljs-comment\">-- Anchor member<\/span>\n    <span class=\"hljs-keyword\">SELECT<\/span>  <span class=\"hljs-number\">3<\/span> <span class=\"hljs-keyword\">AS<\/span> counter\n    <span class=\"hljs-keyword\">UNION<\/span>\n    <span class=\"hljs-comment\">-- Recursive member<\/span>\n    <span class=\"hljs-keyword\">SELECT<\/span> counter - <span class=\"hljs-number\">1<\/span>\n    <span class=\"hljs-keyword\">FROM<\/span> count_down\n    <span class=\"hljs-keyword\">WHERE<\/span> counter &gt; <span class=\"hljs-number\">1<\/span>\n  )\n<span class=\"hljs-keyword\">SELECT<\/span> * <span class=\"hljs-keyword\">FROM<\/span> count_down;<\/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=V0lUSCBSRUNVUlNJVkUgY291bnRfZG93biAoY291bnRlcikgQVMgKCBTRUxFQ1QgMyBBUyBjb3VudGVyIFVOSU9OIFNFTEVDVCBjb3VudGVyIC0gMSBGUk9NIGNvdW50X2Rvd24gV0hFUkUgY291bnRlciA%2BIDEgKSBTRUxFQ1QgKiBGUk9NIGNvdW50X2Rvd247\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Here&#8217;s the breakdown of the query:<\/p>\n\n\n\n<p>First, the anchor member initializes the counter with 3 (first iteration):<\/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> <span class=\"hljs-number\">3<\/span> <span class=\"hljs-keyword\">AS<\/span> counter<\/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>The anchor member forms a base result set:<\/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\"> counter\n<span class=\"hljs-comment\">---------<\/span>\n       <span class=\"hljs-number\">3<\/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>Second, the recursive member starts with the base result set and decrements the counter by 1:<\/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> counter - <span class=\"hljs-number\">1<\/span>\n<span class=\"hljs-keyword\">FROM<\/span> count_down\n<span class=\"hljs-keyword\">WHERE<\/span> counter &gt; <span class=\"hljs-number\">1<\/span><\/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>After the second iteration, the result set will be:<\/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\"> counter\n<span class=\"hljs-comment\">---------<\/span>\n       <span class=\"hljs-number\">2<\/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>After the third iteration, the counter is 1:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"PostgreSQL SQL dialect and PL\/pgSQL\" data-shcb-language-slug=\"pgsql\"><span><code class=\"hljs language-pgsql\"> counter\n<span class=\"hljs-comment\">---------<\/span>\n       <span class=\"hljs-number\">1<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><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>When the counter is 1, it will stop the anchor member. The <code>UNION<\/code> operator combines the result sets of all iterations:<\/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\"> counter\n<span class=\"hljs-comment\">---------<\/span>\n       <span class=\"hljs-number\">3<\/span>\n       <span class=\"hljs-number\">2<\/span>\n       <span class=\"hljs-number\">1<\/span><\/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>Third, the main query retrieves all values from the <code>count_down<\/code> CTE:<\/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> * <span class=\"hljs-keyword\">FROM<\/span> count_down;<\/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<h2 class=\"wp-block-heading\" id='using-a-recursive-cte-to-query-product-categories'>Using a Recursive CTE to Query product categories <a href=\"#using-a-recursive-cte-to-query-product-categories\" class=\"anchor\" id=\"using-a-recursive-cte-to-query-product-categories\" title=\"Anchor for Using a Recursive CTE to Query product categories\">#<\/a><\/h2>\n\n\n\n<p>Suppose that we have the following product categories organized in tree structure:<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"298\" src=\"https:\/\/www.pgtutorial.com\/wp-content\/uploads\/2024\/12\/PostgreSQL-Recursive-Query-Example-1024x298.png\" alt=\"PostgreSQL Recursive Query Example\" class=\"wp-image-583\" srcset=\"https:\/\/www.pgtutorial.com\/wp-content\/uploads\/2024\/12\/PostgreSQL-Recursive-Query-Example-1024x298.png 1024w, https:\/\/www.pgtutorial.com\/wp-content\/uploads\/2024\/12\/PostgreSQL-Recursive-Query-Example-300x87.png 300w, https:\/\/www.pgtutorial.com\/wp-content\/uploads\/2024\/12\/PostgreSQL-Recursive-Query-Example-768x223.png 768w, https:\/\/www.pgtutorial.com\/wp-content\/uploads\/2024\/12\/PostgreSQL-Recursive-Query-Example.png 1148w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<p>Here&#8217;s the table structure:<\/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\">CREATE<\/span> <span class=\"hljs-keyword\">TABLE<\/span> <span class=\"hljs-keyword\">IF<\/span> <span class=\"hljs-keyword\">NOT<\/span> <span class=\"hljs-keyword\">EXISTS<\/span> categories (\n  category_id <span class=\"hljs-type\">INT<\/span> <span class=\"hljs-keyword\">GENERATED<\/span> <span class=\"hljs-keyword\">BY<\/span> <span class=\"hljs-keyword\">DEFAULT<\/span> <span class=\"hljs-keyword\">AS<\/span> <span class=\"hljs-keyword\">IDENTITY<\/span> <span class=\"hljs-keyword\">PRIMARY KEY<\/span>,\n  category_name <span class=\"hljs-type\">VARCHAR<\/span>(<span class=\"hljs-number\">255<\/span>) <span class=\"hljs-keyword\">NOT<\/span> <span class=\"hljs-keyword\">NULL<\/span> <span class=\"hljs-keyword\">UNIQUE<\/span>,\n  parent_id <span class=\"hljs-type\">INT<\/span>,\n  <span class=\"hljs-keyword\">FOREIGN KEY<\/span> (parent_id) <span class=\"hljs-keyword\">REFERENCES<\/span> categories (category_id) <span class=\"hljs-keyword\">ON<\/span> <span class=\"hljs-keyword\">DELETE<\/span> <span class=\"hljs-keyword\">CASCADE<\/span>\n);<\/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>The following statement uses a recursive CTE to query all categories with their depths:<\/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\">WITH<\/span> <span class=\"hljs-keyword\">RECURSIVE<\/span> category_hierarchy <span class=\"hljs-keyword\">AS<\/span> (\n    <span class=\"hljs-keyword\">SELECT<\/span> category_id, category_name, parent_id,  <span class=\"hljs-number\">0<\/span> <span class=\"hljs-keyword\">AS<\/span> depth\n    <span class=\"hljs-keyword\">FROM<\/span> categories\n    <span class=\"hljs-keyword\">WHERE<\/span> parent_id <span class=\"hljs-keyword\">IS<\/span> <span class=\"hljs-keyword\">NULL<\/span>\n    <span class=\"hljs-keyword\">UNION<\/span> <span class=\"hljs-keyword\">ALL<\/span>\n    <span class=\"hljs-keyword\">SELECT<\/span> c.category_id, c.category_name, c.parent_id, s.depth + <span class=\"hljs-number\">1<\/span>\n    <span class=\"hljs-keyword\">FROM<\/span> categories c\n    <span class=\"hljs-keyword\">INNER<\/span> <span class=\"hljs-keyword\">JOIN<\/span> category_hierarchy s <span class=\"hljs-keyword\">ON<\/span> c.parent_id = s.category_id\n)\n<span class=\"hljs-keyword\">SELECT<\/span> * <span class=\"hljs-keyword\">FROM<\/span> category_hierarchy;<\/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\/?q=V0lUSCBSRUNVUlNJVkUgY2F0ZWdvcnlfaGllcmFyY2h5IEFTICggU0VMRUNUIGNhdGVnb3J5X2lkLCBjYXRlZ29yeV9uYW1lLCBwYXJlbnRfaWQsIDAgQVMgZGVwdGggRlJPTSBjYXRlZ29yaWVzIFdIRVJFIHBhcmVudF9pZCBJUyBOVUxMIFVOSU9OIEFMTCBTRUxFQ1QgYy5jYXRlZ29yeV9pZCwgYy5jYXRlZ29yeV9uYW1lLCBjLnBhcmVudF9pZCwgcy5kZXB0aCArIDEgRlJPTSBjYXRlZ29yaWVzIGMgSU5ORVIgSk9JTiBjYXRlZ29yeV9oaWVyYXJjaHkgcyBPTiBjLnBhcmVudF9pZCA9IHMuY2F0ZWdvcnlfaWQgKSBTRUxFQ1QgKiBGUk9NIGNhdGVnb3J5X2hpZXJhcmNoeQ\" 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=\"PostgreSQL SQL dialect and PL\/pgSQL\" data-shcb-language-slug=\"pgsql\"><span><code class=\"hljs language-pgsql\"> category_id |   category_name    | parent_id | depth\n<span class=\"hljs-comment\">-------------+--------------------+-----------+-------<\/span>\n           <span class=\"hljs-number\">1<\/span> | Electronics        |      <span class=\"hljs-keyword\">NULL<\/span> |     <span class=\"hljs-number\">0<\/span>\n           <span class=\"hljs-number\">2<\/span> | Mobile Devices     |         <span class=\"hljs-number\">1<\/span> |     <span class=\"hljs-number\">1<\/span>\n           <span class=\"hljs-number\">7<\/span> | Home Entertainment |         <span class=\"hljs-number\">1<\/span> |     <span class=\"hljs-number\">1<\/span>\n          <span class=\"hljs-number\">10<\/span> | Computers          |         <span class=\"hljs-number\">1<\/span> |     <span class=\"hljs-number\">1<\/span>\n           <span class=\"hljs-number\">3<\/span> | Smartphones        |         <span class=\"hljs-number\">2<\/span> |     <span class=\"hljs-number\">2<\/span>\n           <span class=\"hljs-number\">4<\/span> | Tablets            |         <span class=\"hljs-number\">2<\/span> |     <span class=\"hljs-number\">2<\/span>\n           <span class=\"hljs-number\">5<\/span> | Accessories        |         <span class=\"hljs-number\">2<\/span> |     <span class=\"hljs-number\">2<\/span>\n           <span class=\"hljs-number\">6<\/span> | Wearables          |         <span class=\"hljs-number\">2<\/span> |     <span class=\"hljs-number\">2<\/span>\n           <span class=\"hljs-number\">8<\/span> | Televisions        |         <span class=\"hljs-number\">7<\/span> |     <span class=\"hljs-number\">2<\/span>\n           <span class=\"hljs-number\">9<\/span> | Audio Systems      |         <span class=\"hljs-number\">7<\/span> |     <span class=\"hljs-number\">2<\/span>\n          <span class=\"hljs-number\">11<\/span> | Laptops            |        <span class=\"hljs-number\">10<\/span> |     <span class=\"hljs-number\">2<\/span>\n          <span class=\"hljs-number\">12<\/span> | Desktops           |        <span class=\"hljs-number\">10<\/span> |     <span class=\"hljs-number\">2<\/span><\/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>How it works.<\/p>\n\n\n\n<p>First, the anchor member returns the top category where the <code>parent_id<\/code> is <code>NULL<\/code> with the depth <code>0<\/code>:<\/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> category_id, category_name, parent_id,  <span class=\"hljs-number\">0<\/span> <span class=\"hljs-keyword\">AS<\/span> depth\n<span class=\"hljs-keyword\">FROM<\/span> categories\n<span class=\"hljs-keyword\">WHERE<\/span> parent_id <span class=\"hljs-keyword\">IS<\/span> <span class=\"hljs-keyword\">NULL<\/span><\/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<p>Second, the recursive member returns the categories at the <code>depth + 1<\/code> until there are no rows to fetch:<\/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> c.category_id, c.category_name, c.parent_id, s.depth + <span class=\"hljs-number\">1<\/span>\n<span class=\"hljs-keyword\">FROM<\/span> categories c\n<span class=\"hljs-keyword\">INNER<\/span> <span class=\"hljs-keyword\">JOIN<\/span> category_hierarchy s <span class=\"hljs-keyword\">ON<\/span> c.parent_id = s.category_id<\/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>Third, the <code>UNION<\/code> operator combines the result sets of all iterations.<\/p>\n\n\n\n<p>Finally, the outer query retrieves data from the CTE:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-15\" 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> * <span class=\"hljs-keyword\">FROM<\/span> category_hierarchy;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-15\"><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<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 recursive CTE has a recursive member that references itself.<\/li>\n\n\n\n<li>Use recursive CTE to query hierarchical data.<\/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=recursive-cte\"\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=\"576\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-recursive-cte\/\"\n\t\t\t\tdata-post-title=\"PostgreSQL Recursive CTE\"\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=\"576\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-recursive-cte\/\"\n\t\t\t\tdata-post-title=\"PostgreSQL Recursive CTE\"\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&#8217;ll learn how to use the PostgreSQL recursive CTE to query hierarchical data such as organization charts and category trees. Getting Started with the PostgreSQL Recursive CTE # CTE provides a way to define a temporary table within a query. A recursive CTE is a type of CTE that references itself [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":13,"menu_order":56,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-576","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 Recursive CTE<\/title>\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-recursive-cte\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"PostgreSQL Recursive CTE\" \/>\n<meta property=\"og:description\" content=\"Summary: in this tutorial, you&#8217;ll learn how to use the PostgreSQL recursive CTE to query hierarchical data such as organization charts and category trees. Getting Started with the PostgreSQL Recursive CTE # CTE provides a way to define a temporary table within a query. A recursive CTE is a type of CTE that references itself [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-recursive-cte\/\" \/>\n<meta property=\"og:site_name\" content=\"PostgreSQL Tutorial\" \/>\n<meta property=\"article:modified_time\" content=\"2025-01-02T12:53:24+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.pgtutorial.com\/wp-content\/uploads\/2024\/12\/PostgreSQL-Recursive-Query-Example.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1148\" \/>\n\t<meta property=\"og:image:height\" content=\"334\" \/>\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-recursive-cte\\\/\",\"url\":\"https:\\\/\\\/www.pgtutorial.com\\\/postgresql-tutorial\\\/postgresql-recursive-cte\\\/\",\"name\":\"PostgreSQL Recursive CTE\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.pgtutorial.com\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/www.pgtutorial.com\\\/postgresql-tutorial\\\/postgresql-recursive-cte\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/www.pgtutorial.com\\\/postgresql-tutorial\\\/postgresql-recursive-cte\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.pgtutorial.com\\\/wp-content\\\/uploads\\\/2024\\\/12\\\/PostgreSQL-Recursive-Query-Example-1024x298.png\",\"datePublished\":\"2024-12-03T01:59:27+00:00\",\"dateModified\":\"2025-01-02T12:53:24+00:00\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.pgtutorial.com\\\/postgresql-tutorial\\\/postgresql-recursive-cte\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.pgtutorial.com\\\/postgresql-tutorial\\\/postgresql-recursive-cte\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.pgtutorial.com\\\/postgresql-tutorial\\\/postgresql-recursive-cte\\\/#primaryimage\",\"url\":\"https:\\\/\\\/www.pgtutorial.com\\\/wp-content\\\/uploads\\\/2024\\\/12\\\/PostgreSQL-Recursive-Query-Example.png\",\"contentUrl\":\"https:\\\/\\\/www.pgtutorial.com\\\/wp-content\\\/uploads\\\/2024\\\/12\\\/PostgreSQL-Recursive-Query-Example.png\",\"width\":1148,\"height\":334,\"caption\":\"PostgreSQL Recursive Query Example\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.pgtutorial.com\\\/postgresql-tutorial\\\/postgresql-recursive-cte\\\/#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 Recursive CTE\"}]},{\"@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 Recursive CTE","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-recursive-cte\/","og_locale":"en_US","og_type":"article","og_title":"PostgreSQL Recursive CTE","og_description":"Summary: in this tutorial, you&#8217;ll learn how to use the PostgreSQL recursive CTE to query hierarchical data such as organization charts and category trees. Getting Started with the PostgreSQL Recursive CTE # CTE provides a way to define a temporary table within a query. A recursive CTE is a type of CTE that references itself [&hellip;]","og_url":"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-recursive-cte\/","og_site_name":"PostgreSQL Tutorial","article_modified_time":"2025-01-02T12:53:24+00:00","og_image":[{"width":1148,"height":334,"url":"https:\/\/www.pgtutorial.com\/wp-content\/uploads\/2024\/12\/PostgreSQL-Recursive-Query-Example.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-recursive-cte\/","url":"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-recursive-cte\/","name":"PostgreSQL Recursive CTE","isPartOf":{"@id":"https:\/\/www.pgtutorial.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-recursive-cte\/#primaryimage"},"image":{"@id":"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-recursive-cte\/#primaryimage"},"thumbnailUrl":"https:\/\/www.pgtutorial.com\/wp-content\/uploads\/2024\/12\/PostgreSQL-Recursive-Query-Example-1024x298.png","datePublished":"2024-12-03T01:59:27+00:00","dateModified":"2025-01-02T12:53:24+00:00","breadcrumb":{"@id":"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-recursive-cte\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-recursive-cte\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-recursive-cte\/#primaryimage","url":"https:\/\/www.pgtutorial.com\/wp-content\/uploads\/2024\/12\/PostgreSQL-Recursive-Query-Example.png","contentUrl":"https:\/\/www.pgtutorial.com\/wp-content\/uploads\/2024\/12\/PostgreSQL-Recursive-Query-Example.png","width":1148,"height":334,"caption":"PostgreSQL Recursive Query Example"},{"@type":"BreadcrumbList","@id":"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-recursive-cte\/#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 Recursive CTE"}]},{"@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\/576","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=576"}],"version-history":[{"count":3,"href":"https:\/\/www.pgtutorial.com\/wp-json\/wp\/v2\/pages\/576\/revisions"}],"predecessor-version":[{"id":1382,"href":"https:\/\/www.pgtutorial.com\/wp-json\/wp\/v2\/pages\/576\/revisions\/1382"}],"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=576"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}