// strings reference

SQL ORD function

Returns the code of the leftmost character of a string, combining all of its bytes for multi-byte characters.

Categoria
Strings
Returns
integer
In this category
129 of 172

Sintaxe

ORD(string)

Suporte a mecanismos

MotorSupportNotas
SQL Server Not built in No ORD; UNICODE returns the code point.
PostgreSQL Not built in No ORD; ascii() returns the code point.
MySQL Sim Supported under this name.
SQLite Not built in No ORD; unicode() returns the code point.
Oracle Different name or syntax ASCII returns the same byte-combined value.

Exemplos

MySQL

SELECT ORD('A') AS code, ORD('é') AS utf8_code;  -- 65, 50089

MySQL

SELECT ORD(CONVERT(SUBSTR(col, 1, 1) USING utf32)) AS code_point
FROM items;

Bom saber

  • For a multi-byte character ORD combines the bytes: (first byte × 256) + second byte, and so on. ORD('é') in utf8mb4 is 50089 (0xC3A9), not the code point 233.
  • For single-byte characters ORD equals ASCII. It reads only the first character; pair it with SUBSTR to step through a string.
  • ORD('') is 0 and ORD(NULL) is NULL, like ASCII.

Questions about ORD

How is ORD different from ASCII in MySQL?

ASCII returns only the first byte (195 for é); ORD combines all the bytes of the first character (50089). Neither is the code point. ORD(CONVERT(c USING utf32)) returns 233, because UTF-32 stores the code point directly.

What is the equivalent in other engines?

UNICODE() in SQL Server and SQLite and ascii() in PostgreSQL return code points. Oracle's ASCII returns the same byte-combined value as ORD.

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: MySQL, 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.