How does Model.where('false') work? I am not sure, what above query is actually doing

Viewed 132

I can see query is running something like:

select * from <table_name> where (false);

But my question is:

In where (false), what is false? Is this talking about entire record to be false, because there is no sense of any table column here? If yes, then what is meaning of a record, to be false or true?

Does above query consider some column to get data from the table related to Model?

2 Answers

I am taking Model as User

User.where(false) will generate query as select users.* from users So this returns all records OR LIMIT 11 that is limited records as per default limit.

As mentioned in question 'false' is a string. User.where('false') will generate query as select users.* from users where (false) So this returns no records as the criteria is not met.


Just additional information on what will happen if we use true instead of false User.where(true) will fail with ArgumentError (Unsupported argument type: true (TrueClass))

Using 'true' as a string. User.where('true') will generate query as select users.* from users where (true) So this returns all records OR LIMIT 11 that is limited records as per default limit. It works same as User.where(false)

Note: Above results as from Rails 5.2.3 console

In a SQL (relational) database, the conditions in the where clause are known as "predicates".

They are boolean statements which are evaluated for the relevant tables and column values.

So a row will be returned if the predicate value > 100 is true, for example, or the statement value in (select number from other_table) is true.

It's not uncommon to see queries that contain predicates such as 1 = 0 or 1 = 1 included, which are basically the same as what you're seeing - predictaes that are false or true.

A predicate like that is a constant regardless of the row values of course, and a clever query optimiser will notice that and for false will short-circuit the optimisation to return no rows.

This syntax is probably not going to work in all RDBMSs though, but ActiveRecord might generate different code for a different database.

Related