PostgreSQL
Beginner
1 min read
INSERT and RETURNING
Example
-- Basic INSERT
INSERT INTO users (name, email, created_at)
VALUES ('Alice', 'alice@example.com', NOW());
-- INSERT with RETURNING — get the generated id back
INSERT INTO users (name, email)
VALUES ('Bob', 'bob@example.com')
RETURNING id, created_at;
-- Multi-row INSERT
INSERT INTO products (name, price, stock) VALUES
('Keyboard', 79.99, 100),
('Mouse', 39.99, 150),
('Headset', 129.99, 60)
RETURNING id, name;
-- INSERT ... SELECT — copy rows from another table
INSERT INTO archived_orders (id, user_id, total, archived_at)
SELECT id, user_id, total, NOW()
FROM orders
WHERE created_at < NOW() - INTERVAL '2 years';
-- UPSERT — ON CONFLICT DO UPDATE
INSERT INTO user_settings (user_id, theme, language)
VALUES (42, 'dark', 'en')
ON CONFLICT (user_id) DO UPDATE
SET theme = EXCLUDED.theme,
language = EXCLUDED.language,
updated_at = NOW();
-- ON CONFLICT DO NOTHING — ignore duplicate key errors
INSERT INTO tags (name) VALUES ('postgresql'), ('databases'), ('postgresql')
ON CONFLICT (name) DO NOTHING;
Related Resources
PostgreSQL Reference
Complete tag & property list
PostgreSQL How-To Guides
Step-by-step practical guides
PostgreSQL Exercises
Practice what you've learned
More in PostgreSQL