Full answer
sql
SELECT 'a' || 1 + 2 AS result;| result |
|---|
| 2 |
In SQLite, || has the highest precedence of the binary operators. 'a' || 1 is the text 'a1'; adding 2 converts 'a1' to a number, and since it does not start with digits that number is 0, so the sum is 2. PostgreSQL places || among the 'other operators', below +, so the same text means something else there:
sql
SELECT 'a' || 1 + 2 AS result;| result |
|---|
| a3 |
The same expression gives two different answers on two engines without any error, which makes this a portability trap worth remembering. Parentheses settle it.
sql
SELECT 'a' || 1 + 2 AS result;Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
- SQLite: || binds tighter than +
- PostgreSQL: + binds tighter than ||
- Non-numeric text converts to 0 in SQLite arithmetic
- Always parenthesise mixed expressions
Common mistakes
- Assuming operator precedence is identical across engines
Follow-ups
- What does 'a' || (1 + 2) return in SQLite?
- Which other operators differ in precedence between engines?
Tips
- Run both engines in your head