Most teams use PostgreSQL as a place to keep tables and write everything else in the application. That works. But the database has several mechanisms that are old, well documented, and can simplify a system. Below are five of them, each with a concrete use case and a caveat about when not to use it.

Views as a read contract

A view is a stored query. Its biggest advantage is organisational, not about performance: the front end or another service reads a stable shape of data, and you can change the tables underneath.

SQL
CREATE VIEW app.order_list AS
SELECT o.id,
       o.number,
       c.name AS customer_name,
       o.status,
       sum(l.quantity * l.unit_price) AS total
FROM sales.orders o
JOIN sales.customers c ON c.id = o.customer_id
JOIN sales.order_lines l ON l.order_id = o.id
GROUP BY o.id, o.number, c.name, o.status;

The application runs SELECT * FROM app.order_list and knows nothing about three tables. List the columns of a view by name, because SELECT * inside a view definition freezes the column list at the moment of creation.

Procedures as a write contract

Since PostgreSQL 11 there are procedures called with CALL. Writing through a procedure means the rule "do not cancel an order that has already shipped" lives in one place, not in three services.

SQL
CREATE PROCEDURE app.order_cancel(p_order_id uuid)
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = pg_catalog, pg_temp
AS $$
DECLARE
    v_status text;
BEGIN
    SELECT status INTO v_status FROM sales.orders WHERE id = p_order_id FOR UPDATE;
    IF NOT FOUND THEN
        RAISE EXCEPTION 'The order does not exist' USING ERRCODE = 'U1001';
    END IF;
    IF v_status = 'shipped' THEN
        RAISE EXCEPTION 'A shipped order cannot be cancelled' USING ERRCODE = 'U1002';
    END IF;
    UPDATE sales.orders SET status = 'cancelled' WHERE id = p_order_id;
END;
$$;

Two things matter here. FOR UPDATE locks the row for the duration of the transaction, so two parallel calls cannot break the state. And SECURITY DEFINER with a fixed search_path makes the procedure run with its owner's privileges and keeps it from being fooled by a planted object with the same name. Error codes starting with U are our own convention: SQLSTATE has five characters, and the application can recognise a business rule by it.

JSONB where the data shape varies

jsonb stores a document in binary form and can be indexed. It works for data whose structure you do not control: a webhook payload, settings, attributes that differ between product types.

SQL
CREATE TABLE webhook_events (
    id uuid PRIMARY KEY,
    received_at timestamptz NOT NULL DEFAULT now(),
    payload jsonb NOT NULL
);

CREATE INDEX ix_webhook_events_payload
    ON webhook_events USING gin (payload jsonb_path_ops);

SELECT id FROM webhook_events
WHERE payload @> '{"type": "invoice.paid"}';

A GIN index with the jsonb_path_ops operator class supports the containment operator @>. It is smaller than the default one but does not support every operator, so match it to the queries you actually run. A practical rule: if you read a field in every query and filter on it, it should be a column. A column gives you a type, constraints and an ordinary index.

Indexes beyond the default

A B-tree index on a single column is the beginning. Two variants often make a difference:

SQL
-- Partial index: only the rows you ask about
CREATE INDEX ix_orders_open ON sales.orders (created_at)
    WHERE status = 'open';

-- Covering index: included columns, so the query does not have to visit the table
CREATE INDEX ix_orders_customer ON sales.orders (customer_id)
    INCLUDE (status, created_at);

A partial index is smaller and cheaper to maintain, because it covers only some of the rows. The INCLUDE clause allows index-only scans. Create a new index on a live table with CREATE INDEX CONCURRENTLY so it does not block writes, and check the effect with EXPLAIN (ANALYZE, BUFFERS), not by feel.

Row-level security

RLS moves the rule "a user sees only their own rows" from every query into the table definition. Forgetting a filter in one place stops being a data leak.

SQL
ALTER TABLE sales.orders ENABLE ROW LEVEL SECURITY;
ALTER TABLE sales.orders FORCE ROW LEVEL SECURITY;

CREATE POLICY orders_by_tenant ON sales.orders
    USING (tenant_id = current_setting('app.tenant_id')::uuid)
    WITH CHECK (tenant_id = current_setting('app.tenant_id')::uuid);

At the start of a transaction the application calls SELECT set_config('app.tenant_id', $1, true), where the third argument true limits the setting to the current transaction. Pitfalls: the table owner bypasses RLS unless you add FORCE, and superusers and roles with the BYPASSRLS attribute always bypass it. Views run with their owner's privileges by default, so for RLS to apply to queries through a view, create it with security_invoker = true (available since PostgreSQL 15).

When it is a good idea

  • Several applications or services use the same database and you need one place for the rules.
  • The team knows SQL and wants a rule change not to require an application deployment.
  • Data isolation (tenants, users) must be enforced independently of bugs in the code.

When it is not

  • The rule needs calls to external services, files or queues. That is a job for the application.
  • Nobody on the team debugs PL/pgSQL and there are no database tests. Logic you cannot test is debt.
  • The data has a fixed, known structure and someone proposes jsonb for convenience. The convenience ends at the first report.
  • You have one service and simple CRUD. Then procedures are an extra layer with no gain.

None of this is new, and that is exactly the argument. The PostgreSQL documentation has described each of these mechanisms for years, and they behave predictably.