ruk·si

🐘 PostgreSQL
INSERT

Updated at 2015-05-02 13:59

All statements works in PostgreSQL 9.1+. For more PostgreSQL notes, check out PostgreSQL Guide

Inserting a single row.

INSERT INTO films
    (code, title, document_id, produced, genre)
VALUES
    ('T_601', 'Yojimbo', 106, '1961-06-16', 'Drama');

Inserting multiple rows.

INSERT INTO films
    (code, title, document_id, produced, genre)
VALUES
    ('B6717', 'Tampopo', 110, '1985-02-10', 'Comedy'),
    ('HG120', 'The Dinner Game', 140, '1998-04-15', 'Comedy');

Specifying to use default value.

INSERT INTO films
    (code, title, document_id, produced, genre)
VALUES
    ('T_601', 'Yojimbo', 106, DEFAULT, 'Drama');

Make the statement return a value.

INSERT INTO distributors
    (name)
VALUES
    (DEFAULT, 'XYZ Widgets')
RETURNING distributor_id;           -- Returns just the value.

INSERT INTO distributors
    (name)
VALUES
    ('Acme'),
    ('Dollan')
RETURNING distributor_id, name;     -- Returns all rows.

Using WITH for logging.

WITH upd AS (
    UPDATE employees SET
        sales_count = sales_count + 1
    WHERE id = (
        SELECT sales_person
        FROM accounts
        WHERE name = 'Acme Corporation'
    )
    RETURNING *
)
INSERT INTO employees_log
SELECT *, current_timestamp
FROM upd;

Sources