Branch type resolution in conditional expressions
Core idea
Conditional expressions choose a value, but database engines differ in how they determine its type. PostgreSQL resolves CASE and COALESCE arguments to a common compatible type before execution. SQLite may return different storage classes for different rows.
Minimal example
SELECT typeof(CASE WHEN 1=1 THEN 7 ELSE 'missing' END), typeof(CASE WHEN 1=0 THEN 7 ELSE 'missing' END);Expected SQLite rows:
integer | textHow it works
The first example uses SQLite-specific typeof to show that selecting an integer or text branch can produce different storage classes. PostgreSQL would reject the incompatible integer and text literal example using the same CASE branches because it attempts to convert the text to integer. The second example explicitly casts numeric scores to VARCHAR(20) and uses a text fallback. That makes the intended text output clear; SQLite does not enforce VARCHAR length.
Practical example
SELECT id, CASE WHEN score IS NULL THEN 'missing' ELSE CAST(score AS VARCHAR(20)) END AS label FROM sort_scores ORDER BY id;Expected SQLite rows:
1 | 102 | missing3 | 04 | missingCommon mistake and practice
Do not rely on SQLite accepting mixed result types as evidence of PostgreSQL compatibility. Choose a result type based on the consumer: numeric for arithmetic, text for labels. Practice: rewrite the first CASE so both branches are explicitly cast to VARCHAR(20), then inspect the storage classes in SQLite. PostgreSQL execution is pending.