Note that there are some explanatory texts on larger screens.

plurals
  1. POSpeeding up SQL query when sorting on foreign keys
    primarykey
    data
    text
    <p>This is more of a generic SQL problem but I'm using Firebird 2.5 if anyone knows of a Firebird/Interbase specific optimization. First, the following is a simplified example schema to illustrate the issue I'm trying to solve:</p> <pre><code>CREATE TABLE users ( id INTEGER PRIMARY KEY, name VARCHAR(16) ); CREATE TABLE data_set ( id INTEGER PRIMARY KEY, name VARCHAR(64) ); CREATE UNIQUE INDEX data_set_name_idx ON data_set(name); CREATE TABLE data ( user_id INTEGER, data_set_id INTEGER, data BLOB, PRIMARY KEY(user_id, data_set_id) ); CREATE INDEX data_user_id_idx ON data(user_id); CREATE INDEX data_data_set_id_idx ON data(data_set_id); </code></pre> <p>The query I'm trying to run is as follows:</p> <pre><code>SELECT users.name, data_set.name, data FROM users, data_set, data WHERE user_id=XXX AND user_id=users.id AND data_set_id=data_set.id ORDER BY data_set.name; </code></pre> <p>With 'XXX' being filled in with the <em>user_id</em> I want. So what I'm doing is selecting all the rows from the <em>data</em> table that are owned by a particular user and I'm sorting the results based on the <em>data_set</em> name.</p> <p>This works as it is but the problem is the <em>data</em> table has over a billion rows in it and the <em>data_set</em> table is not small either. The result set for a single user id may be many hundreds of millions of rows. What happens is that in order for the ORDER BY to work the database has to create a massive amount of temporary data which is incredibly slow and uses a lot of disk space. Without the ORDER BY it's fast but obviously not sorted like I need.</p> <p>One solution would be to take the <em>data_set.name</em> values and just put them in a varchar column in <em>data</em>. Then that could be indexed and would be quick to sort. The problem with this approach is that it will have a lot of duplicate data and make the database absolutely massive.</p> <p>Another solution would be something like an Indexed View or an indexed Computed Column. As far as I know neither of those is supported by Firebird.</p> <p>Any other ideas?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload