This condition in principle does not appear to be right, because removing it gives in the same.
However, when Where conditions are generated dynamically, and the programmer adds them with AND
inside if
s, because these depend on other factors of the program that generates SQL, it is clear its intention:
If there is no additional condition, the query remains so ...
SELECT * FROM Destinatario where 1 = 1
... but in the case, if the condition is true right after your example, it can stay:
SELECT * FROM Destinatario where 1 = 1 AND Nome = "Roberto"
Note that if there was no WHERE 1=1
, it would stay that way, and it wouldn’t work:
SELECT * FROM Destinatario AND Nome = "Roberto"
-- temos um erro aqui --^
For one condition AND
only, the author could have put the WHERE
within the condition, but if there are various conditions, the WHERE 1=1
would allow several separate conditions, mounted by if
s different:
SELECT * FROM Destinatario where 1 = 1
SELECT * FROM Destinatario where 1 = 1 AND Nome = "Roberto"
SELECT * FROM Destinatario where 1 = 1 AND Cidade = "Santos"
SELECT * FROM Destinatario where 1 = 1 AND Nome = "Roberto" AND Cidade = "Santos"
Thus the AND Nome
could be in a if
and the AND Cidade
in another, and all would function independently of having to know if there is already a if
previous in the code generating the SQL.
As mentioned by @bfavaretto, Cakephp, for example, uses this technique.
In particular, I find it better to use cleaner ways than how it was used, such as concatenating with AND
only when it comes to the second condition onwards, but each has its own criteria, and at each moment a particular technique may be better than another.
Leaving this specific example of use, it may even happen that someone uses a WHERE
"neutral" when you want to test some condition during code development, eliminating the original condition (equivalent to putting WHERE true
, which would also serve for the initial explanation), but this is already another story.
In our specific case, the IF
this row confirms the initial hypothesis of the optional parameter with AND
:
IF(@param IS NOT NULL) -- <== Aqui
SET @sql = (@sql + ' AND Nome = ''' + @param + '''');
Related: http://desciclopedia.org/wiki/Gambi_Design_Patterns#AND_0.3D0
– Victor Stafusa
In some conditions I use confessed.
– Motta
Be careful with this technique because when you use it.. if you see nothing in others
ands
the database will fetch all the existing records in the table. That is if you have 10million records and have no other filters it will fetch everything..– Valdeilton de Souza