Below is the short, honest answer first; then a few ways to get what you want anyway.
- Can I use a generated column for this?
No, not directly.
PostgreSQL’s generated columns (GENERATED ALWAYS AS …) are only allowed to refer to columns of the same row.
They are not allowed to run sub-queries, window functions, or otherwise “look at” other rows.
So “count how many rows have a date that is < this row’s date” cannot be a generated column.
- What are my options instead?
Option A – Calculate it on the fly with a window function
(This is usually fast enough and needs zero extra storage.)
SELECT t.*,
-- number of rows strictly earlier than this row
ROW_NUMBER() OVER (ORDER BY the_date) - 1 AS earlier_rows
FROM daily_table AS t;
Equivalent form if you prefer COUNT:
SELECT t.*,
COUNT(*) OVER (ORDER BY the_date
ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)
AS earlier_rows
FROM daily_table AS t;
• First row → 0
• Second row → 1
• …and so on.
Option B – Materialised view
(Pre-computed, refresh when you need fresh numbers.)
CREATE MATERIALIZED VIEW daily_table_with_count AS
SELECT t.*,
ROW_NUMBER() OVER (ORDER BY the_date) - 1 AS earlier_rows
FROM daily_table AS t;
-- Later, when data changes:
REFRESH MATERIALIZED VIEW daily_table_with_count;
Option C – Real column maintained by a trigger
(Stored in the table, kept up-to-date automatically.)
ALTER TABLE daily_table
ADD COLUMN earlier_rows integer;
CREATE OR REPLACE FUNCTION set_earlier_rows() RETURNS trigger AS $$
BEGIN
SELECT count(*) INTO NEW.earlier_rows
FROM daily_table
WHERE the_date < NEW.the_date;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER trg_set_earlier_rows
BEFORE INSERT OR UPDATE ON daily_table
FOR EACH ROW EXECUTE FUNCTION set_earlier_rows();
Caveats for the trigger approach
• Slightly slower inserts/updates.
• Be careful with concurrent inserts for the same date; you might want extra locking or deal with possible race conditions (most people just live with it for a daily table).
- Quick reference
• Generated columns = only “this” row ⇒ cannot look at other rows.
• Window functions = perfect for cumulative counts on the fly.
• Materialised views or triggers = the workaround if you need it persisted.
Pick the option that best fits your performance / freshness needs. 👍