By Matthew Rathbone · Updated November 29, 2026

There is no single SQL IF statement that works everywhere. Standard SQL gives you CASE for if/then/else logic inside a query, and each database adds its own shortcuts and procedural IF on top. The quick version:

-- Inside a query: works in every database
SELECT name,
       CASE WHEN stock > 0 THEN 'In stock' ELSE 'Sold out' END AS availability
FROM products;

-- Shortcuts for one true/false test
IF(stock > 0, 'In stock', 'Sold out')    -- MySQL, MariaDB, BigQuery
IIF(stock > 0, 'In stock', 'Sold out')   -- SQL Server, SQLite 3.32+
IFF(stock > 0, 'In stock', 'Sold out')   -- Snowflake

-- Control flow: choose which statements run (SQL Server)
IF @sold_out > 0
    PRINT 'Time to restock';
ELSE
    PRINT 'Everything is in stock';
You want toUse
Show a different value per row ("In stock" / "Sold out")CASE, or IF() / IIF()
Test more than two outcomesCASE WHEN ... WHEN ... ELSE ... END
Count or sum only rows that meet a conditionSUM(CASE WHEN ... THEN 1 ELSE 0 END)
Filter rows "if" something is truePlain WHERE with AND / OR
Run one block of statements or another in a scriptIF ... ELSE (SQL Server), IF ... THEN ... END IF (MySQL procedures), PL/pgSQL (PostgreSQL)
Do something only if a row existsIF EXISTS (SELECT ...), or WHERE EXISTS
Create or drop a table only if neededCREATE TABLE IF NOT EXISTS / DROP TABLE IF EXISTS

Every example below was run on PostgreSQL 16.16, MySQL 8.0.46, SQLite 3.45.1 and SQL Server 2022 (16.0), and the output is copied from those runs.

Jump to: two kinds of IF · sample data · IF in a SELECT · the NULL trap · multiple conditions · IF in WHERE · SQL Server IF...ELSE · MySQL · PostgreSQL · SQLite · IF EXISTS · database table · mistakes · FAQ

The two kinds of IF in SQL

Most confusion about IF in SQL comes from mixing up these two:

Conditional expressionConditional statement (control flow)
What it doesReturns a value, once per rowDecides which SQL statements run
Where it goesInside SELECT, WHERE, ORDER BY, UPDATE ... SETIn a script, stored procedure, function or trigger
Standard SQLCASE WHEN ... THEN ... ELSE ... ENDNot in plain SQL; each database has its own procedural language
ShortcutsIF() (MySQL), IIF() (SQL Server, SQLite), IFF() (Snowflake)IF ... ELSE (T-SQL), IF ... THEN ... END IF (MySQL, PL/pgSQL, PL/SQL)
ExampleSELECT IIF(stock > 0, 'yes', 'no') FROM productsIF @n > 0 PRINT 'restock'

If you are writing a normal query and want a column that says one thing or another, you want an expression, and CASE is the answer that works everywhere. If you want to run an INSERT only when a check passes, you want a statement, and the syntax depends on the database.

Sample data

The examples use a small products table. Note the desk lamp: its stock is NULL, meaning nobody has counted it yet. That row matters later.

CREATE TABLE products (
  id    INT PRIMARY KEY,
  name  VARCHAR(50) NOT NULL,
  price DECIMAL(6,2) NOT NULL,
  stock INT
);

INSERT INTO products (id, name, price, stock) VALUES
  (1, 'Notebook',   4.50, 120),
  (2, 'Pen',        1.20,   0),
  (3, 'Backpack',  39.99,   8),
  (4, 'Desk lamp', 24.00, NULL),
  (5, 'Stapler',    9.75,  35);

IF inside a SELECT: CASE, IF() and IIF()

To label each product as in stock or sold out, any of these three work, depending on your database:

-- Every database
SELECT name, stock,
       CASE WHEN stock > 0 THEN 'In stock' ELSE 'Sold out' END AS availability
FROM products;

-- MySQL / MariaDB
SELECT name, stock, IF(stock > 0, 'In stock', 'Sold out') AS availability
FROM products;

-- SQL Server 2012+ / SQLite 3.32+
SELECT name, stock, IIF(stock > 0, 'In stock', 'Sold out') AS availability
FROM products;

All three return the same rows (MySQL output shown):

+-----------+-------+--------------+
| name      | stock | availability |
+-----------+-------+--------------+
| Notebook  |   120 | In stock     |
| Pen       |     0 | Sold out     |
| Backpack  |     8 | In stock     |
| Desk lamp |  NULL | Sold out     |
| Stapler   |    35 | In stock     |
+-----------+-------+--------------+

IF(condition, value_if_true, value_if_false) and IIF(condition, value_if_true, value_if_false) take the same three arguments in the same order, like IF in a spreadsheet. They are shorthand for a two-branch CASE. SQL Server says so itself: its error messages for IIF talk about "CASE specification", because it rewrites IIF into CASE before running it.

Use the wrong function for your database and you get an error rather than a result:

You runOnError
IF(stock > 0, 'a', 'b')PostgreSQLfunction if(boolean, unknown, unknown) does not exist
IF(stock > 0, 'a', 'b')SQL ServerIncorrect syntax near the keyword 'IF'.
IF(stock > 0, 'a', 'b')SQLite 3.45no such function: IF (works from 3.48)
IIF(stock > 0, 'a', 'b')MySQLFUNCTION shop.IIF does not exist
IIF(stock > 0, 'a', 'b')PostgreSQLfunction iif(boolean, unknown, unknown) does not exist

PostgreSQL has neither function, so CASE is the only option there. If your query has to run on more than one database, use CASE and stop worrying about it.

You can try this right now in the free SQL Easy CASE lesson, which runs a real database in your browser:

The SQL Easy CASE lesson running SELECT name, species, height_cm, CASE WHEN height_cm >= 100 THEN 'tall' ELSE 'short' END AS size FROM friends_of_pickles, returning tall for the two humans and short for the cats and dogs
If/else with CASE in the CASE lesson. The in-browser engine is an older SQLite build, so IIF() returns "no such function: IIF" there; CASE works everywhere.

The NULL trap: "unknown" goes to ELSE

Look at the desk lamp in the output above. Its stock is NULL (unknown), yet every version labelled it Sold out. That's wrong: we don't know it's sold out, we just haven't counted.

The reason is how SQL handles NULL. NULL > 0 is not true and not false; it's unknown. IF(), IIF() and CASE only take the "true" branch when the condition is true, so unknown falls through to the else value. The same happens with the condition alone:

-- MySQL
SELECT IF(NULL, 'yes', 'no');            -- no

-- SQL Server
SELECT IIF(NULL > 1, 'yes', 'no');       -- no

The fix is to test for NULL first, with IS NULL (never = NULL, which is also unknown):

SELECT name, stock,
       CASE
         WHEN stock IS NULL THEN 'Unknown'
         WHEN stock > 0     THEN 'In stock'
         ELSE 'Sold out'
       END AS availability
FROM products;
   name    | stock | availability
-----------+-------+--------------
 Notebook  |   120 | In stock
 Pen       |     0 | Sold out
 Backpack  |     8 | In stock
 Desk lamp |       | Unknown
 Stapler   |    35 | In stock

Flipping the condition does not save you either. In SQL Server, IF @stock > 0 ... ELSE ... and IF NOT (@stock > 0) ... ELSE ... both take the ELSE branch when @stock is NULL, because NOT unknown is still unknown. We ran both: each printed its ELSE message. If a column can be NULL, handle it explicitly. COALESCE is the other common fix: IIF(COALESCE(stock, 0) > 0, ...) treats unknown as zero, if that's what you mean. More background in NULL values in SQL.

Multiple conditions: IF / ELSE IF inside a query

For three or more outcomes you can nest IF() calls, but it gets hard to read fast:

-- MySQL: nested IF()
SELECT name, stock,
       IF(stock IS NULL, 'Unknown', IF(stock > 0, 'In stock', 'Sold out')) AS availability
FROM products;

A CASE with several WHEN branches is the SQL version of if / else if / else, and it reads top to bottom. The first true branch wins, so put the most specific tests first:

SELECT name, stock,
       CASE
         WHEN stock IS NULL THEN 'Unknown'
         WHEN stock = 0     THEN 'Sold out'
         WHEN stock < 10    THEN 'Low stock'
         ELSE 'In stock'
       END AS status
FROM products;
   name    | stock |  status
-----------+-------+-----------
 Notebook  |   120 | In stock
 Pen       |     0 | Sold out
 Backpack  |     8 | Low stock
 Desk lamp |       | Unknown
 Stapler   |    35 | In stock

Combine tests inside one branch with AND, OR and IN: WHEN stock < 10 AND price > 20 THEN 'Reorder soon'. The CASE guide covers multiple conditions and branch order in depth.

SQL Server has a hard limit here. Because IIF becomes CASE, nesting more than ten deep fails with Case expressions may only be nested to level 10. We hit it with eleven nested IIF calls. A flat CASE with many WHEN branches has no such problem.

Keep both results the same type

What happens if the true and false values are different types, like a number and a word?

SELECT name, IIF(stock > 0, stock, 'none') AS s FROM products;
  • MySQL (IF()) and SQLite run it and return 120, none, 8, none, 35. In MySQL the whole column becomes text.
  • SQL Server returns the first row and then fails with Conversion failed when converting the varchar value 'none' to data type int., because it decided the column was an integer.
  • PostgreSQL (with CASE) refuses to run it at all: invalid input syntax for type integer: "none".

Make both results the same type, using CAST if needed: IIF(stock > 0, CAST(stock AS VARCHAR(10)), 'none').

Counting and summing with IF

Put the condition inside an aggregate to count or total only some rows. This is how you get several counts from one pass over the table:

-- MySQL
SELECT COUNT(IF(stock = 0, 1, NULL)) AS sold_out,
       SUM(IF(stock > 0, 1, 0))      AS in_stock
FROM products;

-- SQL Server / SQLite
SELECT COUNT(IIF(stock = 0, 1, NULL)) AS sold_out,
       SUM(IIF(stock > 0, 1, 0))      AS in_stock
FROM products;

-- Every database
SELECT COUNT(CASE WHEN stock = 0 THEN 1 END)     AS sold_out,
       SUM(CASE WHEN stock > 0 THEN 1 ELSE 0 END) AS in_stock
FROM products;
sold_out | in_stock
---------+---------
       1 |        3

Pen is the only sold-out product, and the desk lamp is counted in neither column (the NULL trap again). COUNT counts every non-NULL value, so the false branch must be NULL, not 0; SUM wants 1 and 0. PostgreSQL and SQLite also accept COUNT(*) FILTER (WHERE stock = 0). Add GROUP BY to get these counts per category, or turn them into columns with a pivot.

IF in a WHERE clause

People often search for "if in where clause" when they want a filter that changes depending on some value. You rarely need IF for that; ordinary boolean logic does it:

-- "If the product is expensive, only show it when stock is low;
--  otherwise show it when it's sold out"
SELECT name, price, stock
FROM products
WHERE (price >= 20 AND stock < 10)
   OR (price < 20  AND stock = 0);
   name   | price | stock
----------+-------+-------
 Pen      |  1.20 |     0
 Backpack | 39.99 |     8

A conditional expression can still go in WHERE as long as you compare its result to something. SQL Server and SQLite both run WHERE IIF(stock > 0, 1, 0) = 1 (returning Notebook, Backpack and Stapler). Leave off the = 1 and SQL Server fails with An expression of non-boolean type specified in a context where a condition is expected, because IIF returns a value, not a true/false condition. The AND/OR version is clearer and lets the database use indexes. See AND and OR in SQL and the CASE in WHERE section.

IF in an UPDATE

A conditional expression in SET changes each row differently in a single statement. To take 10% off products with more than 100 in stock and leave the rest alone:

-- MySQL
UPDATE products SET price = IF(stock > 100, price * 0.9, price);

-- Every database
UPDATE products
SET price = CASE WHEN stock > 100 THEN price * 0.9 ELSE price END;
+----+-----------+-------+
| id | name      | price |
+----+-----------+-------+
|  1 | Notebook  |  4.05 |
|  2 | Pen       |  1.20 |
|  3 | Backpack  | 39.99 |
|  4 | Desk lamp | 24.00 |
|  5 | Stapler   |  9.75 |
+----+-----------+-------+

Only the notebook changed. Don't forget the "else keep the old value" part: a CASE without ELSE price sets every other row's price to NULL. Adding WHERE stock > 100 is often simpler still. More in the UPDATE guide.

SQL Server IF...ELSE (T-SQL)

SQL Server's Transact-SQL has a real IF ... ELSE statement that you can use in any batch, script, stored procedure or trigger. It runs one statement or block when the condition is true and, optionally, another when it isn't.

IF condition
    statement_or_block
[ ELSE
    statement_or_block ]

There is no THEN and no END IF. A typical use is to check something with a query and react to it:

DECLARE @sold_out INT = (SELECT COUNT(*) FROM products WHERE stock = 0);

IF @sold_out > 0
    PRINT CONCAT(@sold_out, ' product(s) need restocking');
ELSE
    PRINT 'Everything is in stock';
1 product(s) need restocking

Use BEGIN...END for more than one statement

This is the classic T-SQL bug. Without BEGIN ... END, IF controls only the next statement, no matter how you indent:

IF 1 = 0
    PRINT 'Restock order created';
    PRINT 'Email sent to supplier';   -- NOT part of the IF
Email sent to supplier

The condition is false, yet the second line ran anyway. Wrap the statements in a block and both are skipped together:

IF 1 = 0
BEGIN
    PRINT 'Restock order created';
    PRINT 'Email sent to supplier';
END
PRINT 'done';
done

Using BEGIN ... END even for one statement is a good habit; it makes the next person's edit safe.

ELSE IF for several branches

T-SQL has no ELSEIF keyword. Chain ELSE IF (two words) instead:

DECLARE @stock INT = (SELECT stock FROM products WHERE name = 'Backpack');

IF @stock IS NULL
    PRINT 'Stock unknown';
ELSE IF @stock = 0
    PRINT 'Sold out';
ELSE IF @stock < 10
    PRINT 'Low stock';
ELSE
    PRINT 'In stock';
Low stock

Borrowing syntax from other languages fails with a syntax error:

  • IF 1 = 1 THEN PRINT 'x'; → Incorrect syntax near the keyword 'THEN'.
  • ELSEIF 1 = 2 PRINT 'b' → Incorrect syntax near 'ELSEIF'.
  • Two ELSE branches on one IF → Incorrect syntax near the keyword 'ELSE'.
  • IF inside a SELECT → Incorrect syntax near the keyword 'IF'. Use IIF or CASE there.

Microsoft's reference is IF...ELSE (Transact-SQL), and IIF for the function.

MySQL IF statement (stored procedures)

MySQL has both an IF() function, covered above, and an IF statement. The statement only works inside stored programs: procedures, functions, triggers and events. Its form is closer to other languages:

IF condition THEN
    statements;
[ELSEIF condition THEN
    statements;]
[ELSE
    statements;]
END IF;

Here's a procedure that reports a product's stock status:

DELIMITER //
CREATE PROCEDURE stock_status(IN p_name VARCHAR(50))
BEGIN
  DECLARE v_stock INT;
  SELECT stock INTO v_stock FROM products WHERE name = p_name;

  IF v_stock IS NULL THEN
    SELECT CONCAT(p_name, ': stock unknown') AS status;
  ELSEIF v_stock = 0 THEN
    SELECT CONCAT(p_name, ': sold out') AS status;
  ELSEIF v_stock < 10 THEN
    SELECT CONCAT(p_name, ': low stock (', v_stock, ' left)') AS status;
  ELSE
    SELECT CONCAT(p_name, ': in stock') AS status;
  END IF;
END //
DELIMITER ;

CALL stock_status('Backpack');
CALL stock_status('Desk lamp');
+------------------------------+
| status                       |
+------------------------------+
| Backpack: low stock (8 left) |
+------------------------------+
+--------------------------+
| status                   |
+--------------------------+
| Desk lamp: stock unknown |
+--------------------------+

Things that trip people up in MySQL:

  • Running IF outside a procedure. IF (SELECT COUNT(*) FROM products) > 0 THEN SELECT 'x'; END IF; typed straight into the client fails with ERROR 1064 (42000): You have an error in your SQL syntax. Put it in a procedure, or use the IF() function in a query.
  • ELSE IF instead of ELSEIF. In MySQL, ELSE IF starts a new, nested IF that needs its own END IF. Forget it and CREATE PROCEDURE fails with error 1064. Write ELSEIF as one word.
  • Forgetting DELIMITER. Without it, the client sends the procedure at the first ; and you get a syntax error halfway through.
  • IF() treats its first argument as a number. IF('abc', 'yes', 'no') returns no with a warning (Truncated incorrect DOUBLE value: 'abc'), and IF(0, ...) and IF(NULL, ...) both pick the false value.

MySQL also has IFNULL(a, b) and NULLIF(a, b), which are specialised null checks rather than general if/else. Reference: IF statement and flow control functions.

PostgreSQL IF (PL/pgSQL)

Plain PostgreSQL SQL has no IF at all: inside queries you use CASE. The IF statement lives in PL/pgSQL, PostgreSQL's procedural language, which you use in functions, procedures, triggers and anonymous DO blocks. Note the spelling ELSIF:

DO $$
DECLARE
  v_stock INT;
BEGIN
  SELECT stock INTO v_stock FROM products WHERE name = 'Backpack';

  IF v_stock IS NULL THEN
    RAISE NOTICE 'Stock unknown';
  ELSIF v_stock = 0 THEN
    RAISE NOTICE 'Sold out';
  ELSIF v_stock < 10 THEN
    RAISE NOTICE 'Low stock (% left)', v_stock;
  ELSE
    RAISE NOTICE 'In stock';
  END IF;
END $$;
NOTICE:  Low stock (8 left)
DO

A DO block can't return rows. To use the logic in a query, wrap it in a function:

CREATE FUNCTION stock_status(p_name TEXT) RETURNS TEXT AS $$
DECLARE v_stock INT;
BEGIN
  SELECT stock INTO v_stock FROM products WHERE name = p_name;
  IF v_stock IS NULL THEN RETURN 'Stock unknown';
  ELSIF v_stock = 0 THEN RETURN 'Sold out';
  ELSIF v_stock < 10 THEN RETURN 'Low stock';
  ELSE RETURN 'In stock';
  END IF;
END $$ LANGUAGE plpgsql;

SELECT name, stock_status(name) FROM products ORDER BY id;
   name    | stock_status
-----------+---------------
 Notebook  | In stock
 Pen       | Sold out
 Backpack  | Low stock
 Desk lamp | Stock unknown
 Stapler   | In stock

For something this simple, a CASE in the query would be faster and easier; functions earn their place when the logic is reused in many queries or needs several steps. Notes from our runs:

  • PL/pgSQL accepts ELSEIF as an alias for ELSIF, so both spellings work.
  • ELSE IF (two words) opens a nested IF, as in MySQL. Without a second END IF you get syntax error at end of input.
  • IF ... THEN typed outside a DO block or function fails with syntax error at or near "IF".

SQLite: IIF() and IF(), no IF statement

SQLite has no stored procedures, so it has no IF statement. Inside queries you have:

  • CASE, in every version.
  • IIF(condition, true_value, false_value), since SQLite 3.32.0 (2020).
  • IF() as another name for IIF(), plus a two-argument form, since 3.48.0 (January 2025). From 3.49.0, IIF accepts more than three arguments as condition/value pairs, like a compact CASE.

Check your version with SELECT sqlite_version();. Older builds are still common in apps, browsers and embedded systems: our 3.45.1 returned no such function: IF, and the SQL Easy lessons, which run an older SQLite in your browser, don't have IIF either. CASE works in all of them. In SQLite, IIF('abc', ...) picks the false value and IIF(2, ...) the true one, because the condition is read as a number. See the SQLite core functions page.

Oracle, Snowflake, BigQuery and others

DatabaseIn a queryControl flow
OracleCASE, DECODE(col, val, result, default); no IF() or IIF()PL/SQL: IF ... THEN ... ELSIF ... ELSE ... END IF;
SnowflakeIFF(cond, a, b), CASESnowflake Scripting: IF (cond) THEN ... ELSEIF ... END IF;
BigQueryIF(cond, a, b), CASEProcedural language: IF cond THEN ... ELSEIF ... END IF;
Databricks / Spark SQLIF(cond, a, b), IFF, CASESQL scripting: IF cond THEN ... ELSEIF ... END IF;
MariaDBIF(cond, a, b), CASESame as MySQL, in stored programs

Note Snowflake's spelling: IFF, with two Fs. Writing IIF there is a common copy-paste error from SQL Server.

IF EXISTS: act only when a row is (or isn't) there

A frequent reason to reach for IF is "do this only if a matching row exists". In SQL Server:

IF EXISTS (SELECT 1 FROM products WHERE stock = 0)
    SELECT name FROM products WHERE stock = 0;
ELSE
    PRINT 'Nothing is sold out';
name
----
Pen

PL/pgSQL accepts the same IF EXISTS (...) THEN test inside a DO block or function, and MySQL inside a procedure.

IF EXISTS UPDATE ELSE INSERT (upsert)

The most common use of all is "update the row if it's there, otherwise insert it":

-- SQL Server
DECLARE @id INT = 6;
IF EXISTS (SELECT 1 FROM products WHERE id = @id)
    UPDATE products SET stock = stock + 10 WHERE id = @id;
ELSE
    INSERT INTO products (id, name, price, stock) VALUES (@id, 'Ruler', 2.25, 10);
id | name  | price | stock
---+-------+-------+------
 6 | Ruler |  2.25 |    10

It works, but it has a race condition: two sessions can both see "no row" and both try to insert, and one fails on the primary key. Each database has a single statement that does the check and the write together, which is safer and shorter:

  • PostgreSQL and SQLite: INSERT ... ON CONFLICT (id) DO UPDATE SET ...
  • MySQL: INSERT ... ON DUPLICATE KEY UPDATE ...
  • SQL Server and Oracle: MERGE

The upsert section of the UPDATE guide has tested examples of each. To insert only when a row is missing and never update, a plain INSERT ... SELECT ... WHERE NOT EXISTS (...) works on every database without any IF; see insert if not exists. And to filter on existence inside a query, use WHERE EXISTS.

CREATE TABLE IF NOT EXISTS and DROP TABLE IF EXISTS

These look like IF statements but are part of the DDL command itself, and support varies:

CommandPostgreSQLMySQLSQLiteSQL Server 2022
CREATE TABLE IF NOT EXISTSYes (notice: "already exists, skipping")Yes (note 1050)YesNo: Incorrect syntax near the keyword 'IF'.
DROP TABLE IF EXISTSYesYesYesYes (since 2016)

In SQL Server, wrap the CREATE in a real IF:

IF OBJECT_ID('restock_log', 'U') IS NULL
    CREATE TABLE restock_log (id INT, product_id INT, qty INT);

IF NOT EXISTS only checks the table name, not its columns: if an older products table with different columns exists, the statement silently does nothing.

IF support by database

PostgreSQLMySQLSQL ServerSQLiteOracle
CASEYesYesYesYesYes
IF(cond, a, b)NoYesNo3.48+No
IIF(cond, a, b)NoNo2012+3.32+No
IF statementPL/pgSQL only (ELSIF)Stored programs only (ELSEIF)Anywhere in T-SQL (ELSE IF, no THEN)NonePL/SQL only (ELSIF)
Ends withEND IF;END IF;nothing (use BEGIN ... END for blocks)n/aEND IF;
FILTER (WHERE ...) on aggregatesYesNoNoYesNo

Common mistakes

  1. Using the IF statement inside a SELECT. The statement controls which queries run; it can't produce a column. Use CASE, IF() or IIF().
  2. Forgetting about NULL. An unknown condition goes to the else branch, so missing data gets the "false" label. Test IS NULL first.
  3. Missing BEGIN ... END in T-SQL. Only the first statement after IF is conditional; the rest always run.
  4. Mixing up ELSE IF, ELSEIF and ELSIF. SQL Server: ELSE IF. MySQL: ELSEIF. PostgreSQL and Oracle: ELSIF.
  5. Copying a function between databases. IF() is MySQL, IIF() is SQL Server and SQLite, IFF() is Snowflake, and PostgreSQL has none. CASE is portable.
  6. Returning different types from each branch. SQL Server fails partway through the result; MySQL quietly turns the column into text.
  7. Using IF EXISTS ... UPDATE ELSE INSERT under concurrent load. Use ON CONFLICT, ON DUPLICATE KEY UPDATE or MERGE.
  8. Writing = NULL in a condition. It's never true. Use IS NULL.

FAQ

Is there an IF statement in SQL?

Not in standard SQL queries. The standard way to write if/then/else in a query is CASE WHEN condition THEN a ELSE b END. MySQL adds an IF() function, SQL Server and SQLite add IIF(), and SQL Server, MySQL, PostgreSQL and Oracle each have a procedural IF statement for scripts, procedures and functions.

How do you write an IF ELSE statement in SQL?

In a query: CASE WHEN stock > 0 THEN 'In stock' ELSE 'Sold out' END. In a SQL Server script: IF @stock > 0 PRINT 'In stock' ELSE PRINT 'Sold out';. In a MySQL procedure or PL/pgSQL block: IF v_stock > 0 THEN ... ELSE ... END IF;.

Can I use IF in a SELECT statement?

You can use the IF() function in MySQL and IIF() in SQL Server and SQLite, for example SELECT IIF(stock > 0, 'yes', 'no') FROM products. You can't use the IF ... ELSE statement inside a SELECT. CASE works in a SELECT on every database.

What is the difference between IF and CASE in SQL?

IF() and IIF() test one condition and return one of two values; they are database-specific shortcuts for a two-branch CASE. CASE is standard SQL, works everywhere and handles any number of conditions. The IF statement is different again: it controls which statements run rather than returning a value.

What is IIF in SQL?

IIF(condition, value_if_true, value_if_false) is an inline if function in SQL Server (2012 and later) and SQLite (3.32 and later). SQL Server converts it to a CASE expression, so it follows the same rules, including the limit of 10 levels of nesting.

How do I use multiple conditions in a SQL IF?

Combine tests with AND and OR inside one condition, and use CASE with several WHEN branches (or ELSE IF / ELSEIF / ELSIF in procedural code) for more than two outcomes. Nesting IF() calls also works but becomes hard to read.

What happens if the IF condition is NULL?

It is treated as not true, so the else branch runs (or nothing runs, if there is no else). That applies to IF(), IIF(), CASE and the procedural IF statement alike.

Does PostgreSQL have an IF function?

No. SELECT IF(...) fails with "function if(boolean, unknown, unknown) does not exist". Use CASE in queries, and the PL/pgSQL IF ... THEN ... ELSIF ... END IF statement inside functions and DO blocks.

How do I check if a record exists before inserting?

Use INSERT ... SELECT ... WHERE NOT EXISTS (...), which works everywhere, or the database's upsert (ON CONFLICT, ON DUPLICATE KEY UPDATE, MERGE). IF NOT EXISTS (...) INSERT ... works in SQL Server but can race under concurrent writes.

Practice

The fastest way to get comfortable with conditional logic is to write some. The free CASE lesson runs in your browser with no signup, and COALESCE covers the NULL side. Then read the full CASE statement guide, try the SQL practice problems, and keep the SQL cheat sheet nearby. Conditional logic comes up constantly in SQL interview questions, usually combined with GROUP BY.