487 points · by todsacerdoti · 2y ago · 190 comments
It's like prettification in any other language - visual structures that we can quickly recognize (like consistent indentation levels) make us waste less time on comprehension of the obvious so we can focus on what's important.
The only thing I really object to is "actuallyUsingCaseInIdentifiers" I never want to see columns that require double quotes for me to inspect on cli.
Personally, given SQL's intended similarity to English, I find that I like English "sentence case" for it, with the opening keyword starting with a capital letter and nearly every remaining letter lower case (except for Proper Nouns, the truly case-sensitive parts of SQL like table names). Sentence case has been helpful to me in the past in spotting things like missing semicolons in dialects like Postgres' that require them, and/or near keywords like `Merge` that require them or helping to visually make sure the `select` under a `Merge` is intended as a clause rather than starting a new "sentence".
I could go either way, but if you want to go back and modify a query, this makes it more difficult for me. I just use a block syntax for my queries:
SELECT *
FROM the_table
WHERE some_column = 12
AND other_column IS NOT NULL
ORDER BY order_column;Specifically, if I'm banging out an ad-hoc query that no one will ever see, and I'm going to throw away, I don't worry about casing.
Otherwise, for me, all SQL that's checked in gets the commands in ALL CAPS.
So I wrote a thing that lets me use sql text as a function, it is several sorts of terrible, in that way that you should never write clever code. but I am not really a programmer, most of my code is for myself. I keep using it more and more. I dread the day Someone else needs to look at my code.
E.g., the last time I used the psql program, I don't think it had colorization of the SQL, despite running in a color-capable terminal emulator.
It probably doesn't help that terminal colors are a bit of mess. E.g., piping colored output through 'less' can result in some messy control-character rendering rather than having the desired effect.
It can, but -G or -R can fix that.
This is mostly irrelevant since you really shouldn't be mixing quoted with unquoted identifiers, and introspection largely isn't standardized.
Usual caveat of how nobody sticks to the ANSI standard anyway applies.
There is sqlfluff etc but I'm curious what people use.
[1] DuckDB SQL dialect is very close to Postgres, it's compatible in many ways but has some extra QOL features related to analytics, and lacks a few features like `vacuum full`;
If you don't:
- https://www.depesz.com/2022/09/21/prettify-sql-queries-from-...
- https://gitlab.com/depesz/pg-sql-prettyprinter
Or https://paste.depesz.com for one-off use.
I thought he was talking about psql's case sensitivity with table names, which is incredibly aggravating.
Considering most programming languages do just fine without ALL CAPS KEYWORDS I'd say it's a strange effort. I wish SQL didn't insist on being different this way.
I agree with you on prettification though. As long as the repository chooses a prettifier you can view it your way then commit it their way. So that's my advice: always demand prettification for pull requests.
Obviously not very foolproof, but automated linters/prettifiers like the one in DataGrip do a good job with this for every query I've ever thrown at it.
The combination of all caps keywords + following "the river" whitespace pattern dramatically improves readability in my opinion
All caps letters are more similar and harder to read.
But getting some editor that highlights the SQL will completely solve your issue.
I think the increased legibility for visual pattern matching also makes SQL easier to read for many of the 350 million color blind people in the world.
I've been tinkering with a weird hack for this issue which might help or at least offer some inspiration.
It's similar to the foot-gun of "eagerly convert straight to UTC" except you can easily recalculate it later whenever you feel like it. Meanwhile, you get to keep the same performance benefits from all-UTC sorting and diffing.
The trick involves two additional columns along with time_zone and time_stamp, like:
-- Column that exist as a kind of trigger/info
time_recomputed_on TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT now(),
-- You might be able to do this with special triggers too
-- This coalesce() is a hack so that the above column changing causes re-generation
estimated_utc TIMESTAMP GENERATED ALWAYS AS (COALESCE(timezone('UTC', timezone(time_zone, time_stamp)), time_recomputed_on)) STORED
PostgreSQL will recalculate estimated_utc whenever any of the other referenced columns change, including the useless dependency on time_recomputed_on. So you can force a recalc with: UPDATE table_name SET time_recomputed_on = now() WHERE time_recomputed_on < X;
Note that if you want time_recomputed_on to be more truthful, it should probably get updated if/when either time_zone or stamp are changed. Otherwise it might show the value as staler than it really is.https://www.postgresql.org/docs/current/ddl-generated-column...
Naming is highly misleading though.
But you're right that timestamptz on postgres is different from timestamptz on oracle, which _does_ store a timezone field.
Made me reconsider a few habits I picked up from MySQL land
For example, how nulls work - especially how interact with indexes and unique constraints - is also non-intuitive in mysql.
If you have a user table with a non-nullable email column and a nullable username column, and a uniqueness constraint on something like (email, username), you'll be able to insert multiple identical emails with a null username into that table - because a null isn't equivalent to another null.
FWIW, since 15 postgres you can influence that behaviour with NULLS [NOT] DISTINCT for constraints and unique indexes.
https://www.postgresql.org/docs/devel/sql-createtable.html#S...
EDIT: Added link
Ouch. You don't want to just say that and move on.
The author even linked to a page citing 10 different kinds of normalization (11 with the "non-normalized"). Most people don't even know what those are, and have no use for 7 of those. Do not send people on wild-goose chases after those higher normal forms.
And they're right! I've had to fix a few issues of this in a project I recently got moved to. There's almost never a reason to duplicate data.
Sure, this means you will have some "unnecessary" `tenant_id` columns in some tables that you could get through a relation, but it saves you from _having_ to include that relation just to limit by tenant, which you will some day almost be guaranteed to want. (Especially if you want to enable row-level security¹ someday.)
¹ - https://www.postgresql.org/docs/current/ddl-rowsecurity.html
This way we can load up all the data needed to process an order or invoice etc easily, without a ton of joins.
We don't do multi-tenant, instead separate databases per tenant so far.
It's usually to normalize into the 3rd form. But that's not enough on some cases, that's too much on some other cases, and the reason it breaks is performance about as often as it's not.
6NF means having one non-PK column, so that if the value would be NULL then the row need not exist, and so the value column can be NOT NULL.
But when you need all the columns of what you'd think of as the <thing> then you need to go gather them from all those rows in all those tables. It's a bit annoying. On the other hand a proper EAV schema has its positives (though also its negatives).
In my experience every non-trivial project would need several dozen columns in core tables, all which could be NULL while the user works on the record during the day.
In our current project we'd have to do several hundred joins to get a single main-table record.
I also wonder why people have such an aversion for NULL. Crappy tools?
I didn't know this when I started, so I never vacuumed the reddit databases. Then one day I was forced to, and it took reddit down for almost a day while I waited for it to finish.
And we did run out of transaction IDs, which is why I was forced to do it.
I never turned on the auto-vacuumer but I did set up a daily vacuum.
Keep in mind I left Reddit 13 years ago and I’m sure they’ve made improvements since.
I did none of that work but was on the team where it happened.
More experienced developers knew that the correct answer was to duplicate nothing (except for keys obviously) and then to denormalize only with extreme reluctance.
Then databases like mongo came along and encouraged those juniors by giving them something like a database, but where normalization was difficult/irrelevant. The result was a brief flowering of horrible database designs and unmaintainable crap towers.
Now the pendulum has swing back and people have rediscovered the virtues of a normalized database, but JSON columns provide an escape hatch where those bad practices can still flower.
That said, I’ve worked on projects that had almost no normalization, and it was pure hell. I’m certainly not arguing against normalizing; just saying that data blobs are useful sometimes.
I'm fine with using it for simple throw away stuff, but deciphering someone else's ball of json is soul killing.
1. To store JSON. There's a pattern where when your webserver calls into some third-party API, you store the raw API response in a JSONB column, and then process the response from there. This gives you an auditable paper trail if you need to debug issues coming from that 3rd-party API.
2. To store sum types. SQL not supporting sum types is arguably the biggest deficiency when modelling data in SQL databases. There are several workarounds - one of them being "just chuck it in a JSONB column and validate it in the application" - but none of the workarounds is particularly great.
3. End-user extra fields. Stuff you don't care about, but someone somewhere does.
Whether we actually should be building DMBSes on top of DMBSes is questionable, but is the current state of affairs regardless.
. They never used queries and instead had their own in-memory operators for traversing the graph, had to solve problems like deleting an entry and removing all references, partial graph updates.
And I still don’t think it works.
If there are CLI tools involved, you also need to ensure you can handle some downtime, or do synchronized version update across company, or support both old and new schemas for a while.
If a database is not part of team's primary product all of this could be missing.
i think the author might find it helpful to readers to add a note to https://challahscript.com/what_i_wish_someone_told_me_about_... that if someone is selecting for b alone, then an index on columns (b, a) would work fine. i think this is kind of implied when they talk about selecting on a alone, but maybe it wouldn't hurt to be extra explicit.
(i didn't spend much time on the json/jsonb part since i rarely use that stuff)
It would be a good start to read the paper of codd and trying to understand what the relational model is. It's only 11 pages long and doing that would reduce the suffering in this world.
I'd also recommend reading up on the awesome pg statistics tables, and leverage them to benchmark your things like index performance and macro call speeds.
Because 'null' in the JSON spec is a literal value (a constant), not SQL's NULL. Nothing to see here.
Great and super useful notes
We were migrating from version 1 to version 2, double writing into the same table. An index on (key, val, version) was being hit by our reader process using a where clause like key=k and version=1.
When we flipped the reader to read version 2, the latency jumped from 30ms to 11s. Explain showed a sequential scan even though the index could serve the query. I was able to use MATERIALIZED and reorder CTEs to get the planner to do the right thing, but it caused an outage.
We were autovacuuming as well. I ended up deleting the old version and rebuilding the index.
My theory is that because the read load was on 50% of the data, the stats were super skewed.
... although I haven't had the chance to verify this myself
json_col #>> '{foo,bar,baz}'This is one of the more perplexing thing to me where Postgres ideology is a bit too strong, or at least, the way it works is too hard for me to understand (and I've tried - I'm not going to claim I'm a genius but I'm also not a moron). I hear there may be finally support for some kind of hints in upcoming versions, which would be very welcome to me. I've spent way too much time trying to divine the voodoo of why a slow query is not using indexes when it seems obvious that it should.
I think that given that you are not really dealing with structured data - you've said that different sites have different structures, and I assume even with processing, you may not be able to generate identical metadata structures from each entry.
I think I would go for one column of XML, plus maybe another column that holds a parsed data structure that represents the result of your processing (basically a cache holding the post-processed version of each site). Hopefully that could be re-evaluated by whatever language (Python?) you are using for your application. That way you don't have to do the full parsing each time you want to examine the entry, but you have access to something that can quickly give you whatever metadata is associated with it, but which doesn't tie you to the rigid structure of a table based database.
Once you know what you are really doing with the data, then you could add additional metadata columns that are more rigid, and which can be queried directly in SQL as you identify patterns that are useful for performance.
Store some parsed representation that makes it easier for you to work with (probably normalized). Keep an archive of raw data somewhere. That may be another column, table or even S3 bucket. Don't worry about schema changes but you need to not lose the original data. There are some pitfalls to schema migrations. But the schema should be the representation that works for you _at the moment_, otherwise it'll slow you down.
If you’re just reprinting — you’re parsing only for the sake of rendering logic — then storing the parse-result is probably just extra unnecessary work.
Also if storage isn’t a concern, then I like using the database as intermediate storage for the pipeline. Grab the RSS, stuff it in the DB as-is. Take it out of the DB, parse, store the parse results. Etc. You’ll have to do this anyways if you’re going to end up with a processing queue (and you can use PG as a simple queue.. SELECT…FOR UPDATE), but it’s nice-to-have if your pipeline is going to eventually change as well — and you’re able to reprocess old items
> Store it in multiple columns after processing it and it may require different logic for different websites + changing your overall python processing logic requires a lot of thinking on how it might affect some source.
Don’t you need to deal with this problem regardless? Ideally you’ll find a common subset you actually care about and your app-logic will look like website —> website handler -> extract data subset —> add to common structure —> render common structure
Even if you don’t use a database at all your app-code will need to figure out the data normalization
Don't <thing>
Why not?
When should you?
format of the Postgres Don't Do This page.
I assume _someone_ can read this pseudo programming, but it's not me.
https://www.oreilly.com/library/view/postgresql-16-administr...
The alternative is they have to break it up into several quasi examples, each with their own optional modifiers.
If I may suggest, use `position: sticky` instead of `position: fixed` or some equivalent to whatever trick you used.
\pset null '␀'This bit me. It's highly tedious that case isn't preserved honestly.
Oracle enters the chat... (last I used it it considered an empty string '' the same as NULL)
At this point "journey" is a cringe word because of it's excessive usage in blogspamverts. It tells me you are a gross aspiring influencer.
>"You don't need to write SQL in uppercase"
>"What's an index ?" section
From reading this, it's clear that the author never sat down and learned to use databases from the ground up. The author started using them and learned as he went, so his "tips" include things you'll be told in the first hour of any course.
This doesn't hold any value for someone who's been using databases for almost any length of time.
Then ask it to rewrite the query three different ways and explain the pros and cons of each.
Do the same for any existing queries in your system … drop in the schema then the query and ask for an analysis and suggested improvements.
It will give some good basic results and probably some functional queries, but it misses the mark with the finer points of optimization etc. If you don't know how to properly build the queries, go learn it properly with confidence that what you're learning is actually reliable.