AlgoViz

PostgreSQL

medium 32 min

PostgreSQL is an open-source relational database that never overwrites a row: every change adds a new version, readers pick the version their snapshot may see, and vacuum clears away versions nobody needs.

Row versions, snapshots and vacuum in 60 lines

Read it, run it, change a line and run it again.

Loading editor…

A small model. The real server also tracks running transactions inside a snapshot, hint bits, indexes and locks.

The same in Java
// HikariCP with the PostgreSQL JDBC driverHikariConfig config = new HikariConfig();config.setJdbcUrl("jdbc:postgresql://localhost:5432/myapp");config.setUsername("app");config.setPassword(System.getenv("DB_PASSWORD"));config.setMaximumPoolSize(20);config.setMinimumIdle(5);config.setConnectionTimeout(10_000);   // 10 s to get a connectionconfig.setIdleTimeout(300_000);        // 5 minconfig.setMaxLifetime(1_800_000);      // 30 minconfig.addDataSourceProperty("preparedStatementCacheQueries", "256");HikariDataSource pool = new HikariDataSource(config);void transfer(long from, long to, BigDecimal amount) throws SQLException {  try (Connection conn = pool.getConnection()) {    conn.setAutoCommit(false);    try (PreparedStatement debit = conn.prepareStatement(             "UPDATE accounts SET balance = balance - ? WHERE id = ? AND balance >= ?");         PreparedStatement credit = conn.prepareStatement(             "UPDATE accounts SET balance = balance + ? WHERE id = ?")) {      debit.setBigDecimal(1, amount); debit.setLong(2, from); debit.setBigDecimal(3, amount);      if (debit.executeUpdate() == 0) throw new SQLException("Insufficient funds");      credit.setBigDecimal(1, amount); credit.setLong(2, to);      credit.executeUpdate();      conn.commit();    } catch (SQLException e) {      conn.rollback();      throw e;    }  }                                    // close returns it to the pool}List<Result> search(String text, String category) throws SQLException {  String sql = """      SELECT id, title, ts_rank(search_vector, q) AS rank,             ts_headline('english', content, q, 'MaxWords=35, MinWords=15') AS snippet      FROM articles, websearch_to_tsquery('english', ?) AS q      WHERE search_vector @@ q AND (?::text IS NULL OR category = ?)      ORDER BY rank DESC LIMIT 20""";  try (Connection conn = pool.getConnection(); PreparedStatement st = conn.prepareStatement(sql)) {    st.setString(1, text); st.setString(2, category); st.setString(3, category);    List<Result> out = new ArrayList<>();    try (ResultSet rs = st.executeQuery()) {      while (rs.next()) out.add(new Result(rs.getLong("id"), rs.getString("title"),                                           rs.getDouble("rank"), rs.getString("snippet")));    }    return out;  }}
The same in SQL
-- Connections now, and the limitSELECT application_name, state, count(*) FROM pg_stat_activityWHERE datname = current_database() GROUP BY 1, 2 ORDER BY 3 DESC;SHOW max_connections;-- Serializable: be ready to run the whole transaction againBEGIN ISOLATION LEVEL SERIALIZABLE;UPDATE inventory SET quantity = quantity - 1 WHERE id = 42;COMMIT;-- Phrase, proximity and prefix searchSELECT title FROM articles WHERE search_vector @@ phraseto_tsquery('english', 'connection pooling');SELECT title FROM articles WHERE search_vector @@ to_tsquery('english', 'database <2> performance');SELECT title FROM articles WHERE search_vector @@ to_tsquery('english', 'optim:*');-- Typo-tolerant searchCREATE EXTENSION IF NOT EXISTS pg_trgm;CREATE INDEX ON articles USING gin (title gin_trgm_ops);SELECT title, similarity(title, 'postgrsql') AS s FROM articlesWHERE title % 'postgrsql' ORDER BY s DESC;-- JSONB: merge, remove, aggregateUPDATE user_settings SET preferences = preferences || '{"theme":"light"}' WHERE user_id = 1;UPDATE user_settings SET preferences = preferences - 'old_key' #- '{notifications,sms}' WHERE user_id = 1;SELECT jsonb_agg(jsonb_build_object('id', id, 'name', name)) FROM products;-- Windows: partition, percentiles, first value, a shared windowSELECT region, person, sales,       rank() OVER (PARTITION BY region ORDER BY sales DESC) AS place,       ntile(4) OVER (ORDER BY sales) AS quartile,       percent_rank() OVER (ORDER BY sales) AS pct,       cume_dist() OVER (ORDER BY sales) AS cume,       first_value(person) OVER (PARTITION BY region ORDER BY sales DESC) AS bestFROM sales_summary;SELECT month, revenue, lag(revenue, 12) OVER w AS last_year, lead(revenue) OVER w AS nextFROM monthly_revenue WINDOW w AS (ORDER BY month);-- Deep pages: remember the last key instead of counting rowsSELECT * FROM articles WHERE (created_at, id) < ($1, $2)ORDER BY created_at DESC, id DESC LIMIT 10;-- SizesSELECT relname, pg_size_pretty(pg_total_relation_size(oid)) AS total,       pg_size_pretty(pg_indexes_size(oid)) AS indexesFROM pg_class WHERE relkind = 'r' ORDER BY pg_total_relation_size(oid) DESC LIMIT 10;