Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • PostgreSQL - Get Started
  • Install PostgreSQL
  • Connect to PostgreSQL DB
  • Create Database
  • Create Table
  • Copy Table
  • Drop Table
  • Drop Database
  • Truncate Table
  • ALTER Table
  • Rename Table
  • Rename Columns
  • Add Columns
  • Modify Column Type
  • Set Default Value of Column
  • Remove Columns
  • Add Constraints to Table
  • Insert Data
  • Upsert Data
  • Update Data
  • Delete Data
  • SELECT Statement
  • WHERE Clause
  • GROUP BY Clause
  • HAVING Clause
  • ORDER BY Clause
  • DISTINCT Clause
  • Inner Join
  • Left Outer Join
  • Right Outer Join
  • Full Outer Join
  • Self Join
  • Natural Join
  • Cross Join
  • LIMIT OFFSET Clause
  • GROUPING SETS
  • GROUPING() Function
  • GROUP BY CUBE
  • GROUP BY ROLLUP
  • Sub Query
  • ALL Operator
  • ANY Operator
  • UNION Operator
  • INTERSECT Operator
  • EXCEPT Operator
  • IS NULL Operator
  • BETWEEN Operator
  • LIKE Operator
  • CAST Operator
  • CASE Expressions
  • NULLIF()
  • COALESCE()
  • GREATEST(), LEAST()
  • WITH Queries (CTE)
  • Constraints
  • NOT NULL Constraint
  • Unique Constraint
  • Check Constraint
  • Primary Key
  • Foreign Key
  • Sequence
  • Serial Type
  • Identity Columns
  • Generated Columns
  • Data Types
  • Boolean Type
  • Character Type
  • Integer Type
  • Numeric Type
  • Date Type
  • Time Type
  • TimeStamp Type
  • Interval Type
  • Array Type
  • Json Type
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

Subquery in PostgreSQL

PostgreSQL supports a query nested inside another query. The nested query is called Subquery. The Subquery can be used in SELECT, INSERT, UPDATE or DELETE statements.

Syntax
SELECT <columns> FROM <table1>
    WHERE <column> <OPERATOR> (SELECT <column> FROM <table2>)

In the above syntax, the first SELECT query is called the outer query and another query inside brackets is called a subquery or inner query. The operators after the WHERE clause can be =, >=, <=, >, <. IN, or EXISTS.

Let's use the following Department (parent table) and Employee (child table) to understand a subquery.

Sample Table
Sample Table

Subquery with IN operator

PostgreSQL executes a query that has a subquery in the following sequence:

  1. Execute the subquery
  2. Pass the result of the subquery to the outer query
  3. Execute the outer query
Example: Subquery with IN
SELECT * FROM Employee
WHERE dept_id IN (SELECT dept_id FROM Department 
				 WHERE dept_name IN ('IT','FINANCE'));
Subquery

In above query, (SELECT dept_id FROM Department WHERE dept_name IN ('IT','FINANCE'))is a subquery, which can return one or more rows. The subquery is executed once and sends the result (2,3) to the outer query. Then the outer query SELECT * FROM Employee WHERE dept_id IN (2,3) is executed and returns list of employees with dept_id = 2 or dept_id = 3.

Subquery with EXISTS operator

In PostgreSQL, the subquery can be passed as input to EXISTS operator EXISTS <sub_query>.

The subquery has a condition specified that joins with a table of the outer query. For every row of the outer query, the subquery is executed. If the subquery returns at least one row for the outer query matching row, the EXISTS returns true. If the subquery returns no rows for the outer query matching row, the EXISTS returns false.

The EXISTS operator only checks the number of rows returned from the subquery. It does not care about the content of the row.

The subquery with EXISTS operator is also called a correlated subquery.

Let's use subquery with EXISTS operator to fetch all employees who belong to the IT and FINANCE department.

Example: Subquery with Exists Operator
SELECT * FROM Employee emp
WHERE EXISTS (SELECT 'X' FROM Department dept
				 WHERE dept.dept_id = emp.dept_id
			  	 AND dept_name IN ('IT','FINANCE'));

As you can see, we are getting the same rows in the result set as using IN operator. The subquery has a joining condition dept.dept_id = emp.dept_id that performs an inner join between the Employee and Department tables. For each row of the Employee table, the subquery is executed once to check whether that employee belongs to the IT or FINANCE department or not. If for an employee, a matching row is found in the department then that employee will be shown in the result set.

TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.