PostgreSQL

SQL Where 1=1

If you have worked with SQL databases before, you might have come across the statement WHERE 1=1. It is a common statement that is used to return all the records from a given table.

The statement where 1=1 in SQL means true. It is the same operation as running the select statement without the where clause.

You might ask, what is the purpose of the clause where 1=1?

In most cases, you will only need to use this clause when you need to build dynamic SQL statements. Once you apply the where 1=1 clause, all the subsequent statements after it can start with the ‘and’ keyword.

It is more like a way to include exploratory SQL statements in a much lazy and convenient manner. It also allows you to comment out queries in a simple manner.

Consider an example where you are guessing an id of a column. Assuming you are not sure whether that id exists on the database, you can use something like where 1=1 to return all the rows even if the target id is not on the database.

SELECT * FROM users WHERE id = 10 OR 1=1;

The query above uses an or statement. Hence, only one of the conditions needs to be true for the query to work.

Even if there is no user with an id of 10, the 1=1 will always evaluate to true, and the query will fetch all the rows in the specified table.

Query Execution

If you are not hunting for information on databases, you will rarely need to concern yourself with the where 1=1 clause.

However, you may ask whether the clause improves the execution time.

The answer is No.

Setting the clause where 1=1 is the same as running the query without a where clause. Most database engines will remove the clause before executing the statement.

Conclusion

This short article describes what the SQL where 1=1 clause and why you can use it.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list