JIYIK CN >

Current Location:Home > Learning > DATABASE > PostgreSQL >

Using multiple WITH statements in one PostgreSQL query

Author:JIYIK Last Updated:2025/04/09 Views:

withStatements are used to create temporary tables, which means that these tables are not persisted in the database and exist only in memory until the query is completed.

The statement was introduced withto break down complex queries into simpler queries that are easier to process and debug.

This article will teach you how to use multiple withstatements to execute a query using two temporary tables in PostgreSQL.

WITHUsing multiple statements in one PostgreSQL query

Login to your PostgreSQL database using the following command. The default user is postgres.

If you have multiple users in the database, change the username. If you configured user authentication during login, enter the password in the next prompt.

david@david-HP-ProBook-6470b:~$ psql -U postgres

After successfully logging into the PostgreSQL server, use the following commands to create and connect to the database we will use to store data.

postgres=# create database multiple_with_db;
CREATE DATABASE
postgres=# \c multiple_with_db;
You are now connected to database "multiple_with_db" as user "postgres".

We first need to create two persistent tables from which we will create the temporary table. The first table will hold the customer data.

Create customerthe table as shown in the following data definition language. To create the table, you can copy and paste the query on the terminal and press Enter.

multiple_with_db=# create table customer(customer_id SERIAL UNIQUE NOT NULL,first_name varchar(50),last_name varchar(50),email varchar(60),PRIMARY KEY(customer_id));
CREATE TABLE

Use the following data manipulation language customerto create some customers in the table. You can copy and paste the query on the terminal to insert records into the table.

multiple_with_db=# insert into customer(first_name, last_name, email) values('john','doe','john@gmail.com');
INSERT 0 1
multiple_with_db=# insert into customer(first_name, last_name, email) values('mary','public','mary@gmail.com');
INSERT 0 1
multiple_with_db=# insert into customer(first_name, last_name, email) values('peter','parker','peter@gmail.com');
INSERT 0 1
multiple_with_db=# insert into customer(first_name, last_name, email) values('steve','harvey','steve@gmail.com');
INSERT 0 1

Use the following query to verify that your record was created successfully.

multiple_with_db=# select * from customer;

Output:

 customer_id | first_name | last_name |      email
-------------+------------+-----------+-----------------
           1 | john       | doe       | john@gmail.com
           2 | mary       | public    | mary@gmail.com
           3 | peter      | parker    | peter@gmail.com
           4 | steve      | harvey    | steve@gmail.com
(4 rows)

The second table contains order information for products purchased by customers. Create customer_orderthe table as shown below.

multiple_with_db=# create table customer_order(order_id SERIAL UNIQUE NOT NULL, product_name varchar(50), product_price integer, product_quantity integer, total_price integer, created_at DATE, cust_id integer REFERENCES customer(customer_id));
CREATE TABLE

Insert some records into customer_orderthe table and ensure that the referential integrity constraint references Customer as shown below.

multiple_with_db=# insert into customer_order(product_name, product_price, product_quantity, total_price, created_at, cust_id) values('laptop',500,3,3*500,'2022-03-07',1);
INSERT 0 1
multiple_with_db=# insert into customer_order(product_name, product_price, product_quantity, total_price, created_at, cust_id) values('laptop',500,4,4*500,'2022-03-07',3);
INSERT 0 1
multiple_with_db=# insert into customer_order(product_name, product_price, product_quantity, total_price, created_at, cust_id) values('laptop',500,7,7*500,'2022-03-07',4);
INSERT 0 1
multiple_with_db=# insert into customer_order(product_name, product_price, product_quantity, total_price, created_at, cust_id) values('laptop',500,5,5*500,'2022-03-07',2);
INSERT 0 1

Use the following query to ensure that your data has been successfully saved in the database.

multiple_with_db=# select * from customer_order;

Output:

 order_id | product_name | product_price | product_quantity | total_price | created_at | cust_id
----------+--------------+---------------+------------------+-------------+------------+---------
        1 | laptop       |           500 |                3 |        1500 | 2022-03-07 |       1
        2 | laptop       |           500 |                4 |        2000 | 2022-03-07 |       3
        3 | laptop       |           500 |                7 |        3500 | 2022-03-07 |       4
        5 | laptop       |           500 |                5 |        2500 | 2022-03-07 |       2
(4 rows)

WITHUse commas to separate multiple statements in PostgreSQL

To use multiple withstatements, follow the first withstatement with a comma ( ,) instead of another withstatement.

The following example shows how we can withexecute a query using multiple statements separated by commas.

The first temporary table is customercreated with all the data in the table, and the second temporary table is customer_ordercreated with all the data in the table.

Execute a query on the temporary table to return two columns, one containing the customer's email and the other containing the total price of the products purchased by each customer.

multiple_with_db=# WITH customer_info AS (select * from customer), order_info AS (select * from customer_order) SELECT (email,total_price) FROM customer_info t1 INNER JOIN order_info t2 ON t1.customer_id=t2.order_id;

Output:

          row
------------------------
 (john@gmail.com,1500)
 (mary@gmail.com,2000)
 (peter@gmail.com,3500)
 (steve@gmail.com,2500)
(4 rows)

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Terminate the PostgreSQL connection

Publish Date:2025/04/11 Views:199 Category:PostgreSQL

In this article, we will learn how to terminate a PostgreSQL session. Any open connections are run by background processes or tasks, PSQL which may no longer exist despite exiting the user interface or command line tool. Use ps -ef or grep

Single query to rename and change column type in PostgreSQL

Publish Date:2025/04/11 Views:166 Category:PostgreSQL

This article describes how to rename a column and change its type in PostgreSQL using only a single query. Renaming and changing column types in MySQL In MySQL , if you want to change the column type and rename it, you can use a simple stat

Joining columns using Select in PostgreSQL

Publish Date:2025/04/11 Views:176 Category:PostgreSQL

MySQL PostgreSQL is an object-relational database system, which means it can support more complex data types than its competitors . Today we will learn how to use SELECT the operator to join the columns of a table. Using operators to || joi

Using CASE in PostgreSQL

Publish Date:2025/04/11 Views:124 Category:PostgreSQL

This article shows how to use the statement in PostgreSQL CASE . CASE How to use the statement in PostgreSQL case Statements are similar to those in general-purpose programming languages if-else . But in SQL, if you want to write IF-ELSE ,

Using NOT IN with subqueries in PostgreSQL

Publish Date:2025/04/11 Views:93 Category:PostgreSQL

NOT IN The inverts the result of NOT simply using IN the operator. NOT IN The right side of the operator must have a subquery in which multiple columns are returned to check whether the expression matches the data. NOT IN Tends to return tr

Using variables in PostgreSQL

Publish Date:2025/04/11 Views:171 Category:PostgreSQL

This article will demonstrate how we can declare and assign values ​​to variables in PostgreSQL. In PostgreSQL, DECLARE variables are declared using Often you will need variables in your PL/SQL scripts. In DECLARE the section called , y

Connect to PostgreSQL using a password

Publish Date:2025/04/11 Views:171 Category:PostgreSQL

This article shows various ways to connect to PostgreSQL using a password. It can be through the command line, pgpass a file, PGPASSWORD an environment variable or a connection string. Connecting to PostgreSQL with a password using the comm

Deleting a database in PostgreSQL via PSQL

Publish Date:2025/04/11 Views:166 Category:PostgreSQL

There are two ways to access PostgreSQL objects and databases on your system. One is through an interface, such as a graphical interface like PGADMIN, and the other is the basic command line tool psql. Today, we will look at DROP DATABASE t

Using the database in PostgreSQL

Publish Date:2025/04/11 Views:132 Category:PostgreSQL

This article demonstrates connecting to a database, creating a new database, and creating a table in PostgreSQL. Available databases in PostgreSQL You can run the following command after opening the Postgres command line to view all availab

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial