Skip to main content

How do I query a model with a value less than

Rails • Asked by Stephen Sizer

I have a Lesson model that has an order field of type integer. What i want to do is find the previous lesson.

Lesson.where("order < ?" , 8)

This causes the following error. Any help would be appreciated.

Lesson Load (1.9ms) SELECT "lessons".* FROM "lessons" WHERE (order < 8) LIMIT $1 [["LIMIT", 11]]
ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR: syntax error at or near "order"
LINE 1: SELECT "lessons".* FROM "lessons" WHERE (order < 8) LIMIT...
^
: SELECT "lessons".* FROM "lessons" WHERE (order < 8) LIMIT $1


If I'm not mistaken, order is a reserved keyword in most DB's, I know it is in PG.

Quick test I got the same result as you, but my foo column returned fine.

Rename your column order to something else, maybe position and then you should be good to go.


@jacob 👍

That would make sense since you use ORDER to sort in SQL.

I guess you could modify the code to be the following to specify the column and clarify it for the db that you're not using the ORDER keyword.

Lesson.where("lessons.order < ?" , 8)

I'd much rather rename the column though.


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 27,623+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.