r/programming • • Mar 18 '25

Life Altering Postgresql Patterns

https://mccue.dev/pages/3-11-25-life-altering-postgresql-patterns
233 Upvotes

82 comments sorted by

View all comments

45

u/taotau Mar 18 '25

Good summary of common best practices in general. I'd love to share this with my junior bootcamp Devs who don't like to read, but the system_id thing is just weird and a pretty bad practice.

20

u/CrackerJackKittyCat Mar 18 '25

Agree with most of these also, except for system_id and maybe 'always soft delete.'

16

u/taotau Mar 18 '25

I'm a fan of soft delete. Data at rest is cheap.

35

u/CrackerJackKittyCat Mar 18 '25 edited Mar 18 '25

I challenge you to express 'live rows in this table should only foreign key to live rows in the related table.'

Any attempt is immediately fugly, unwieldy, and has gaps. I think pervasive soft delete directly contradicts many benefits of foreign keys.

16

u/Ecksters Mar 18 '25

I do notice that this often trips up developers when they're trying to add indexes to improve performance, most of the time they should be adding partial indexes to exclude soft deleted rows, but rarely do I see them doing it, so they end up with sequential scans despite adding indexes.

8

u/FrankBattaglia Mar 18 '25

My SQL is a bit rusty, but isn't that accomplished by including a sentinel 'not_deleted = true' field on each table (and included in the foreign key) that's set to null when the record is deleted? IIRC the key will be ignored in the source table for rows where a field in the key is null, and it won't match any records in the target table where the field isn't true.

3

u/JustaDevOnTheMove Mar 20 '25

I'm not complaining about your comment at all, just expressing a syntax opinion:

I hate it when services/apps use terms like "not_something", it's so unnatural, at least to me. Saying "not_deleted = true" requires thought/concentration whereas "is_deleted = false" is just a statement that requires no mental processing.

2

u/FrankBattaglia Mar 27 '25

Agreed; were I to implement this in practice, I'd probably use is_active instead of not_deleted but for the purposes of a reddit comment the semantics of not_deleted seemed less ambiguous.

0

u/[deleted] Mar 18 '25

[deleted]

1

u/CrackerJackKittyCat Mar 19 '25

Yeah, that's good. Also can use generic trigger that copies deleted rows to an archive table including a jsonb column which holds the deleted row's data. Or kinda less generic triggers that copies to side-table(s) with actual columns plus the deleted_date.

Either can be in a separate tablespace which is 'cheaper, slower'.

If needing to do arbitrary as-of point-in-time queries, then can take the deleted side table one step further and have the side table represent all row versions with a lifetime tstzrange column, with the range start being the row INSERT/UPDATE time, and the range end being either open-ended for 'current live row version' or capped at when this row version was supplanted by either an UPDATE or DELETE operation. Then you want either a gist or sp-gist index on the range column (plus perhaps additional query fields like your primary key(s), probably spelling those additional fields first for more compact indices), and a partial unique index on the range column and primary key columns ... where upper_inf(lifetime) helping prove that the side-table maintenance triggers are doing the right thing and allowing at most one single 'live' row, and/or a more general one proving no overlapping ranges for any set of primary key(s).

Then in your point-in-time report queries ... doing the temporal joins across many such row-change-data-capture side tables gets ... really long. Making views to do the overlapping joins can then compress the actual end-user queries.

I like any of the above better than having deleted_at within the main table, in that they don't contradict foreign keys at all.

1

u/woutske Mar 18 '25

Partial indexes work great for that

7

u/CrackerJackKittyCat Mar 18 '25

They're useful in this context, sure. But still does not solve "a live row should only ever FK over to another live row,," namely breaking any TX which marks a referenced row as soft deleted w/o also marking referents.

Need ... additional trigger(s) for that, getting unwieldy fast.

1

u/taotau Mar 18 '25 edited Mar 18 '25

Where deleteddate is null.

Most orms will do this automatically, and it's not hard to add to most SQL builders.

Edit. Context dependent obviously. I deal mostly with systems where I need to be able to generate a report on 'past transactions' even if the 'customer' that made those transactions has been 'deleted' or the 'product' that those transactions were made in is no longer available.

9

u/CrackerJackKittyCat Mar 18 '25

Foreign key clause accepts a where condition?

2

u/taotau Mar 18 '25

Oh you mean trying to ensure that a foreign key has to be to a non deleted row.

Yeah. I don't do business rules in the db.

Except when I had to, but then I had a whole team of oracle boffins at my disposal to figure those things out.

→ More replies (6)

9

u/agentoutlier Mar 18 '25

It isn't always because it is expensive. It can be because of privacy.

I know this from our system where we actively used soft delete for years but then various laws of privacy passed and we have customers in other countries that take that far more seriously than here in the US.

So when they request to be deleted from your system you need to actually delete them or scrub. Sometimes scrubbing is not enough (e.g. transforming the data to nonsense).

So if you do soft delete particularly of user data you need to prepare for the potential that you will really need to do delete the data.

I say this because currently the "purge" option in our system is rather complicated SQL that I can't decide if we knew apriori we would have made data design decisions differently.

4

u/massenburger Mar 18 '25

Soft deletes don't make sense for transient data. We have a table where we store one-time passcodes. If we used soft deletes, this table would get unwieldly within about a week. We do use soft deletes for more stable, stateful data though.

11

u/turbothy Mar 18 '25

I don't even understand what it's trying to achieve.

6

u/EldritchSundae Mar 18 '25

I (think) the system_id thing is meant to differentiate data inserted and maintained by system operators for special cases, vs user maintained data, when such data otherwise fits the same structure and references and makes sense to put in the same table.

Examples I can think off of the top of my head, for a users table:

  • a default admin user in the users table before hand-off to a client

  • a system [deactivated] user you can re-relate records to when legal says all PII has to get removed but the business says all their comments have to stay

  • anonymous users you can create based on session_id on the fly before login to track app interactions, convert to concrete users on signup, and batch delete with cascade at a cadence

I like the idea behind this pattern but generally I'd say it's pretty niche and can/should often be handled by application logic instead.

There are always some constructs in any given system so pivotal to how application logic works, though (like current_user in a SaaS) that pushing special cases into the db can really clean up a lot of edge cases and enforce constraints in ways that would be otherwise error-prone and verbose in app logic.

6

u/turbothy Mar 18 '25

Thanks for the explanation, I hate it.

2

u/slvrsmth Mar 19 '25

You might hate it, but that's how businesses run. Some things are more special than others.

For example, an app I recently worked on, allows users to donate their accumulated in-app currency to a charitable cause. The "donation" is just another product as far as the purchase flows are concerned. But the business needs custom reporting to handle the donation amounts. Will you hardcode a product ID, and mess with the data to ensure IDs are same accross multiple environments? Build configuration for the IDs? Add an is_donation column, then is_foo and is_bar for the other "special" products? Add a system_id or similar to products table and you're golden, write your reports to hearts content. As a bonus, where system_id = 'donation' is much more expressive in logs than where id = '123abc-123abc-....' you would get from configuring IDs.

2

u/turbothy Mar 19 '25

But why call it the completely useless and nondescript name system_id? The column on your example would appear to be a kind: kind = 'donation', kind = 'foo', kind = 'bar'. It's actually worse than nondescript, it's a lie: donation is in all likelihood not something anybody would recognize as a system_id.

ETA: also, having this as a TEXT column without a CHECK constraint is a great way of getting data inconsistencies. I'd much prefer to have a kind table and a foreign key.