Why use WHERE 1=1 in SQL Queries

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

The WHERE 1=1 condition means WHERE TRUE. It returns the same query result as it would without the WHERE Clause. There is no impact on query execution time.

This is something you can add to a SQL query for convenience for adding & replacing conditions on the statement. If you have WHERE 1=1 on a SQL query you are writing, all conditions thereafter will contain AND, so it’s easier when commenting out conditions on exploratory SQL queries.

Example: WHERE 1 Equals 1

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

You can see this would be easier for commenting out WHERE conditions in the SQL ^

Example (Extra): Commenting Columns

This is similar to another SQL querying technique where you have commas before column names, rather than after the column name.

Again, this might work out well for you when commenting out columns on a work-in-progress SQL query.

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

Personally, I often make use of both of the above techniques when I write SQL queries.

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, choose what you are most optimal with.

If you wonder what would happen if we change the WHERE 1=1 to WHERE 1=2, have a look at my other blog post: Why Use WHERE 1=2 in SQL


Comments

One response to “Why use WHERE 1=1 in SQL Queries”

  1. Quintin White Avatar
    Quintin White

    Great thank you for the tip !

Recent Posts
Categories
Tags

Always On Availability Groups (AAG) (4) AWS (4) AWS Redshift (6) Database Admin (72) Database Backups & Recovery (14) Database Mirroring (2) Error Messages (5) Failover Cluster Instances (FCI) (1) Git Commands (6) Importing & Exporting Data (2) Linked Servers (3) Linux Administration (2) Logging & Monitoring (1) Microsoft Patching (2) MySQL (4) Postgres (6) PowerShell Scripts (2) SQL Certificates & Encryption (3) SQL Server Agent (5) SQL Server CDC (2) SQL Server Data Types (2) SQL Server Management Studio (SSMS) (16) SQL Server Networking (3) SQL Server on Linux (1) SQL Server Patching (2) SQL Server Performance Tuning (6) SQL Server Processes (SPIDs) (7) SQL Server Replication (2) SQL Server Scripts (13) SQL Server Security (4) SQL Server Storage (10) Windows Admin (21) Windows Authentication (2) Windows Automation (1) Windows Events (2) Windows Firewall (4) Windows Subsystem for Linux (WSL) (18)