Feature Flag Toggle With RETURNING
Flip a boolean feature flag in place with SET enabled = NOT enabled and RETURNING the new state, so toggling needs no read-modify-write round trip.
Code
-- Feature-flag table: one row per flag; flipping the boolean column is the toggle
CREATE TABLE feature_flags (
key text PRIMARY KEY,
enabled boolean NOT NULL DEFAULT false,
updated_at timestamptz NOT NULL DEFAULT now()
);
-- Seed the default-off flag; reruns are absorbed by ON CONFLICT
INSERT INTO feature_flags (key) VALUES ('new-checkout')
ON CONFLICT (key) DO NOTHING;
-- Toggle: SET enabled = NOT enabled flips in place and RETURNING reads the new state straight back
UPDATE feature_flags
SET enabled = NOT enabled,
updated_at = now()
WHERE key = 'new-checkout'
RETURNING key, enabled;
-- Bulk enable: touch only still-disabled flags; enabled rows are not rewritten, so no dead tuples appear
UPDATE feature_flags
SET enabled = true, updated_at = now()
WHERE enabled = false
RETURNING key;Inside the snippet
Several statements share this file — INSERT / UPDATE / CREATE, with feature_flags among the objects involved.
What the statements actually assemble: a WHERE clause narrowing which rows one statement affects; an upsert guard (ON CONFLICT/MERGE) that turns insert-or-update into one atomic statement; a RETURNING clause that hands the affected rows back to the caller; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; DEFAULT values filling omitted columns.
Using it
Run the statement against the feature_flags table.
Key statements
UPDATE feature_flags
SET enabled = NOT enabled,
updated_at = now()
WHERE key = 'new-checkout'
RETURNING key, enabled;
UPDATE feature_flags
SET enabled = true, updated_at = now()
WHERE enabled = false
RETURNING key;
CREATE TABLE feature_flags (
key text PRIMARY KEY,
enabled boolean NOT NULL DEFAULT false,
updated_at timestamptz NOT NULL DEFAULT now()
);
Interactive Tools for This Topic
FAQ
- Name the tables involved in this file.
- The references are `feature_flags`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.