EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials PostgreSQL Tutorial PostgreSQL Recursive Query
Secondary Sidebar
PostgreSQL Tutorial
  • Basic
    • What is PostgreSQL
    • PostgreSQL Features
    • How to Install PostgreSQL
    • PostgreSQL Versions
    • PostgreSQL Architecture
    • PostgreSQL GUI
    • Postgres Command-Line
    • PostgreSQL Variables
    • PostgreSQL Data Types
    • PostgreSQL NOT NULL
    • PostgreSQL Integer
    • PostgreSQL Boolean
    • PostgreSQL BIGINT
    • PostgreSQL NULLIF
    • PostgreSQL Administration
    • PostgreSQL Commands
    • PostgreSQL Operators
    • PostgreSQL IN Operator
    • Postgres like query
    • PostgreSQL encode
    • PostgreSQL Cheat Sheet
    • PostgreSQL List Databases
    • PostgreSQL Rename Database
  • Control Statement
    • PostgreSQL IF Statement
    • PostgreSQL if else
    • PostgreSQL CASE Statement
    • PostgreSQL LOOP
    • PostgreSQL For Loop
    • PostgreSQL While Loop
  • Joins
    • Joins in PostgreSQL
    • PostgreSQL Inner Join
    • PostgreSQL Outer Join
    • LEFT OUTER JOIN in PostgreSQL
    • PostgreSQL FULL OUTER JOIN
    • PostgreSQL LEFT JOIN
    • PostgreSQL Full Join
    • PostgreSQL Cross Join
    • PostgreSQL NATURAL JOIN
    • PostgreSQL UPDATE JOIN
  • Queries
    • PostgreSQL Queries
    • PostgreSQL INSERT INTO
    • PostgreSQL WHERE Clause
    • PostgreSQL WITH Clause
    • PostgreSQL ORDER BY
    • PostgreSQL ORDER BY Random
    • PostgreSQL ORDER BY DESC
    • PostgreSQL GROUP BY
    • PostgreSQL group_concat
    • PostgreSQL HAVING
    • PostgreSQL Recursive Query
  • Advanced
    • PostgreSQL Schema
    • Postgres List Schemas
    • PostgreSQL Drop Schema
    • PostgreSQL VARCHAR
    • Array in PostgreSQL
    • PostgreSQL DDL
    • PostgreSQL List Users
    • Postgres Default User
    • Postgres add user
    • PostgreSQL User Password
    • PostgreSQL log_statement
    • PostgreSQL repository
    • PostgreSQL shared_buffer
    • PostgreSQL String Functions
    • PostgreSQL Compare Strings
    • PostgreSQL Text Search
    • PostgreSQL TEXT
    • PostgreSQL String Array
    • PostgreSQL where in array
    • PostgreSQL Constraints
    • PostgreSQL UNIQUE Constraint
    • PostgreSQL CHECK Constraint
    • PostgreSQL INTERSECT
    • PostgreSQL Like
    • Cursors in PostgreSQL
    • PostgreSQL UNION ALL
    • Indexes in PostgreSQL
    • PostgreSQL Index Types
    • PostgreSQL REINDEX
    • PostgreSQL UNIQUE Index
    • PostgreSQL Clustered Index
    • PostgreSQL DROP INDEX
    • PostgreSQL DISTINCT
    • PostgreSQL FETCH
    • PostgreSQL RAISE EXCEPTION
    • PostgreSQL Auto Increment
    • Sequence in PostgreSQL
    • Wildcards in PostgreSQL
    • PostgreSQL Subquery
    • PostgreSQL Alias
    • PostgreSQL LIMIT
    • PostgreSQL Limit Offset
    • PostgreSQL LAG()
    • PostgreSQL Table
    • Postgres Show Tables
    • PostgreSQL Describe Table
    • PostgreSQL Lock Table
    • PostgreSQL ALTER TABLE
    • Postgres Rename Table
    • PostgreSQL List Tables
    • PostgreSQL TRUNCATE TABLE
    • PostgreSQL Table Partitioning
    • Postgres DROP Table
    • PostgreSQL Functions
    • PostgreSQL Math Functions
    • PostgreSQL Window Functions
    • Aggregate Functions in PostgreSQL
    • PostgreSQL Primary Key
    • Foreign Key in PostgreSQL
    • PostgreSQL Procedures
    • PostgreSQL Stored Procedures
    • PostgreSQL Views
    • PostgreSQL Materialized Views
    • Postgres Create View
    • PostgreSQL Triggers
    • PostgreSQL DROP TRIGGER
    • PostgreSQL Date Functions
    • PostgreSQL TO_DATE()
    • PostgreSQL datediff
    • PostgreSQL Timestamp
    • PostgreSQL CURRENT_TIMESTAMP()
    • PostgreSQL Notify
    • PostgreSQL LENGTH()
    • PostgreSQL blob
    • PostgreSQL Median
    • PostgreSQL kill query
    • PostgreSQL Formatter
    • PostgreSQL RANK()
    • PostgreSQL Select
    • PostgreSQL Average
    • PostgreSQL DATE_PART()
    • PostgreSQL EXECUTE
    • PostgreSQL COALESCE
    • PostgreSQL EXTRACT()
    • PostgreSQL Sort
    • PostgreSQL TO_CHAR
    • PostgreSQL Interval
    • PostgreSQL Number Types
    • PostgreSQL ROW_NUMBER
    • Alter Column in PostgreSQL
    • PostgreSQL Identity Column
    • PostgreSQL SPLIT_PART()
    • PostgreSQL CONCAT()
    • PostgreSQL replace
    • PostgreSQL TRIM()
    • PostgreSQL MAX
    • PostgreSQL DELETE
    • PostgreSQL Float
    • PostgreSQL OID
    • PostgreSQL log
    • PostgreSQL REGEXP_MATCHES()
    • PostgreSQL MD5 
    • PostgreSQL NOW()
    • PostgreSQL RANDOM
    • PostgreSQL round
    • PostgreSQL Trunc()
    • PostgreSQL TIME
    • PostgreSQL IS NULL
    • PostgreSQL CURRENT_TIME
    • PostgreSQL MOD()
    • Postgresql Count
    • PostgreSQL Datetime
    • PostgreSQL MIN()
    • PostgreSQL age()
    • PostgreSQL enum
    • PostgreSQL OR
    • PostgreSQL Wal
    • PostgreSQL NOT IN
    • PostgreSQL SET
    • PostgreSQL Current Date
    • PostgreSQL Compare Date
    • PostgreSQL SERIAL
    • PostgreSQL UUID
    • PostgreSQL Merge
    • PostgreSQL Database
    • PostgreSQL Clone Database
    • PostgreSQL Copy Database
    • PostgreSQL Show Databases
    • PostgreSQL Restore Database
    • PostgreSQL DROP DATABASE
    • PostgreSQL ALTER DATABASE
    • Postgres DROP Database
    • Postgres Dump Database
    • PostgreSQL OFFSET
    • PostgreSQL GRANT
    • PostgreSQL COMMIT
    • PostgreSQL ROLLUP
    • PostgreSQL JSON
    • EXPLAIN ANALYZE in PostgreSQL
    • PostgreSQL Temporary Table
    • PostgreSQL Show Tables
    • PostgreSQL cluster
    • PostgreSQL Replication
    • PostgreSQL Logical Replication
    • PostgreSQL flush privileges
    • PostgreSQL Tablespaces
    • CAST in PostgreSQL
    • PostgreSQL CTE
    • hstore in PostgreSQL
    • PostgreSQL Encryption
    • PostgreSQL DECODE()
    • PostgreSQL Vacuum
    • PostgreSQL EXCLUDE
    • Postgres Change Password
    • Postgres Delete Cascade
    • PostgreSQL EXCEPT
    • PostgreSQL Roles
    • PostgreSQL Link
    • PostgreSQL Partition
    • PostgreSQL column does not exist
    • PostgreSQL Log Queries
    • PostgreSQL escape single quote
    • PostgreSQL Query Optimization
    • PostgreSQL Character Varying
    • PostgreSQL Transaction
    • PostgreSQL Extensions
    • PostgreSQL Import CSV
    • PostgreSQL Client
    • PostgreSQL caching
    • PostgreSQL Incremental Backup
    • PostgreSQL JSON vs JSONNB
    • PostgreSQL JDBC Driver
    • PostgreSQL Interview Questions

PostgreSQL Recursive Query

By Priya PedamkarPriya Pedamkar

PostgreSQL Recursive Query

Definition of PostgreSQL Recursive Query

PostgreSQL recursive query provides with a statement which was allows us to use auxiliary statement in the query. A recursive query is a query in PostgreSQL, referred to as recursive common table expressions; it is used in multiple situations such as querying hierarchical data like organisation structure. The common table expression in PostgreSQL is the same as temporary tables, which was used during running the query. PostgreSQL will provide a recursive query, which was recursive in nature, and it will fetch the data until the termination condition was not met.

Syntax:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Below syntax shows recursive query.

WITH RECURSIVE (common table expression name) or table_name AS(
Definition of non-recursive term common table expression
UNION or UNION ALL
Definition of recursive term common table expression
) SELECT * FROM table_name or common table expression name;

Parameter:

Below is the parameter description syntax of the recursive query.

  • Recursive: Using recursive query and with clause, we are creating temporary tables; the scope of this temporary table is only that query itself.
  • CTE name or table name: Common table expression name is specified in its table name on which we have retrieving data.
  • Non-recursive term: This is defined in PostgreSQL common table expression query, which provided the result set of common table expressions.
  • Recursive term: It is defined in PostgreSQL in one or more common table expressions or query definitions join with the non-recursive term.
  • UNION: Union and union all is used to join the two queries by using the recursive query in PostgreSQL.
  • Termination check: It is used when the recursion stops, and no rows will return from the iteration.
  • Select: It is used to select the data from a table or from the common table expressions in PostgreSQL.

How Recursive Query Works in PostgreSQL?

  • Below is the working of a recursive query in PostgreSQL.
  • Recursive query in PostgreSQL will work in three parts; the recursive query has four basic steps to execute the query. PostgreSQL will execute the common table expression or recursive query in the following sequence are as follows.
    • It is defined as the initial value, and the working table of the recursive query is populated in this step.
    • The second step is known as the recursive part. As we can see in the recursive query will referring to print the numbers itself, and it will get the values from the working table, which we have mentioned in the recursive query in PostgreSQL. This query in the recursive function will continue running till the termination condition is met. It executes the recursive result with Ri as input, and it will result as Ri+1.
    • The third step is the actual part or query, which was used to select all the values from a column from a table or common table expressions. This step is defined as repeat the second step until the set is not empty. It is also called a termination check.
    • The fourth step is to return the final result using the UNION and UNION ALL statement.
  • The recursive common table expressions and subordinates will define the one non-recursive and one recursive term.
  • The non-recursive term will return the base result set of R0. The recursive term will return the direct subordinates.
  • With the statement in PostgreSQL will provides the way to write an auxiliary statement for use in the large query.
  • An auxiliary statement which is often to be used as common table expressions. Each of the auxiliary statements can be used to select, update, delete or insert, and clause itself to its primary statement.
  • Recursive query evaluation will contain the non-recursive term’s evaluation; for using UNION, we can discard the duplicate rows.
  • The form of a recursive statement with a query in PostgreSQL is always a non-recursive statement, where the recursive statement contains the reference of the queries output.

Examples of PostgreSQL Recursive Query

We have using the student table to describe an example of a recursive query. Below is the student table structure, and the data that we have used in the example are as follows.

select * from student;
\d+ student;

PostgreSQL Recursive Query-1.1

Example #1 – Recursive Query using UNION

The below example shows that recursive query using UNION.

Code:

WITH RECURSIVE subordinates AS (
SELECT
stud_id,
phone,
stud_name
FROM
student
WHERE
stud_id = 10
UNION
SELECT
s.stud_id,
s.phone,
s.stud_name
FROM
student s
INNER JOIN subordinates sub ON sub.stud_id = s.phone
) SELECT
*
FROM
subordinates;

Output:

PostgreSQL Recursive Query-1.2

  • In the above example, the recursive common table expression defines the recursive and non-recursive term.
  • Non-recursive term will return the base result of R0, which was the stud_id is 10.

Example #2 – Recursive Query using UNION ALL

  • The below example shows that recursive query using UNION ALL.
  • The non-recursive term will return the base result of R0, which was the stud_id is 5.

Code:

WITH RECURSIVE subordinates AS (
SELECT
stud_id,
phone,
stud_name
FROM
student
WHERE
stud_id = 5
UNION ALL
SELECT
s.stud_id,
s.phone,
s.stud_name
FROM
student s
INNER JOIN subordinates sub ON sub.stud_id = s.phone
) SELECT
*
FROM
subordinates;\

Output:

PostgreSQL Recursive Query-1.3

Example #3 – Recursive Query to Retrieve All Data from Table

The below example shows that recursive queries using UNION to retrieve all data from the table.

Code:

WITH RECURSIVE subordinates AS (
SELECT
stud_id,
phone,
stud_name
FROM
Student
UNION
SELECT
s.stud_id,
s.phone,
s.stud_name
FROM
student s
INNER JOIN subordinates sub ON sub.stud_id = s.phone
) SELECT
*
FROM
subordinates;

Output:

Output-1.4

Recommended Articles

This is a guide to PostgreSQL Recursive Query. Here we also discuss the definition and how recursive query work in postgresql along with different examples and their code implementation. you may also have a look at the following articles to learn more –

  1. PostgreSQL Variables
  2. PostgreSQL round
  3. PostgreSQL GRANT
  4. PostgreSQL Auto Increment
Popular Course in this category
PostgreSQL Course (2 Courses, 1 Project)
  2 Online Courses |  1 Hands-on Project |  7+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more