Ask A Question


You’re not receiving notifications from this thread.

How do I query a model with a value less than

Stephen Sizer asked in Rails

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.

Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 81,149+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more.

    © 2024 GoRails, LLC. All rights reserved.