I have a SQL (MSSQL) table storing data like the following, with id
as primary key.
id | col1 | col2 | col3 | data | valid |
---|---|---|---|---|---|
1 | A | B | C | 1 | |
2 | A | B | C | 0 | |
10 | X | Y | Z | 1 | |
15 | X | Y | Z | 0 | |
75 | A | B | C | 1 | |
99 | X | Y | Z | 1 | |
The kind of retrieval that the application needs is a 3-step process.
First, get all the
id
s wherecol1
,col2
,col3
are of some value, andvalid
is1
, similar to this:select id from table where col1 = 'A' and col2 = 'B' and col3 = 'C' and valid = 1;
Then, from the list of
id
s, select a singleid
based on some computation.Given a single
id
from step #2, retrieve thedata
.
Question
How to speed up the process of looking up all the id
s in step #1? Because at some point, the table will grow to 10 millions+ and looking up would be slow.
One way is to create index in MSSQL on col1
, col2
, col3
, and valid
columns, so that the query would be fast. But I believe it would still be ~ O(logN).
Another solution I can think of is to have a background process to create a key-value database alongside the SQL table. This background process would build something like this:
key | value |
---|---|
A:B:C | 1, 75, ... |
X:Y:Z | 10, 99, ... |
The reason why I want to create a key-value index alongside SQL table is because the number of valid records could be relatively very small (~100) compared to the whole size of the table (~10M+). So we wouldn't have to search/scan through the invalid records. And with key-value, the lookup, and therefore the step #1, would be O(1).
I was just wondering if this is common, or there is other database technology that supports this better.
Edit
- Sorry, I oversimplified the question and it could affect the answer. The
valid
column doesn't actually exist in the original SQL table; it is computed at runtime and stored in another table. @Akina 's reply in the comment regarding the partition on thevalid
column (soft delete?) should still help though.
CREATE INDEX idx ON table (valid, col1, col2, col3)
. Moreover, you may partition your table byvalid
(i.e.CREATE PARTITION FUNCTION pfn (INT) AS RANGE LEFT FOR VALUES (0); GO; CREATE PARTITION SCHEME psc AS PARTITION pfn TO (invalid, valid);
) which will made the rows selection O(1) because of the partition pruning.valid
column doesn't actually exist in the original SQL table; it is computed at runtime and stored in another table (id, valid
). But I could try to havevalid
column in the same table as well, which in that case, your suggestion regarding the partition is very interesting.valid
column is not part of the original SQL table, do you see other options other than creating a key-value index alongside?