What is “where(query, false)”? | Elixir / Phoenix

Photo by Ambitious Creative Co. — Rick Barrett on Unsplash

Are you a good friend for SQL? Please say YES! I will tell you something about Ecto, but the essence of this post is SQL. I guess you love the “where” statement to select data with some conditions. On another word, when using “where” means you want to get data by filtered all results.

However, I also do not know why it does exist, the “where” can take “false” as an argument. When it comes, you can not get any results from the database.

Hey!, I want to select some data from the database, That’s why I will do ask the Ecto to fetch data with some conditions I will give! As a result, if there is nothing, I have no choice and I agree.

However, Mr. “Where: false” just give me nothing whatever other conditions exist.

When do we need it or use false as an argument of where?

Yes, I’ve finally happened to meet up.
Let’s (please) imagine that we can see 100 checkboxes, radio buttons and some textboxes as a search UI. Each UI will make one “where” condition for a query to select data like the following.

query
|> where([a, b, c, d, e, f, g, h],e.name == ^criteria)
|> where([a, b, c, d, e, f, g, h],a.flag == true)
|> where([a, b, c, d, e, f, g, h],b.flag == ^criteria)
|> where .....
|> where .....
|> where .....
|> where .....

No problem. That query will work properly for me.
However, each parameter for each “where” is an option so that we do not need to check all buttons and input for all textboxes. This is the design of the system.
So, I usually make a function for each “where” statement like the following.

“where(query, true)” just returns query which is passed to the function _filtered_by_name.

So far, so good?

Then I have finally met one condition that could make all other conditions dead if that specific condition won’t exist just in my case. This is like “Balus” from “Laputa: Castle in the Sky”.

In this above my design case, if param (could be one of the request parameters) does not have the parameter named “flag_b”, the results will be empty. This is my system design.

If that is caused by “flag_b” request parameter, which may be from one UI, We can check if it exists or not like the guard section using “with” statement or something like that.

--

--