Sub topic 13
Type conversion and dialect differences
This chapter assumes you can write SELECT-list expressions, use COALESCE and NULLIF, name columns with AS, and write CASE expressions. It covers how SQL converts values from one type to another, where that conversion produces surprises, and where the major databases (PostgreSQL, MySQL, SQL Server, Oracle, SQLite) disagree on syntax or behavior.
Why types matter in expressions
Every expression has a result type. salary * 12 takes its type from salary and the literal 12. A CASE or COALESCE has a type too, which the database works out from its branches or arguments. When the operands differ, the database converts one or more of them. This is called type conversion (or coercion).
There are two kinds:
- Implicit conversion: the database converts a value on its own, for example integer to decimal when you add
1 + 1.5. - Explicit conversion: you request it with
CASTor a dialect-specific function.
Implicit conversion is convenient until it hides a bug, so the rest of the chapter works through the cases where it matters.
Explicit conversion with CAST
CAST(expression AS type) is standard SQL and works in every major database.
SELECT CAST('2026-11-27' AS DATE) AS ship_date,
CAST('42' AS INTEGER) + 1 AS next_number,
CAST(salary AS DECIMAL(12,2)) / 12 AS monthly_salary
FROM employees;Other conversion syntax is not portable:
| Database | Extra conversion syntax |
|---|---|
| PostgreSQL | `value::type`, for example `salary::numeric` |
| SQL Server | `CONVERT(type, value)`, `TRY_CAST`, `TRY_CONVERT` |
| Oracle | `TO_NUMBER`, `TO_CHAR`, `TO_DATE` |
| MySQL | `CONVERT(value, type)` |
| BigQuery | `SAFE_CAST` |
A failing conversion such as CAST('abc' AS INTEGER) raises an error and stops the whole statement. SQL Server's TRY_CAST and BigQuery's SAFE_CAST return NULL instead. PostgreSQL has no equivalent function, so you must validate the text first.
Type names also differ. MySQL does not accept CAST(x AS VARCHAR(20)). It uses CAST(x AS CHAR(20)). Oracle uses VARCHAR2 for its native text type, though CAST(x AS VARCHAR(20)) is accepted there.
Integer division
When both operands of / are integers, the result depends on the database.
SELECT 7 / 2 AS plain_division,
7 / 2.0 AS decimal_operand,
CAST(7 AS DECIMAL(10,2)) / 2 AS cast_operand;| Database | `7 / 2` |
|---|---|
| PostgreSQL | 3 (truncated) |
| SQL Server | 3 (truncated) |
| SQLite | 3 (truncated) |
| MySQL | 3.5000 (decimal) |
| Oracle | 3.5 |
The second and third columns return a decimal (3.5) in every database listed. This matters most in ratios such as completed_count / total_count, which silently returns 0 in PostgreSQL and SQL Server whenever completed_count is smaller than total_count. Cast one operand, or multiply by 1.0, before dividing.
SELECT completed_count * 1.0 / NULLIF(total_count, 0) AS completion_rate
FROM job_summary;Here NULLIF guards against division by zero, as in the earlier chapter, and * 1.0 forces decimal arithmetic.
Division by zero also differs. PostgreSQL, SQL Server, and Oracle raise an error. MySQL returns NULL by default, depending on its SQL mode. Do not rely on either behavior. Use NULLIF.
Result types of CASE and COALESCE
CASE returns one value, so all its THEN and ELSE results must share a type. The database finds a common type, and what it does when it cannot varies.
SELECT first_name,
CASE
WHEN commission IS NULL THEN 'none'
ELSE commission
END AS commission_label
FROM employees;If commission is numeric, this query fails in PostgreSQL and SQL Server. PostgreSQL reports a type mismatch. SQL Server tries to convert 'none' to a number, because numbers rank higher in its type precedence, and the conversion fails. MySQL runs the query and returns text. SQLite also runs it, because it does not enforce column types strictly.
The portable fix is to cast the branches to one type yourself:
SELECT first_name,
CASE
WHEN commission IS NULL THEN 'none'
ELSE CAST(commission AS VARCHAR(20))
END AS commission_label
FROM employees;On MySQL, write CAST(commission AS CHAR(20)).
The same rule applies to COALESCE, which behaves like a CASE: COALESCE(commission, 'none') fails for the same reason. When the branches mix types that can be combined, such as integer and decimal, the result takes the wider type. A CASE with THEN 1 and ELSE 2.5 returns decimal values for both branches, so you see 1.0, not 1.
Comparing values of different types
Comparisons convert types as well. The behavior is a common source of dialect bugs:
- PostgreSQL refuses to compare a number with text, such as
WHERE employee_id = 'abc'. It raises an error. - SQL Server converts the text to a number and fails on
'abc'. - MySQL converts silently.
'abc' = 0is true, because'abc'becomes 0.
This affects simple CASE, which compares with equality. In CASE status WHEN 'P' THEN ..., case sensitivity of the text comparison also depends on the database. PostgreSQL and Oracle are case-sensitive by default. MySQL and SQL Server compare text case-insensitively under their default collations, so 'p' matches 'P' there. When your CASE must behave the same everywhere, normalize the input first, as in CASE UPPER(status) WHEN 'P' THEN ....
Text concatenation and NULL
Joining text is one of the biggest dialect differences.
| Database | Operator or function | NULL behavior | Column | Column | Column | Column |
|---|---|---|---|---|---|---|
| PostgreSQL | `a \ | \ | b`, `CONCAT(a, b)` | `\ | \ | ` returns NULL if any part is NULL; `CONCAT` skips NULLs |
| Oracle | `a \ | \ | b`, `CONCAT(a, b)` | NULL is treated as empty text in `\ | \ | ` |
| SQL Server | `a + b`, `CONCAT(a, b)` | `+` returns NULL if any part is NULL; `CONCAT` skips NULLs | ||||
| MySQL | `CONCAT(a, b)` | Returns NULL if any argument is NULL | ||||
| SQLite | `a \ | \ | b` | Returns NULL if any part is NULL |
In MySQL, || means logical OR unless the PIPES_AS_CONCAT mode is on. The function CONCAT(a, b) is the nearest thing to portable, and you should wrap nullable columns in COALESCE:
SELECT CONCAT(first_name, ' ', COALESCE(middle_name, ''), ' ', last_name) AS full_name
FROM employees;This leaves a double space when middle_name is missing. Building a clean name takes a CASE, which also shows how the earlier chapters combine:
SELECT CASE
WHEN middle_name IS NULL THEN CONCAT(first_name, ' ', last_name)
ELSE CONCAT(first_name, ' ', middle_name, ' ', last_name)
END AS full_name
FROM employees;Oracle needs one more warning. It treats an empty string as NULL, so COALESCE(middle_name, '') produces NULL again there, and WHERE middle_name = '' never matches.
Names for NULL handling functions
COALESCE and NULLIF are standard and portable. Each database also has shorter, non-standard functions:
| Function | Database | Equivalent |
|---|---|---|
| `IFNULL(a, b)` | MySQL, SQLite | `COALESCE(a, b)` |
| `NVL(a, b)` | Oracle | `COALESCE(a, b)` |
| `ISNULL(a, b)` | SQL Server | `COALESCE(a, b)`, with a type difference |
The type difference with SQL Server's ISNULL is a trap. Its result takes the type of the first argument, so ISNULL(short_text_column, 'a much longer replacement') truncates the replacement to the first column's length. COALESCE uses type precedence across all arguments and does not truncate. Prefer COALESCE in code you want to move between databases.
Alias rules across databases
The earlier chapter on alias scope gave the standard rule: WHERE cannot see an alias from the same SELECT, but ORDER BY can. Databases extend the rule in different ways:
| Clause | PostgreSQL | MySQL | SQL Server | Oracle |
|---|---|---|---|---|
| `WHERE` | No | No | No | No |
| `GROUP BY` | Yes | Yes | No | No in older versions |
| `HAVING` | No | Yes | No | No |
| `ORDER BY` | Yes | Yes | Yes | Yes |
Snowflake and Redshift go further and allow an alias to be reused by another expression in the same SELECT list. MySQL, PostgreSQL, SQL Server, and Oracle do not. Check your version's documentation, because newer releases keep relaxing these rules.
The portable form repeats the expression or moves it into a subquery. This example groups by a CASE and works in every major database:
SELECT salary_band, COUNT(*) AS headcount
FROM (
SELECT CASE
WHEN salary >= 100000 THEN 'high'
WHEN salary >= 50000 THEN 'medium'
ELSE 'low'
END AS salary_band
FROM employees
) AS banded
GROUP BY salary_band;Alias spelling also varies. Unquoted names fold to lowercase in PostgreSQL and to uppercase in Oracle. Quoting protects spaces and reserved words, and the quote character differs: double quotes are standard, MySQL uses backticks, and SQL Server also accepts square brackets.
SELECT salary * 12 AS "Annual Salary"
FROM employees;Checklist
- Cast one operand before dividing integers.
- Make every CASE and COALESCE branch the same type with
CAST. - Guard concatenation against NULL.
- Do not rely on aliases in
GROUP BYorHAVING. - Use COALESCE instead of
IFNULL,NVL, orISNULL.
Exercise
A query computes passed_count / total_count AS pass_rate on PostgreSQL, and every row shows 0 even though many students passed. What is wrong, and how do you fix it, including the case where total_count can be 0?
Show answer
Both columns are integers, so PostgreSQL truncates the division result to a whole number, and any ratio below 1 becomes 0. Convert one operand to decimal and guard the divisor: passed_count * 1.0 / NULLIF(total_count, 0) AS pass_rate. NULLIF turns a zero divisor into NULL, so the result is NULL instead of an error.
Exercise
This query fails on SQL Server because the commission column is numeric: SELECT CASE WHEN commission IS NULL THEN 'none' ELSE commission END FROM employees;. Explain the failure and write a version that works on every major database except MySQL, then state the change for MySQL.
Show answer
The branches are text ('none') and a number. SQL Server gives numbers higher type precedence, so it tries to convert 'none' to a number and the conversion fails. Cast the numeric branch to text: CASE WHEN commission IS NULL THEN 'none' ELSE CAST(commission AS VARCHAR(20)) END. On MySQL, use CAST(commission AS CHAR(20)), because MySQL's CAST does not accept VARCHAR.