IF() — SQL Technical Interview Questions & Answers

IF()

IF()

  • IF(condition, a, b) is a function: IF(marks >= 40, 'Pass', 'Fail'). CASE is clearer for many branches. IF as a procedure statement (IF THEN END IF) is different — that is flow control inside stored programs.
  • Trap: mixing IF() function with procedural IF. Trap: nested IF() soup — use CASE.
  • On the example next to this theory: IF(): create two demo rows, then SELECT qty >= 2 ordered. Say which labels come back.

Technical Interview Tip: IF(marks >= 40, 'Pass', 'Fail') or CASE WHEN …

Code Examples for IF()

IF() — sample query

-- IF()
CREATE TABLE demo (
  id INTEGER PRIMARY KEY,
  label TEXT NOT NULL,
  qty INTEGER DEFAULT 0
);
INSERT INTO demo (id, label, qty) VALUES
  (1, 'alpha', 2),
  (2, 'beta', 5);
SELECT label, qty FROM demo WHERE qty >= 2 ORDER BY qty DESC;

IF(): create two demo rows, then SELECT qty >= 2 ordered. Say which labels come back.

How to Explain IF() to an Interviewer

Pass/fail column?

IF(marks >= 40, 'Pass', 'Fail')