I ran into a unexpected postgres query issue within my Rails3 app.
I thought I'd run this by stackoverflow and see what the brains of the internet have to say :)
Is this result Expected behaviour (and why?!) or is this a bug?
Given that I have a table, Orders, in my Postgres 9.1.4 database:
id state
===== ======
1 <-- nil (default value)
2 'success'
3 'failure'
When I run the query:
Order.where('orders.state != ?', 'success').map { |order| order.id }
Order Load (3.8ms) SELECT "orders".* FROM "orders" WHERE (orders.state != 'success')
=> [3]
I was expecting the result [1, 3]. There are clearly 2 rows in which (!= 'success') is satisfied.
Why is it that nil != 'success' is not true here? Does != just ignore NULL values? should it?
NOTE: I produced the desired result by using the following query:
Order.where('orders.state IS NULL OR orders.state != ?', 'success').map { |order| order.id }
Order Load (2.3ms) SELECT "orders".* FROM "orders" WHERE (orders.state IS NULL OR orders.state != 'success')
=> [1, 3]
Any comments would be appreciated.