VARCHAR — SQL Technical Interview Questions & Answers

VARCHAR

VARCHAR

  • VARCHAR(n) is variable-length text up to n characters (MySQL 8 utf8mb4: n is characters). name VARCHAR(50). CHAR(n) always uses n characters — rare now except fixed codes.
  • Don’t VARCHAR(255) everything without thought, but 255 is a common default. Too small = insert errors. TEXT is for long blobs (notes) — you cannot index TEXT the same way without a prefix.
  • Trap: VARCHAR for money or roll. Trap: CHAR(50) for names wasting space.
  • On the example next to this theory: VARCHAR: create two demo rows, then SELECT qty >= 2 ordered. Say which labels come back.

Technical Interview Tip: name VARCHAR(50) NOT NULL

Code Examples for VARCHAR

VARCHAR — sample query

-- VARCHAR
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;

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

How to Explain VARCHAR to an Interviewer

VARCHAR vs CHAR?

VARCHAR = variable length CHAR = fixed length