how to lookup last record in dataset in Mnesia?

hans.bolinder@REDACTED hans.bolinder@REDACTED
Wed Jun 7 15:29:06 CEST 2006

[Gaspar Chilingarov:]
> I have a table in Mnesia, which I with to filter by some field(s) and
> fetch one record with maximal ID (ie. last inserted).
> (SQL equivalent: SELECT MAX(ID) FROM table WHERE foo_field = 'bar' and
> user_name = 'Alice')
> Are there any fast ways to achieve this in mnesia?

    QH = qlc:q([ || 
                     R <- mnesia:table(T),
                     R#foo.foo_field =:= bar, 
                     R#foo.user_name =:= 'Alice']),
    lists:max([0 | qlc:e(QH)]) % assumption: 'id' is an integer > 0

If 'foo_field' or 'user_name' is the key column, or either of them is
indexed, the query is just a lookup. Otherwise the whole table will be
traversed, possibly using select and a match specification.

Best regards,

Hans Bolinder, Erlang/OTP

More information about the erlang-questions mailing list