๐Ÿ˜œ

์ญˆ๋‚˜์•„๋น  ๋ธ”๋กœ๊ทธ

JUNA
STUDIO

[PostgreSQL] Optimizing SQL Queries with Temporary Tables

๋ฐœํ–‰์ผ: Feb, 2025
์กฐํšŒ์ˆ˜: 5
๋‹จ์–ด์ˆ˜: 148

Table of Contents

Problem with Nested Select Queries

When writing complex SQL queries in a single statement, you may need to use nested select queries. These queries often lead to additional JOIN operations, which can significantly increase execution time due to high computational costs.


Using Temporary Tables for Optimization

To avoid performance issues with nested selects, you can create temporary tables to store intermediate query results. By performing JOIN operations on these temporary tables instead, you can retrieve data much faster.


Creating a Temporary Table in PostgreSQL

In PostgreSQL, you can create a temporary table using the following syntax:

CREATE TEMP TABLE temp_test
(
  "Id" INT,
  "Name" TEXT
);

ON COMMIT Options

Unlike MSSQL, PostgreSQL allows additional options when creating temporary tables:

-- By default, the table preserves rows across transactions.
CREATE TEMP TABLE temp_test
(
  "Id" INT,
  "Name" TEXT
)
ON COMMIT PRESERVE ROWS;

-- Deletes all rows when the transaction is committed, but the table remains.
CREATE TEMP TABLE temp_test
(
  "Id" INT,
  "Name" TEXT
)
ON COMMIT DELETE ROWS;

-- Drops the table entirely upon transaction commit.
CREATE TEMP TABLE temp_test
(
  "Id" INT,
  "Name" TEXT
)
ON COMMIT DROP;

Official Documentation

For more details, refer to the official PostgreSQL documentation: PostgreSQL CREATE TABLE Documentation


Tags: #PostgreSQL#SQL#Temporary Table#Performance Optimization#Nested Select#ON COMMIT
JUNA BLOG VISITORS
Today
7
 (
updown
-7
)
Total
657
 (
updown
+7
)

ยฉ 2025 juniyunapapa@gmail.com.