// dialect comparison

Binary and blob hex literals in SQL Server, PostgreSQL, MySQL, SQLite and Oracle

The same four bytes, four spellings, and the SQL Server form is not even quoted.

Filed under Types & casting

The verdict

Portability requires binding binary values as parameters rather than literals; inline, every engine spells the bytes differently, and PostgreSQL's \x prefix makes it the easiest to misquote.

Where they differ

Writing literal bytes into a query surfaces each engine's binary model: SQL Server uses unquoted 0x literals, MySQL and SQLite use X'' strings, PostgreSQL escapes into bytea, and Oracle converts from a hex string.

How each engine writes it

SQL Server

SELECT 0xDEADBEEF;

Bare 0x literal, no quotes, yields VARBINARY. CONVERT(VARBINARY(8), 'DEADBEEF', 2) parses a hex string; CONVERT(VARCHAR, 0xDEADBEEF, 2) renders it back.

PostgreSQL

SELECT '\xDEADBEEF'::BYTEA;

bytea accepts the escape format \x inside a quoted string; DECODE('DEADBEEF', 'hex') is the string-based path, ENCODE(b, 'hex') the way out.

MySQL

SELECT X'DEADBEEF', 0xDEADBEEF;

X'...' is a binary string (even digit count required); a bare 0xDEADBEEF is a numeric hex literal that behaves as bytes in string context.

SQLite

SELECT X'DEADBEEF';

X'...' is the only blob literal and must have an even digit count. unhex('DEADBEEF') (3.41+) parses a hex string, and ZEROBLOB, RANDOMBLOB or CAST of text build others.

Oracle

SELECT HEXTORAW('DEADBEEF') FROM dual;

No binary literal syntax: HEXTORAW parses a hex string and RAWTOHEX renders one back. X'DEADBEEF' is a syntax error, 23ai included.

Questions that come up

Why does my hex literal with odd digits fail?

X'' literals in MySQL and SQLite need two hex digits per byte, so X'D' is a syntax error; write X'0D'. Unquoted 0x literals are more forgiving: SQL Server and MySQL read 0xD as 0x0D.

How do I view blob contents as text?

Round-trip through hex: CONVERT(VARCHAR, b, 2) in SQL Server, ENCODE(b, 'hex') in PostgreSQL, HEX(b) in MySQL and SQLite, RAWTOHEX(b) in Oracle.

Is a bare 0xDEADBEEF the same in MySQL and SQL Server?

Yes, both treat an unquoted 0x literal as binary-typed; the difference is MySQL also allows it as a number in numeric context, while SQL Server's is strictly varbinary.

Keep reading

// write it once, run it anywhere

Switch engines without relearning SQL

SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.