Menu & Search
Why use WHERE 1=1 in SQL Queries

Why use WHERE 1=1 in SQL Queries

A common SQL question is, why does anyone use WHERE 1=1 in their queries? And what does it do?

The condition means WHERE TRUE, so it’s just bringing back the same query result as it would without. Also, there’s no impact on query execution time.

This is really something you’d add into a query for convenience. When adding in conditions to a query that already has WHERE 1=1, all conditions thereafter will contain AND, so it’s easier when commenting out conditions on exploratory queries.

SELECT *
FROM TABLE
WHERE 1=1
--  and column1='blah'
    and column2='more_blah'
--  and column3 is not null

This is similar to another technique where you’d have commas before column names rather than after. Again, it’s easier for commenting :

SELECT
     Column1
--  ,Column2
    ,Column3
    ,Column4
--  ,Column5
FROM TABLE

Peronsally I make use of both of the above.

Convenience is everything when working behind a computer. We have to keep exploring new short-keys and any general ways of working to optimize our efficiency. Some things you might not like and won’t adopt… and sometimes GUI is better than CLI… it’s all personal preference in the end really!


Share

1 Comment

  1. Avatar
    Quintin White
    2 months ago

    Great thank you for the tip !