r/SQL • u/7Seas_ofRyhme • Oct 28 '24
Discussion What does WHERE 1 = 1 means? Purpose?
I've been seeing it alot recently. What are the use cases of it?
82
u/yourteam Oct 28 '24
Allows you to out a where condition with 0 impact.
From there you can add / remove the other conditions without worrying about removing the statement
3
u/AdviceNotAskedFor Oct 28 '24
Where do most people put and and in there where statements? At the beginning of the each line?
3
u/mamarussel2 Oct 28 '24
I put them at the beginning to simplify troubleshooting. Everyone has their own style but this is the most common style I see.
2
u/microcozmchris Oct 29 '24
Same argument as putting
WHERE 1=1on the first line. A bareANDat the end has to be removed if you comment the last line of your conditionals, so it's easy to carelessly make a mistake, especially when adding it back.Both of these cases have been rediscovered by many developers independently over time and we keep coming to the same conclusions.
2
u/cLYRly Oct 28 '24
No. It's usually
WHERE 1=1 AND a.column =b.column AND b.column LIKE '%thing%'
1
u/rmpbklyn Oct 28 '24
they may use to turn off so they later set to something that wont run 1=2 inthat case a variable be better setv @getdetail =1. latervin code …where @getdetail =1, they be trying do a cross apply but only if that was only whete condition
0
u/dasonk Oct 28 '24
I think you need to update your formatting for Reddit
-1
u/cLYRly Oct 28 '24
Le sigh.
0
u/dasonk Oct 28 '24
?
Line breaks matter my guy. Especially when the question is literally about the line breaks
1
u/cLYRly Oct 28 '24
I was on my phone and had just woken up. I assumed the order was sufficient to answer the question. If my code is not to your satisfaction, I encourage you to answer the question (if you haven't already) with the formatting that pleases you most.
1
0
44
u/zarsus Oct 28 '24
It's for the possibility to easily comment out comparisations. And if you are dynamically generating the sql then it will work even when all the clauses are not populated or commented out. ex:
select foo from bar where 1 = 1--and foo = 1and foobar = 'abc'and bar = 'xyz'and anotherfoo = 4
11
Oct 28 '24
The other comments have it but a tiny note if you’re using SQL server, WHERE 1 = (SELECT 1) prevents trivial plans for simple queries.
1
8
u/Steve_P1 Oct 28 '24
I use 2=2 just to be a bit different.
7
u/nachos_nachas Oct 28 '24
(CASE 2 WHEN 2 THEN 2 END) = (CASE 2 WHEN 2 THEN 2 END)3
u/SQLDave Oct 28 '24
(CASE 3 WHEN 3 THEN 3 END) - 1 = (CASE 1 WHEN 1 THEN 1 END) + 1
2
1
7
u/SportTawk Oct 28 '24
I use a web front end to build up a SQL query from a series of drop down list selections.
So using where 1=1 means I can just use a series of AND statements to this query.
1
6
u/phesago Oct 28 '24
I guess Im not surprised that no one has mentioned that its used to force different plans to be cached in dynamically generated SQL. Erik Darling has a good video where is show cases this, where he uses WHERE 1=1, WHERE 2=2, and WHERE 3=3 in different scenarios so those get cached independently because they have separate WHERE clauses.
6
u/ravan363 Oct 28 '24
It's dummy value and used to comment out the filters in the where clause. I adopted leading commas and this dummy value.. Its so much easier to comment out and debug.
4
6
8
u/orz-_-orz Oct 28 '24
Other than easy for commenting, it's also easier to program a script to generate SQL code dynamically using WHERE 1=1, for example you don't have to code "if it's first key then print WHERE x=2 else print AND x=2".
1
3
3
u/mike-manley Oct 28 '24
For SQL Server I probably overuse WHERE 1 = 1. For other DBMS, I use WHERE TRUE.
3
u/fleetmack Oct 28 '24
i do this in literally every sql block i like. makes it easier to comment out any AND statement for testing.
2
Oct 28 '24
It helps to comment out the conditions without deleting the actual statement from the query
2
u/dudeman618 Oct 28 '24
I use 1=1 all the time because I'm doing research and testing, because I am constantly changing my where clause for texting. Also, if you're writing a program and building the where clause dynamically all you have to do is tack on the next AND clause. Rarely I will want to negate my SQL or subquery, I change it to 1=0.
2
u/Professional_Shoe392 Oct 28 '24
Also, you can use WHERE 1=2 if you need the table structure minus the indexes and constraints.
2
u/wknight8111 Oct 28 '24
I've used it in applications before. Depending on the user's security permissions and log-in state, I may append "WHERE 1 = 1" (the user can access) or "WHERE 1 = 0" (the user can't access). In the later case everything else in the application seems to work correctly with the same flows, but the search results come back empty, and all the ID lookups return NotFound.
2
u/Cool-Personality-454 Oct 28 '24
It lets you comment out lines beginning with AND in the WHERE clause. Useful for debugging and troubleshooting
SELECT * FROM products WHERE 1 = 1 --AND color = 'blue' AND size = 'medium'
2
u/Afraid-Expression366 Oct 29 '24
When you need a condition hard coded to true “1 = 1” does the trick.
Conversely if you want to create a table that is identical in structure to another but want it to be empty you could do:
CREATE TABLE x AS SELECT * FROM y WHERE 1 = 0;
2
2
3
u/SpetsnazCyclist Oct 28 '24
you can also just write true as well, which is 1 more character and much easier to understand. IMO this should not be in production code.
1
1
u/Krassix Oct 28 '24
Some sql server implementations (I know it from informix) drop a warning when you run an update or delete without a where clause. With this where clause you get around this issue.
1
u/gregorydgraham Oct 28 '24
Aside from all the other explanations WHERE 1=1 makes generating dynamic SQL easier.
If you start with WHERE 1=1 your following all start with AND, and zero conditions queries are not a special case so the logic is a lot simpler.
1
u/JacksterJA Oct 28 '24
Also, if you’re using a ‘qualify’ you need either an alias (table = alias) or a predicate (where x=y). I personally use a ‘where true’ but same same.
1
1
u/Psychological_Ad8426 Oct 28 '24
In a case statement you might have some thing like this Where Case when color = blue then 1 When color = red and type = truck then 0 When color = red then 1 End = 1
This would give you all the red and blues unless it was a red truck. If you changed it to end = 0 it would red trucks. Over simplified but basic use.
1
u/Outside-Childhood-20 Oct 29 '24
where 1 also works in many dbs. Ultimately, the query engine will simply return all rows where all conditions evaluate to true. Most engines should interpret 1 as true.
1
Oct 29 '24
Sometimes you’ll see that with dynamic sql when the dev who designed it didn’t need a condition and found that easier to write. It’s a placeholder that isn’t getting used.
I tend not to leave that kind of crap behind in the code (non-dynamically built) but I will use it while troubleshooting sometimes
1
u/JankyPete Oct 30 '24
It's for adding and commenting our "and" clauses on queries. Every additional "and" clause is easier to add
1
u/Bunkerman91 Jan 03 '25
Oh my god I’m not alone. The guy I learned sql from taught me that trick and I swear I’ve never seen anyone else do it in the wild. My coworkers all know my handwriting by it.
Like some forgotten ninja scroll passed down.
0
-6
u/torstengrust Oct 28 '24
This means that the engineers developing that particular SQL engine have been too lazy to implement a proper Boolean type and its literal values true and false.
0
Oct 28 '24
[deleted]
53
u/BeeAnalyst Oct 28 '24
Off topic but this link is great and I'll be sharing with junior members of my team.
49
u/bliffer Oct 28 '24
I adopted the leading comma years ago and now queries with trailing commas drive me fucking batty.
12
u/littlelowcougar Oct 28 '24
I hate the aesthetics but appreciate the functionality. If only SQL allowed trailing commas on the last element.
7
u/konwiddak Oct 28 '24
Some databases do allow this now.
3
u/ryadical Oct 28 '24
The tips were written for snowflake which allows an extra comma at the end of select, but not group/order by.
1
1
u/BobBarkerIsTheKey Oct 30 '24
Is the aesthetic problem with the first column in the select being slightly out of vertical alignment with subsequent columns?
2
u/littlelowcougar Oct 30 '24
The aesthetic problem is that in ~27+ years of looking at any form of code, you rarely see commas first in lists, and thus, my brain hates it.
2
u/BobBarkerIsTheKey Oct 30 '24
Ah ok. The first column being off by a single character always bothers be with comma-first. So I add an extra space to make them line up. lol
2
u/Expensive-Sherbet596 Oct 29 '24
Ive been doing that for a few years now. It drives me crazy when I see code with trailing commas now lol. I did manage to get others on my team to do the leading comma.
8
u/Contingency_Plans Oct 28 '24
Ugg. I hate leading commas. They destroy readability, which is more important to me than easily commenting out lines during query development.
12
u/ipwnall123 Oct 28 '24
Lol I appreciate the sentiment that they are a little ugly, but I got a chuckle at the pure drama of “they destroy readability”
2
2
21
u/bobertskey Oct 28 '24
also off topic: snowflake now allows for trailing commas before the FROM statement so we swapped our leading comma preference for trailing commas. Nice little QOL upgrade.
8
4
u/konwiddak Oct 28 '24
Also great QOL features when you're interrogating data:
Dynamic pivots, makes new columns based on the available values (or you can use a subquery into the columns part of the pivot).
Select * excluding.... Allows you to select all columns except for the ones you don't want.
4
3
u/AdviceNotAskedFor Oct 28 '24
I know I can Google this, but what is snowflake? I'm seeing it mentioned all the time and I'm just curious
10
u/soulstrikerr Oct 28 '24
A data warehouse. You can store tabular data and query the data using SQL.
3
u/AdviceNotAskedFor Oct 28 '24
What makes it unique? And why is everyone talking about it recent?
4
u/EarthGoddessDude Oct 28 '24
It’s one of the most popular cloud data warehousing solutions out there. It abstracts a lot of the mundane aspects of managing a database and separate storage and compute so it’s quite popular.
-7
u/AdviceNotAskedFor Oct 28 '24
Ahh gotcha. Cloud.
Ick.
4
u/konwiddak Oct 28 '24
I'm a champion of stay on-prem unless you're getting tangible advantages from cloud. Snowflake is an example where cloud really does deliver tangible advantages for big businesses. It saves a huge amount of IT and administration overhead and allows you to get stuff done without many barriers or red tape. It's probably never optimal, but it's almost always good.
1
9
Oct 28 '24
[removed] — view removed comment
2
u/duraznos Oct 28 '24
They've convinced people that if they arent separating storage from compute they're doing it wrong, ignoring the fact that most people's data sets could probably fit in memory on a sizeable enough server.
I remember meeting with their sales team about six months before they went public and telling them they'd have to speed up our ETL jobs 5x for us to even break even over using on-demand redshift dc2's and that was at their cheapest compute credits
2
Oct 29 '24
[removed] — view removed comment
2
u/duraznos Oct 29 '24
We knew how to efficiently operate on that data so only the subset that mattered needed to be loaded in Memory at a given time.
Inject this right into my veins. Query optimization and database design are such dying arts with all the various ways to just throw money at a problem. There's so much performance to be squeezed out of a SQL db if you just take the time.
1
1
2
2
u/I_Am_Astraeus Oct 28 '24
I cannot believe the leading comma idea has been there all along.
This was an instant as soon as I saw it I immediately was like oh that's leagues better for dynamic querying. Love this.
2
2
u/Mononon Oct 28 '24
Shout-out to how "NOT IN" interacts with NULLs. I've been doing SQL for years, and that one just got me like last week. Completely slipped my mind.
2
2
u/ReallyNotTheJoker Oct 29 '24
That is not a use for that that I've thought of but I kinda like it. I usually just manipulate my WHERE when I do test cases but I like this.
2
u/Joseph___O Oct 29 '24
We use positional arguments for group by in production all the time I don’t see any issue.
In fact I think it is better because when we auto format the code it will be on one line but if I wrote every column it might add another 30 lines to the query.
96
u/yen223 Oct 28 '24
It's just for convenience when writing exploratory SQL
If I wanted to ignore the
user_idcondition, I can't just comment out the WHERE line because that will kill the where clause.So instead people write something like
and they can just comment out the
AND user_id = 10line.