[erlang-questions] Reading the first or last N records from a secondary index in mnesia

Igor Ribeiro Sucupira <>
Wed Jan 13 16:18:34 CET 2010

Hi, Sam.

I believe secondary indices are bags, so they are not stored in a way
that provides efficient sorted iteration.

If you really need that functionality, you can implement your own
index, using another ordered_set table.

Best regards.

On Wed, Jan 13, 2010 at 4:25 AM, Sam Bobroff <> wrote:
> Hi everyone,
> I've been trying, unsuccessfully, to work out how to read either the
> first, (or last) few keys from an mnesia table's secondary index in a
> reasonably efficient manner.
> (If I want to read records from a primary index I can make the table
> ordered_set and use first(), last() and next() or prev().)
> All I can come up with is something like this:
> Q = qlc:cursor( qlc:sort( qlc:q( [ R || R <- mnesia:table(blah) ] ),
> [{order, fun compare_secondary_index/2}] ) )
> qlc:next_answers(QC, N).
> But it seems to cause the entire table to be read and sorted before any
> records are returned. It doesn't seem to use the secondary index at all.
> Have I missed some obvious way to do this?
> Is it possible to iterate over the secondary index?
> Cheers,
> Sam.
> --
> Sam Bobroff |  | M5 Networks
> Why does my email have those funny headers? Because I use PGP to sign
> my email (and you should too!): that's how you know it's really from me.
> See: http://en.wikipedia.org/wiki/Pretty_Good_Privacy

"The secret of joy in work is contained in one word - excellence. To
know how to do something well is to enjoy it." - Pearl S. Buck.

More information about the erlang-questions mailing list