Weird error when order by 'when'

In my appointments model, I want to order by a column called “when”,
which is supposed to house the appointment date.

So im my model file appointment.rb I did this…

class Appointment < ActiveRecord::Base
default_scope :order => ‘when’
[…]
end

and I got this error…

SQLite3::SQLException: near “when”: syntax error: SELECT
“appointments”.* FROM “appointments” ORDER BY when


So then I used ticks…

class Appointment < ActiveRecord::Base
default_scope :order => ‘when
[…]
end

and it worked. I have something similar with my client.rb file, didn’t
used ticks and never had any problem.

class Client < ActiveRecord::Base

Order clients alphabetically

default_scope :order => ‘name’
[…]
end

Is there a reason for this error? is “when” a reserved keyword? I
googled “sqlite3 when” and didn’t find anything. Sorry if my question
may seem irrelevant, it’s just that I want to UNDERSTAND Rails.

On Oct 7, 2010, at 10:23 AM, Leonel - wrote:

and I got this error…
[…]

Is there a reason for this error? is “when” a reserved keyword? I
googled “sqlite3 when” and didn’t find anything. Sorry if my question
may seem irrelevant, it’s just that I want to UNDERSTAND Rails.

Yes. Google for “sqlite reserved words”…

http://www.sqlite.org/lang_keywords.html

I believe I ran into something similar once some time ago. I think
that if you enclose the column name with quotes it might take it.

pepe wrote:

I believe I ran into something similar once some time ago. I think
that if you enclose the column name with quotes it might take it.

Well, actually, it has to be enclosed with ticks and then with single or
double quotes, like this…

default_scope :order => ‘when

or

default_scope :order => “when

Actually, it’s a better idea to use quote_column_name instead of literal
quotes. This way, changing databases won’t break your code (MySQL and
SQLite use `` identifier quoting, PostgreSQL uses “” or nothing, MS SQL
uses [], but the quote_column_name method abstracts them all).

I didn’t know about that one. Thanks Marnen.

Leonel . wrote:

pepe wrote:

I believe I ran into something similar once some time ago. I think
that if you enclose the column name with quotes it might take it.

Well, actually, it has to be enclosed with ticks and then with single or
double quotes, like this…

default_scope :order => ‘when

or

default_scope :order => “when

Actually, it’s a better idea to use quote_column_name instead of literal
quotes. This way, changing databases won’t break your code (MySQL and
SQLite use `` identifier quoting, PostgreSQL uses “” or nothing, MS SQL
uses [], but the quote_column_name method abstracts them all).

Best,

Marnen Laibow-Koser
http://www.marnen.org
[email protected]