What is the fastest way to fetch the last row from a table?

You'll need an index on product_id regardless of solution.

Provided you have an index on the updated_at column, and all you need is to fetch "a specific product" as you stated, then I would do:

select *
from Prices
where product_id = ?
order by updated_at desc 
limit 1

But if I did not get the results I wanted or if I needed to get the current price for many products, then I would try the option of adding a active column, and setting it to N for all prices other than the new one when doing updates of the prices and then I would create a partial index where active as suggested by a_horse_with_no_name. I would go there only if I needed to as it adds a layer of complexity of updating previous price rows to not be active, etc.


Without knowledge of the rest of your database, you can afford a bit of non normal form to speed up products price fetching (assuming there is one price for each item).

Just create a new column named last_priceof type price in your product table and create a trigger AFTER INSERT ON EACH ROWon your price table. Every time a new price is created, it updates the related product with the latest price. This way, every time you fetch a product, you also fetch its last price.

Since version 9.3, PostgreSQL supports materialized views. This is a nice way to denormalize the data, keeping a normal form for writing and denormalized view for reading. The update of the view can be triggered by Postgres’ LISTEN/NOTIFY mechanism.