Data changes, transactions, and indexes

PostgreSQL 19.0

Use transactions to keep related changes together. Use indexes to improve query access when they fit how the application reads data.

On this page

Save or undo a group of changes

BEGIN starts a transaction. COMMIT makes its changes permanent and ROLLBACK discards them. Use WHERE to target the intended rows when you update or delete. This example rolls back a course fee change.

BEGIN;
UPDATE courses SET fee = 35.00 WHERE id = 1;
SELECT title, fee FROM courses WHERE id = 1;
ROLLBACK;
SELECT title, fee FROM courses WHERE id = 1;

Compare plans before and after an index

A transaction controls which changes are saved together. The next example looks at a separate question about the same database work: how PostgreSQL finds the row a query asks for. Run the same query against a temporary table before and after adding a B-tree index on sku. Each SKU occurs once in this sample. ANALYZE updates the planner statistics. EXPLAIN ANALYZE runs the SELECT and reports the plan and observed results. The rollback cleans up the sample.

BEGIN;
CREATE TEMP TABLE lesson_index_products (sku text, name text);
INSERT INTO lesson_index_products (sku, name)
SELECT 'SKU-' || n, 'Product ' || n
FROM generate_series(1, 20000) AS sample(n);
ANALYZE lesson_index_products;

EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM lesson_index_products WHERE sku = 'SKU-18000';

CREATE INDEX ON lesson_index_products (sku);

EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM lesson_index_products WHERE sku = 'SKU-18000';
ROLLBACK;
Seq Scan
Reads the table and checks rows against the filter.
Index Scan
Looks up matching entries in the index and fetches the corresponding table rows.
Index trade-off
An index takes storage and adds work to writes. For small tables or queries returning much of a table, the planner may still choose a sequential scan.

What to expect Both plans should report one actual matching row. The first plan typically shows Seq Scan and the second Index Scan. Compare the scan type and buffers. Elapsed time can vary by machine and cache state.

Official references