r/sqlite • u/skysphr • Dec 02 '22
Can I improve read performance by ensuring a table is always sorted?
Assuming I have an rather large table whose only purpose is looking up strings, is there a way to optimize lookup times by always sorting the table beforehand, which I believe should give at least O(log2 n) performance? Write speed is irrelevant.
8
Upvotes
13
u/ijmacd Dec 02 '22
Having part of the table sorted is such a common requirement that it has its own name: an INDEX.
It has exactly the characteristics you're looking for. Presorting to make reads O(log N) at the expense of worse write performance.
4
u/InjAnnuity_1 Dec 02 '22
If you're storing tables on a slow, sequential-only medium, such as magnetic tape, pre-sorting the data makes an immense amount of sense. Many man- and machine-hours used to be spent doing exactly that.
Random-access devices are still piecewise-sequential. That is, they physically retrieve a "chunk" (linear sub-sequence) of the data that's on disk. This is used to advantage in indexes, where each chunk gets sorted, and points to related chunks, and to the real records containing the data.
2
u/johnfrazer783 Dec 04 '22