209 points · by todsacerdoti · 4y ago · 90 comments
Very interesting insight.
Most use hybrid columnar and store chunks of rows in column-major order (Snowflake, Spanner, Parquet, Arrow).
So for small DWH, I am just using PostgreSQL
That said, consider the path of the warehouses over the last 20 years. Previously, you needed teams of data developers and engineers with modeling experts to put forth a datawarehouse that may solve a companies problem. Now, you _can_ toss very wide tables in a cloud data platform (snowflake, redshift serverless, synapse) and it likely will 'just work'. Sure it can be faster, but these problems are being slowly removed from something we have to care about.
I'm a data specialist, and my knowledge is going to be worthwhile for a good long time, but the premium that exists for it will go down I think.
"Command-line tools can be faster than your Hadoop cluster"
http://aadrake.com/command-line-tools-can-be-235x-faster-tha...
But if you want to split the table between frequently and rarely accessed sets of columns you could just use a view to bring different types of tables together? Eg: a view that brings a row-oriented table together with a column-oriented one? Or row-oriented table together with an external table (storage).
Obviously, DMLs would then become a little more complicated.
[0] https://docs.gitlab.com/ee/development/ordering_table_column...
1 word is 8 bytes, and if you use two columns, the first one having size 2 bytes, and the second – 8 bytes, you'll end up spending 8 + 8 = 16 bytes, because the first one (2byte in length) will be aligned with 6 zeroes to fill the whole "8-byte word". For example, with smalling (which has size 2 bytes but might be aligned, depending on the "column tetris" situation we have) + int8:
test=# select pg_column_size(1::int2);
pg_column_size
----------------
4
(1 row)
test=# create table tttt1 as select 1::int2 as c1, 2::int8 as c2;
SELECT 1
test=# create extension pageinspect;
CREATE EXTENSION
test=# select lp_len from heap_page_items(get_raw_page('tttt1', 0));
lp_len
--------
40
(1 row)
-- the total length of the tuple in this example is 40 bytes. Why 40? Because the tuple header is 23 bytes aligned to 3 "words", hence 24 bytes – so total is 24 + 8 + 8 = 40; though, effective data size us just 23 + 2 + 8 = 33; and 7 bytes are "wasted". And our int2 column was aligned by 6 additional bytes, to whole 8-byte word.Of course, if the second column is of size 4, then both columns fit into a single word – let's try real + int4:
if we'd have 2 int2 columns, followed by a int4 one, we'd use just one word (8 bytes to store this data, plus 24 bytes for tuple header):
test=# create table tttt2 as select 1::int2, 2::int2, 3::int4;
SELECT 1
test=# select lp_len from heap_page_items(get_raw_page('tttt2', 0));
lp_len
--------
32
(1 row)
-- in this case, the tuple length now is 32 bytes (24 bytes tuple header + 8 bytes for the data). Alignment was not needed.Thus, I don't see what's wrong with the document – probably I just didn't understand you.
E.g. attributes of types (in order) byte, smallint, smallint, int, bigint would have alignment padding of 0 (offset=0), 1 (o = 1 + 1 padding=2), 0 (o=4), 2 (o=6 +2p=8), and 4(o=12+4p=16), respectively, when all those attributes are filled with data.
[0] 'must' is the case most of the time, because variable length attributes have special handling rules when working with alignment of attributes -- but that's not important right now.
Instead, the "alignment needed" column is a self-fulfilling prophecy that tells you the required alignment for the succeeding column if the succeeding column is of at least a size requiring that alignment, and then it's not a required alignment for that type but instead that for a different type.
Your article and the parent one are explaining performance improvements related to INSERT and SELECT but what about the improved performance for UPDATE?
I wrote a long comment[0] on yesterday’s PostgreSQL post related to column order optimization with regards to UPDATE.
My information was 20+ years old and I figured it was horribly outdated but these articles make me think it could still be true.
The TLDR is you want to put variable length columns at the end because it makes UPDATE more efficient. My theory was it’ll be less likely the DB would need to move data around when updating the variable column contents.
Less data being moved = improved performance.
Seeing these articles means I was right with regards to improved performance of INSERT/SELECT but I wonder if I’m right about improved UPDATE performance.
Anyone know?
It doesn’t? Postgres columns have alignment, and that alignment goes from 1 to 8 bytes, but “postgres uses 8 byte alignment” doesn’t really make any sense.
Makes perfect sense to me, but it seems it is wrong? At least this page[1] suggests different data types have different alignment.
[1]: https://www.enterprisedb.com/postgres-tutorials/data-alignme...
There's sometimes need for control in performance-critical things, but that needs an escape hatch instead of providing everyone with an implicit tool they don't even know they have.
The same applies to struct packing in I guess most compiled languages and using the order to define ABIs.
There are limits: for example, maybe during initial creation, sure, it can pack for you, but as you start adding and dropping fields it gets more complex, and databases of consequence tend to have long lives where the returns on complication to get a better result in the initial schema load look a bit more marginal.
If you think a bit about how much more complex the cataloging of pg_attributes and the storage code needs to be to support multiple arrangements of attributes in one table -- feasibly more complicated, but definitely a lot more complicated -- you can get an idea why it isn't done.
If my client code can’t handle that, then I should specify the list in the order I want.
[1]: https://www.postgresql.org/message-id/flat/20220628083230.c4...
I'm about to move off from PostgreSQL back to MySQL primarily for this reason.
After a period of development, the ordering becomes a mess by keep adding columns to the end with no logical grouping and it's a pain to view the data that way.
Some cool optimizations are possible if the size of each row doesn't change. * Rows could be done in parallel. * The simplest method would be to copy the row to a scratch buffer, and then copy over data to their final position. * Furthermore, with some fancy permutation, you only need a register of scratch space. Although, with more random memory access, that could result in worse performance.
That’s not entirely honest. The problem is caused by the varchar (or any other variable-size column).
With fixed-size columns, postgres doesn’t need to look at the row to determine the offset of a value, it can just loop through the pg_attributes (the column definitions) and look at the nulls bitmap in the row header to skip null values. It still needs some computation (to sum the sizes of the previous columns iff they’re non-null) but that’s a lot more performance-friendly than also needing to go hit and the data tuple and decode the varlen metadata of every varlen field.
Doesn't indexes fix this too? You can index on column 100 which puts in on disk as Column100|PrimaryKey and now it's a really narrow table. Like yeah you shouldn't have a table with 1,500 columns but sometimes you really do need it.
Edit Flipped the index layout.
If your query is such that an index-only scan will fulfil it then yeah, it should.
This is more an interesting experiment than something you generally need to worry about, and if you do need to worry about it there are other things you may need to fix first (do you really need 1,500 columns on that table, is there not a design that is orders of magnitude more efficient generally thus making this issue measurable but insignificant?).
PG could be refactored to make these cases much more efficient, but the developer (and QA) time required would be much better spent elsewhere and the changes needed may impact the performance of other operations that occur far more regularly in both good and bad designs.
grow with your app like a gardener :} dont learn how to make skyscrapers when you are building houses...
when I insert rows into a table that has e.g. 30 varchar columns which are initially empty but which will be updated later (not all at once but e.g. 10 in a first round, then another 10 in another cycle, then the last 10), is it ok to leave those columns empty or should I e.g. use space-chars to fill those columns with the expected future length of the string?
Asking because I'm not sure if having the columns contents increase their size will cause kind of "row movement" (row cannot be updated in-place as there is no space to accomodate the new long string) which might(?) entangle a bit the contents of the table (e.g. maybe later the more rows are updated the more fragmented the table/tablespace becomes etc...).
I guess that Vacuum would fix such situations (if this actually happens), but maybe I can decrease the work that it has to do... . I'm just starting with Postgres, thx for reading.
EDIT: forget this, I just read here the post by "singron" stating "An update in postgres will always copy the tuple for MVCC, so it can't take advantage of an optimization like this to modify it in place", so the row gets moved anyway.
https://www.postgresql.org/docs/current/storage-page-layout....
Postgresql can store the data in any order, and I expect it to do so when it clearly makes sense to do so, such as this.
The interface of Postgres is in fact abstract enough to do such an optimization (perhaps there would be a problem with "SELECT * FROM table" queries? not sure if in that case the order of columns is specified by the standard), but they just haven't. Optimizations don't happen simply because they are allowed by an interface.
Now your abstraction has broken again, as existing tables with new columns added are performing poorly compared to new tables, even though from the abstraction level of the user, they _should_ be the same thing.
Usually the abstraction/interface gives you certain guarantees, such as "the data that a query X returns will be the same, no matter of the order of columns". But unless the abstraction makes explicit statements about performance guarantees, you shouldn't assume any.
> Essentially, the current behaviour is wasteful and never needed to be
It's not so easy. You can't just simply physically re-order columns based on new columns that were added. I mean, doing that causes IO and locks/latency issues, so maybe the user wants to run this on demand only or wants to configure it to run in the background under certain conditions, similar to vacuum. It's not trivial.
IME that's not true. I've been hacking on postgres, with occasional forays into other databases, for quite a while, and it's typically trivial to find low-hanging fruits across a varied set of workloads. It's a bit harder to find things in the most commonly benchmarked workloads, particularly when those benchmarks are easy-ish to run. But even there there's often lots.
I would guess cache misses have a larger effect than the bit twiddling needed to walk to the nth item in each row.
A way to sort-of test that would be by using a table that fits in cache and repeating the query. The noise on time measurement might make that difficult, though.
In the end it's not too surprising - a good number of columns fit in a cache line, and adjacent lines can easily be prefetched.
The cache miss matters a lot for the first column / row header, but not that much after.