Goal: Compare CHECK with ENUM, prove generated values follow source updates, and observe decimal versus binary arithmetic.
Before exploring advanced column types, connect to beer_db. Run psql -U beer_db -d beer_db to open a psql session.
Inspect \d ingredients. The column is text, not an ENUM. Its CHECK accepts exactly hop, malt, yeast, and adjunct. This is the baseline closed-set design; later you will build a real enum fixture to compare.
Insert Citra Test with type = 'hop ' including the trailing space. Expect ingredients_type_check. The existing CHECK already prevents the typo; switching to ENUM is another design choice, not a repair required by this dataset.
Switch with \c weather_db weather_db: change both the database and the SQL role to the ordinary weather dataset owner. Inspect \d climate_anomalies. Find anomaly_c numeric(5,2) generated from avg_temp_c - baseline_temp_c and stored. The source columns are writable; the generated value is derived.
Insert a dedicated temperature example for 2099-01-01 using a stable existing station ID supplied by the subquery. Write average 18.5 and baseline 15.0, leaving anomaly_c out. RETURNING shows 18.50 / 15.00 / 3.50. Then update only this station/period average to 19.0 and expect 19.00 / 15.00 / 4.00. The changed result proves recalculation on UPDATE, not just initial population.
The weather example stored a calculated number: two temperatures go in, their difference comes out. Now we will use the same idea with text: a review goes in, search terms come out.
Stay in psql. Switch back with \c beer_db beer_db, then run \d beer_ratings.
Find these two columns:
review_text (text): the original sentence a person writes.
review_tsv (tsvector): a search representation PostgreSQL calculates from that sentence. A tsvector stores normalized words and their positions, rather than the original prose.
Read the generated expression from the inside out:
to_tsvector('english', COALESCE(review_text, ''))
COALESCE(review_text, '') uses the review text, or an empty string if it is NULL.
to_tsvector('english', ...) processes it using English rules, including reducing word forms to search terms.
GENERATED ALWAYS AS (...) STORED makes PostgreSQL calculate and store the result when the row is inserted or updated.
Under Indexes, idx_beer_ratings_fts is a separate GIN index on review_tsv. The generated column holds the search terms; the index helps find matching rows efficiently. Updating a review recalculates that row's column and maintains its index entries automatically.
The new approach: your application writes only review_text. The database owns the rule that keeps review_tsv in sync. The next steps will make this visible with one short review.
Before using the generated column, try its main function on its own:
SELECT to_tsvector('english', 'Fresh beer') AS search_terms;
Expect 'beer':2 'fresh':1. The words are lowercased and listed in sorted order. The numbers record their positions in the original sentence: “Fresh” was first, “beer” second.
This SELECT only shows the conversion; it does not save a review. In beer_ratings, the generated-column formula performs this conversion for you whenever you write the source text.
Insert a practice review with the text Fresh beer. Supply a beer ID, reviewer name, and score because those columns are required. The subquery picks an existing beer ID for you.
INSERT INTO beer_ratings (beer_id, reviewer_name, score, review_text)
VALUES ((SELECT id FROM beers ORDER BY id LIMIT 1),
'Generated column learner', 8.0, 'Fresh beer')
RETURNING review_text, review_tsv;
Leave review_tsv out of the INSERT. PostgreSQL fills it using the formula you just inspected. RETURNING shows both columns from the saved row: the original text and 'beer':2 'fresh':1.
We use a distinctive reviewer name so the next steps can find this practice row without changing other reviews.
Change the practice review from Fresh beer to Bitter hops:
UPDATE beer_ratings
SET review_text = 'Bitter hops'
WHERE reviewer_name = 'Generated column learner'
RETURNING review_text, review_tsv;
The WHERE clause limits the change to your practice review. Again, you write only the source text.
Expect review_tsv to become 'bitter':1 'hop':2. The old terms fresh and beer disappear. English processing reduces “hops” to hop.
With an ordinary manually maintained column, changing the text alone would leave old search terms behind. With this generated column, PostgreSQL recalculates the stored vector as part of the UPDATE. There is no second application update to forget.
Check whether your updated review matches its old word fresh or its new word hops:
SELECT review_text,
review_tsv @@ plainto_tsquery('english', 'fresh') AS matches_old_word,
review_tsv @@ plainto_tsquery('english', 'hops') AS matches_new_word
FROM beer_ratings
WHERE reviewer_name = 'Generated column learner';
plainto_tsquery converts the search input using the same English rules. @@ asks “does this vector match this search?” and returns a boolean.
Expect Bitter hops, f for the old word, and t for the new word. Searching for “hops” works even though the vector stores hop, because both sides use the same normalization.
You have now followed the whole chain: write review text → PostgreSQL generates search terms → searches use the current terms. The GIN index can speed up matching on a large table; it does not change which words match. You will explore full-text search in more depth later.
Back in beer_db, create ingredient_type_demo with labels hop, malt, yeast, and adjunct. Then create enum_demo with a NOT NULL column of that type and inspect it. These separate names avoid changing the production ingredients CHECK. Expect CREATE TYPE, CREATE TABLE, and the custom type in the table definition.
Insert hop successfully, then change only the literal to hop plus a trailing space. Expect INSERT 0 1 followed by invalid input value for enum ingredient_type_demo. A SELECT confirms exactly one saved hop row: the failed second insert did not add data.
Add label water, then insert it into the same enum column. Expect ALTER TYPE, INSERT 0 1, and the sorted labels hop then water. These are separate autocommitted commands: a value added inside an explicit transaction cannot be used until that transaction commits. There is no direct REMOVE VALUE command.
Run the same addition with float8 and numeric. :: casts the inputs. Expect 0.30000000000000004 versus 0.3. Then compare each sum to 0.3 of its own type: expect f for float8 and t for numeric. This is a controlled equality demonstration; 3.5 is exactly representable in binary, so it would not demonstrate the claimed rounding problem.
Try assigning a literal to the practice review_tsv. Expect “can only be updated to DEFAULT” and a detail saying it is a generated column. PostgreSQL permits DEFAULT to request recomputation, but rejects an independently supplied value. The practice review should still contain Bitter hops and its generated search terms.