-5

I have a doubt about SQL. Sometimes is necessary to have some sort of ifs in queries, however, there are no ifs in SQL right? So it seems that we should handle these cases with logic operators but I'm not understanding properly how this works, how these logic operators can be used as ifs. Do you know how that works?

closed as unclear what you're asking by mustaccio, Philᵀᴹ, Vérace, Marcello Miorelli, Marco Apr 21 at 18:19

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • give a specific example of what you are trying to do – Martin Smith Apr 18 at 22:55
  • For example, a condition where is necessary to return only the records where the User.Id is stored in a specific variable (using the in operator, for example, where User.Id in $Users) or return all records if that variable doesn't have any UserId. – user11096156 Apr 18 at 23:08
  • Which RDBMS are you actually using? MySql or SQL server? – Martin Smith Apr 19 at 13:09
  • MySQL has the IF(bool, val, val) function, CASE ..., IF-THEN in Stored Routines, and perhaps more. – Rick James Apr 27 at 2:25
0

Consider SQL Server's CASE statement.

If you're trying to say:

if x=3 then I want this, else I want that

...then you could say:

SELECT CASE x WHEN 3 THEN this ELSE that END

See https://docs.microsoft.com/en-us/sql/t-sql/language-elements/case-transact-sql?view=sql-server-2017

0

Microsoft SQL Server supports various imperative constructs, you can wrap statements around logical conditions using IF/ELSE. For instance, you can use the following lines to only execute code on a specific server:

IF @@SERVERNAME = 'ProductionServer'
   BEGIN
      PRINT 'ProductionServer'
   END
ELSE
   BEGIN
      PRINT 'Please login to the Production Server.'
   END

You can also use logical functions such as CHOOSE or IIF (Shorthand for CASE).

https://docs.microsoft.com/en-us/sql/t-sql/functions/logical-functions-choose-transact-sql?view=sql-server-2017

https://docs.microsoft.com/en-us/sql/t-sql/functions/logical-functions-iif-transact-sql?view=sql-server-2017

Not the answer you're looking for? Browse other questions tagged or ask your own question.