IF Statement — SQL Technical Interview Questions & Answers

IF Statement

IF Statement

  • Inside procedures: IF marks < 40 THEN SET msg = 'fail'; ELSE SET msg = 'pass'; END IF; This is not the IF() function. You need BEGIN … END and DELIMITER when creating the procedure.
  • Trap: writing IF THEN in a normal query tab. That’s a syntax error. Use IF() or CASE in SELECT.
  • On the example next to this theory: IF Statement: create two demo rows, then SELECT qty >= 2 ordered. Say which labels come back.

Technical Interview Tip: IF THEN is for procedures. SELECT uses IF() / CASE.

Code Examples for IF Statement

IF Statement — sample query

-- IF Statement
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 Statement: create two demo rows, then SELECT qty >= 2 ordered. Say which labels come back.

How to Explain IF Statement to an Interviewer

Can you use IF THEN in a normal SELECT?

No Use IF() or CASE