EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login

PostgreSQL Subquery

Home » Data Science » Data Science Tutorials » PostgreSQL Tutorial » PostgreSQL Subquery

PostgreSQL Subquery

Introduction to PostgreSQL Subquery

PostgreSQL Subquery is also known as the nested query or inner query; it is the query within another query and embedded within where clause. It is used to returns data that will be used in the main query as a condition to restrict the data further to be retrieved. It is used to select, insert, update and delete statements along with the operators like >, =, <, >=, <=, IN, etc. There are many rules available to use a subquery in PostgreSQL.

Syntax of PostgreSQL Subquery

Below is the syntax as follows.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

1. With a select statement

Select column_name1, .., column_nameN
From table_name1 [, table_name2] Where column_name operator
Select column_name from table_name1 [, table_name2] [Where] condition)

2. With Insert statement

INSERT INTO table_name [ (column_name1 [, column_name2 ]) ] SELECT [ *|column_name1 [, column_name2 ] ] FROM table_name1 [, table_name2] [WHERE VALUE OPERATOR]

3. With update statement

UPDATE table_name
SET column_name = new_value
[WHERE OPERATOR [VALUE] (SELECT COLUMN_NAME
FROM TABLE_NAME)
[WHERE) ]

4. With delete statement

DELETE FROM TABLE_NAME
[ WHERE OPERATOR [ VALUE ] (SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]

Below is the parameter description of the above syntax are as follows.

  • Select – Used to select the statement.
  • Column_name1 to column_nameN – It specifies the Column name.
  • From – From clause is used to select the specified table from which we need to fetch the data.
  • TABLE_NAME – Used to specify the Table name.
  • Where condition – Where condition specified to fetch data as per the condition described in the query to fetch the data.
  • Operator – Operator, is used to specifying the condition. Operators like >, =, <, >=, <=, IN etc. used in PostgreSQL.
  • Insert – Used to Insert statement.
  • Delete – Used to Delete statement.
  • Update – Used to Update statement.

Working of PostgreSQL Subquery

Below is the working as follows.

  • It is a nested subquery, also knows as an inner query In PostgreSQL.
  • We have used the PostgreSQL subquery in select, insert, update and delete statements.
  • We have selected subquery in operators like >, =, <, >=, <=, IN. These operators used along with where condition in PostgreSQL subquery.
  • In PostgreSQL, subquery between operators cannot be used with a subquery, but it is used within the subquery.
  • It must be enclosed with parenthesis.
  • Only one column we have used in the select clause and multiple columns is in the main query to compare it with selected columns.
  • Order by clause is not used in the PostgreSQL subquery, but we can use it within the main query.
  • Instead of the order by, we have used group by to perform the same operation as order by in the PostgreSQL subquery.
  • It will return more than one row.
  • The subquery is used to return data that is used in the main query as a condition to restrict the data further to be retrieved from the query.

Types of PostgreSQL Subquery

Below is the type as follows. We have used Employee_test1 and Employee_test2 tables to describe types.

1. Table1 – Employee_test1

CREATE TABLE Employee_Test1 ( emp_id INT NOT NULL, emp_name character(10) NOT NULL, emp_address character(20) NOT NULL, emp_phone character(14), emp_salary INT NOT NULL, date_of_joining date NOT NULL);

PostgreSQL Subquery Table 1 - 1

INSERT INTO Employee_Test1 (emp_id, emp_name, emp_address, emp_phone, emp_salary, date_of_joining) VALUES (1, 'ABC', 'Pune', '1234567890', 20000, '01-01-2020');

PostgreSQL Subquery Table 1 - 2

INSERT INTO Employee_Test1 (emp_id, emp_name, emp_address, emp_phone, emp_salary, date_of_joining) VALUES (2, 'PQR', 'Pune', '1234567890', 20000, '01-01-2020');

PostgreSQL Subquery Table 1 - 3

INSERT INTO Employee_Test1 (emp_id, emp_name, emp_address, emp_phone, emp_salary, date_of_joining) VALUES (3, 'XYZ', 'Mumbai', '1234567890', 35000, '02-01-2020');

PostgreSQL Subquery Table 1 - 4

INSERT INTO Employee_Test1 (emp_id, emp_name, emp_address, emp_phone, emp_salary, date_of_joining) VALUES (4, 'BBS', 'Mumbai', '1234567890', 45000, '02-01-2020');

PostgreSQL Subquery Table 1 - 5

INSERT INTO Employee_Test1 (emp_id, emp_name, emp_address, emp_phone, emp_salary, date_of_joining) VALUES (5, 'RBS', 'Delhi', '1234567890', 50000, '03-01-2020');

PostgreSQL Subquery Table 1 - 6

select * from Employee_Test1;

PostgreSQL Subquery Table 1 - 7

2. Table2 – Employee_test2

CREATE TABLE Employee_Test2 ( emp_id INT NOT NULL, emp_name character(10) NOT NULL, emp_address character(20) NOT NULL, emp_phone character(14), emp_salary INT NOT NULL, date_of_joining date NOT NULL);

PostgreSQL Subquery Table 2 - 1

INSERT INTO Employee_Test2 (emp_id, emp_name, emp_address, emp_phone, emp_salary, date_of_joining) VALUES (1, 'PQR', 'Pune', '1234567890', 20000, '01-01-2020');

PostgreSQL Subquery Table 2 - 2

INSERT INTO Employee_Test2 (emp_id, emp_name, emp_address, emp_phone, emp_salary, date_of_joining) VALUES (2, 'XYZ', 'Mumbai', '1234567890', 35000, '02-01-2020');

PostgreSQL Subquery Table 2 - 3

INSERT INTO Employee_Test2 (emp_id, emp_name, emp_address, emp_phone, emp_salary, date_of_joining) VALUES (3, 'BBS', 'Mumbai', '1234567890', 45000, '02-01-2020');

PostgreSQL Subquery Table 2 - 4

INSERT INTO Employee_Test2 (emp_id, emp_name, emp_address, emp_phone, emp_salary, date_of_joining) VALUES (4, 'RBS', 'Delhi', '1234567890', 50000, '03-01-2020');

PostgreSQL Subquery Table 2 - 5

INSERT INTO Employee_Test2 (emp_id, emp_name, emp_address, emp_phone, emp_salary, date_of_joining) VALUES (6, 'ABC', 'Pune', '1234567890', 20000, '01-01-2020');

PostgreSQL Subquery Table 2 - 6

select * from Employee_test2;

PostgreSQL Subquery Table 2 - 7

  • Subqueries with the SELECT Statement

 Below is the example of the Subqueries with the SELECT Statement is as follows.

select * from Employee_Test1 where emp_id IN (select emp_id from Employee_Test2 where emp_salary > 35000);

Sub queries with the SELECT Statement

  • Subqueries with the INSERT Statement

 Below is the example of the Subqueries with the INSERT Statement is as follows.

INSERT INTO Employee_Test1 SELECT * FROM Employee_Test2 WHERE EMP_ID IN (SELECT EMP_ID FROM Employee_Test2) ;

Sub queries with the INSERT Statement 1

select * from Employee_test1;

Sub queries with the INSERT Statement 2

  • Subqueries with the UPDATE Statement

 Below is the example of the Subqueries with the UPDATE Statement is as follows.

UPDATE Employee_Test1 SET EMP_SALARY = EMP_SALARY * 5 WHERE EMP_ID IN (SELECT EMP_ID FROM Employee_Test2 WHERE EMP_ID > 2 );

Sub queries with the UPDATE Statement 1

select * from Employee_test1;

Sub queries with the UPDATE Statement 2

  • Subqueries with the DELETE Statement

 Below is the example of the Subqueries with the DELETE Statement is as follows.

DELETE FROM Employee_Test1 WHERE EMP_ID IN (SELECT EMP_ID FROM Employee_Test2 WHERE EMP_ID > 2);

Sub queries with the DELETE Statement 1

select * from Employee_test1;

Sub queries with the DELETE Statement 2

Conclusion

It is also known as nested as well as an inner subquery. Order by clause not used in Subquery but used in the main query. We used to group by clause instead of the order by clause in the PostgreSQL subquery.

Recommended Articles

This is a guide to PostgreSQL Subquery. Here we discuss the types, working, and parameters along with the examples.  You may also have a look at the following articles to learn more –

  1. PostgreSQL Date Functions
  2. PostgreSQL Data Types
  3. PostgreSQL Operators
  4. Guide to PostgreSQL Schema
  5. Complete Guide to PostgreSQL IN Operator
  6. Guide to PostgreSQL Alias
  7. Learn the PostgreSQL LIMIT

All in One Data Science Bundle (360+ Courses, 50+ projects)

360+ Online Courses

50+ projects

1500+ Hours

Verifiable Certificates

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
PostgreSQL Tutorial
  • Advanced
    • PostgreSQL Schema
    • Postgres List Schemas
    • PostgreSQL VARCHAR
    • Array in PostgreSQL
    • PostgreSQL DDL
    • PostgreSQL List Users
    • Postgres Default User
    • Postgres add user
    • PostgreSQL log_statement
    • PostgreSQL String Functions
    • PostgreSQL Compare Strings
    • PostgreSQL Text Search
    • PostgreSQL TEXT
    • PostgreSQL String Array
    • PostgreSQL Constraints
    • PostgreSQL UNIQUE 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
    • 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 Timestamp
    • PostgreSQL CURRENT_TIMESTAMP()
    • PostgreSQL Notify
    • 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 Database
    • PostgreSQL Clone Database
    • PostgreSQL Copy Database
    • 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 cluster
    • PostgreSQL Replication
    • PostgreSQL Logical Replication
    • PostgreSQL flush privileges
    • PostgreSQL Tablespaces
    • CAST in PostgreSQL
    • PostgreSQL CTE
    • hstore in PostgreSQL
    • 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 JDBC Driver
    • PostgreSQL Interview Questions
  • Basic
    • What is PostgreSQL
    • PostgreSQL Features
    • How to Install PostgreSQL
    • PostgreSQL Versions
    • PostgreSQL Architecture
    • PostgreSQL GUI
    • PostgreSQL Variables
    • PostgreSQL Data Types
    • PostgreSQL NOT NULL
    • PostgreSQL Integer
    • PostgreSQL Boolean
    • PostgreSQL NULLIF
    • PostgreSQL Administration
    • PostgreSQL Commands
    • PostgreSQL Operators
    • PostgreSQL IN Operator
  • 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 WHERE Clause
    • PostgreSQL WITH Clause
    • PostgreSQL ORDER BY
    • PostgreSQL ORDER BY Random
    • PostgreSQL GROUP BY
    • PostgreSQL group_concat
    • PostgreSQL HAVING
    • PostgreSQL Recursive Query
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • 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

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

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

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

EDUCBA

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

Forgot Password?

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

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

Special Offer - All in One Data Science Bundle (360+ Courses, 50+ projects) Learn More