Sub topic 12
When to Use Something Else
Assume you know basic CREATE TABLE, SELECT, INSERT, and UPDATE statements. You should also know the difference between a table and a view, and understand that indexes speed up some searches.
A generated column is a good fit when PostgreSQL can calculate a value from other columns in the same row. Sometimes the value needs information that generated columns cannot use, or storing the value is unnecessary. In those cases, choose a view, an expression index, or a trigger.
Compare the alternatives
| Need | Good choice | Why |
|---|---|---|
| Reuse a calculated value in many queries | Generated column or view | Both give the calculation a named interface |
| Search by a calculation without storing it | Expression index | The index stores the calculated key |
| Combine data from several tables | View | A view can contain joins and aggregations |
| Calculate a value from another row or table | Trigger | A trigger can run custom procedural logic |
| Keep a result physically stored for fast reads | Generated column or trigger | Both write a value into the table |
The important question is where the calculation belongs:
- A generated column belongs to one row and is maintained by PostgreSQL.
- A view calculates its result when you read it.
- An expression index stores calculated index keys, but does not add a selectable column.
- A trigger runs custom code when a row changes.
Use a view for read-time calculations
A view is a named query. It does not normally store its result. PostgreSQL runs the query when you read from the view.
Use a view when the derived result combines columns from several tables, needs filtering, or should always reflect current source data.
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
subtotal numeric(10, 2) NOT NULL,
tax numeric(10, 2) NOT NULL
);
CREATE VIEW order_totals AS
SELECT
id,
subtotal,
tax,
subtotal + tax AS total
FROM orders;
SELECT id, total
FROM order_totals
WHERE total > 100;This view avoids storing total. A change to subtotal or tax appears immediately when the view is queried. The trade-off is that PostgreSQL may repeat the calculation for every read. A normal view also cannot automatically provide an index on total.
A materialized view stores the result of a query, but it must be refreshed. It can help with expensive joins or aggregates when slightly stale data is acceptable.
Use an expression index for search performance
An expression index indexes the result of an expression without adding a column to the table. Use it when the main requirement is finding rows by a calculation.
CREATE TABLE people (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
first_name text NOT NULL,
last_name text NOT NULL
);
CREATE INDEX people_full_name_idx
ON people ((first_name || ' ' || last_name));
SELECT id
FROM people
WHERE (first_name || ' ' || last_name) = 'Ada Lovelace';The query expression must match the indexed expression closely enough for the planner to use the index. An expression index does not make full_name available in SELECT statements, and it does not provide a stored value for another column or application.
The expression must also satisfy PostgreSQL's index-expression rules. In practice, use immutable expressions whose result depends only on their inputs.
Use a trigger for broader logic
A trigger runs a function automatically when an event such as INSERT or UPDATE occurs. It is appropriate when the result depends on other rows, another table, or logic that a generated-column expression cannot express.
CREATE TABLE invoices (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id bigint NOT NULL,
amount numeric(10, 2) NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE FUNCTION set_invoice_updated_at()
RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
NEW.updated_at := now();
RETURN NEW;
END;
$$;
CREATE TRIGGER invoices_set_updated_at
BEFORE UPDATE ON invoices
FOR EACH ROW
EXECUTE FUNCTION set_invoice_updated_at();Triggers can contain conditionals, queries, and procedural code. They also introduce hidden write behavior. Developers must inspect the trigger to understand why a value changed. Multiple triggers can interact, and careless cross-row updates can create locking or consistency problems.
Use a trigger only when its extra power is necessary. Keep the function small, document it, and test updates as well as inserts.
A practical decision rule
Choose a generated column for a deterministic, same-row value that should behave like a normal column. Choose a view when flexibility and always-current results matter more than storing the calculation. Choose an expression index when the calculation is needed mainly in a WHERE or ORDER BY condition. Choose a trigger when the calculation requires procedural logic or data outside the current row.
If the derived data is part of a business event, such as recording the price used at checkout, store that value explicitly. A live calculation may change when source data changes, while an event record often needs an immutable historical value.
Exercise
You need to filter people by lower(email), but you do not need to select the transformed value as a separate column. Which alternative is the best fit, and why?
Show answer
Create an expression index on lower(email). It indexes the search expression without adding or maintaining another selectable column.