Working with Create Temporary Table in Postgres

03.14.2022

Intro

The CREATE TEMPORARY TABLE statement allows us to create a short-lived table then is removed at the end of our session. This is helpful when doing some local calculations that you don't want to keep long term. In this article we will learn hwo to use Create Temporary Table in PostgreSQL.

The Syntax

The basic syntax of CREATE TEMPORARY TABLE is as follows:

CREATE TEMPORARY TABLE [table_name] (
  [columns]
  ...
  [constraints]
)

Notice that the syntax is pretty much the same as a regular table, except for the keyword TEMPORARY.

If you want the answer, here is the quick solution.

CREATE TEMPORARY TABLE employees_temp (
  emp_no SERIAL PRIMARY KEY,
  birth_date DATE NOT NULL
);

Getting Setup

We will be using docker in this article, but feel free to install your database locally instead. Once you have docker installed, create a new file called docker-compose.yml and add the following.

version: '3'
 
services:
  db:
    image: 'postgres:latest'
    ports:
      - 5432:5432
    environment:
      POSTGRES_USER: username
      POSTGRES_PASSWORD: password
      POSTGRES_DB: default_database
    volumes:
      - psqldata:/var/lib/postgresql

  phpmyadmin:
    image: phpmyadmin/phpmyadmin
    links:
      - db
    environment:
      PMA_HOST: db
      PMA_PORT: 3306
      PMA_ARBITRARY: 1
    restart: always
    ports:
      - 8081:80

volumes:
  psqldata:

Next, run docker-compose up.

Now, navigate to http://localhost:8081/ to access phpMyAdmin. Then log in with the username root and pass root_pass.

Click the SQL tab and you are ready to go.

An Example

Creating a temporary table is pretty much the same as creating a regular table. Here is an example.

CREATE TEMPORARY TABLE employees_temp (
  emp_no SERIAL PRIMARY KEY,
  birth_date DATE NOT NULL
);

We often want to select a result set from one table and insert it into another for processing. We can use INSERT and SELECT to do this.

INSERT INTO employees_temp(emp_no,birth_date)
SELECT emp_no, birth_date
FROM employees
WHERE emp_no > 10;

With this table, we can do our normal SELECT, INSERT, UPDATE commands. We can also DROP the temporary table, although SQL will handle this for you when you exit the session.