// conversion reference

SQL BINARY cast

CAST(value AS BINARY) turns a value into raw bytes. Which bytes depends on the engine: the string's character set on MySQL, UTF-16 for nvarchar on SQL Server, the database encoding for bytea.

Категория
Conversion
Returns
binary
In this category
12 of 39

Синтаксис

CAST(expression AS BINARY)  -- MySQL
CONVERT(varbinary(n), expression)  -- SQL Server
CAST(expression AS BLOB)  -- SQLite

Each block is a separate form. The support table and the examples show which engine takes which.

Поддержка движка

ДвижокSupportЗаметки
SQL Server Different name or syntax CONVERT(varbinary(n), value)
PostgreSQL Different name or syntax value::bytea or convert_to(text, encoding)
MySQL Да Supported under this name.
SQLite Different name or syntax CAST(x AS BLOB) keeps the text's bytes
Oracle Different name or syntax UTL_RAW.CAST_TO_RAW(text); HEXTORAW for hex strings

Примеры

MySQL

SELECT BINARY name = 'MATT' AS exact_match
FROM users;

SQL Server

SELECT CONVERT(varbinary(16), token) AS bytes
FROM sessions;

PostgreSQL

SELECT decode('4d415454', 'hex') AS bytes;

Полезно знать

  • MySQL's BINARY cast compares bytes: trailing spaces become significant and case folding disappears. It is a one-off comparison change; a binary collation (_bin) is the persistent fix.
  • MySQL 8.0.27 deprecated the BINARY operator spelling (BINARY expr) in favour of CAST(expr AS BINARY). Old code still runs but raises warning 1287.
  • On SQL Server, CONVERT(varbinary(8), N'SQL') is 0x530051004C00 (UTF-16, two bytes per character) while CONVERT(varbinary(8), 'SQL') is 0x53514C. The same text casts to different bytes depending on its type.
  • PostgreSQL bytea is not a string type: it prints as hex with a \x prefix, concatenates with || and needs convert_from(bytes, 'UTF8') to become text again.

Questions about BINARY / varbinary casts

Is BINARY the same as a binary collation?

No. BINARY casts the value to bytes for one comparison; a binary or case-sensitive collation (utf8mb4_bin, utf8mb4_0900_as_cs) keeps the string type and changes the comparison rule. For case-sensitive matching, the collation is the intended tool.

Why do my hashes differ between engines?

Because the bytes differ: MySQL hashes the string in its character set, SQL Server hashes nvarchar as UTF-16. HEX both inputs and compare the bytes before blaming the hash function.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.