0

I have two tables, Users and Transactions. In both tables, rows have a timestamp.

I am running into performance issues when running complex queries where the transaction dates are being normalized to reflect at what point of a user experience they happened (i.e. how many days after a user joined was the transaction processed).

This "normalized day" measure is calculated as

ceil(extract(days from T.tdate - U.created_at)) +1

Is there any way to index this such that I can increase the speed of the query?

2 Answers 2

2

There is no way to make such index directly.

You can add another field to the T table, which would store the value of your formula, and you can add an index on that field. You can maintain the value of that field using triggers.

2

No: PostgreSQL doesn't currently allow the creation of an index which references more than one table.

Alternatively you could:

  • Follow maniek's suggestion of using triggers to compute timestamp differences on insert/updates to both of the tables.
  • Use Postgresql 9.3's CREATE MATERIALIZED VIEW which allows you to define the view which takes a snapshot of the view's resultset and stores it as a table. Note that any changes made to the source tables after this snapshot are not automatically included. You can use REFRESH MATERIALIZED VIEW to update this view, just before generating reports for an updated snapshot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.