// strings reference

SQL UNICODE function

The Unicode-aware sibling of ASCII. Same first-character-only rule, but for emoji the answer depends on whether the engine counts code points or UTF-16 units.

类别
Strings
Returns
integer
In this category
52 of 172

语法

UNICODE(string)
unicode(string)

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

引擎支持

引擎Support备注
SQL Server 是 UTF-16 code units unless the collation is _SC
PostgreSQL Different name or syntax ascii() returns the code point in a UTF8 database
MySQL Not built in no UNICODE(); ORD() returns encoded bytes
SQLite 是 Supported under this name.
Oracle Not built in No built-in equivalent.

示例

SQL Server

SELECT UNICODE(N'a') AS cp;  -- 97

SQL Server

SELECT UNICODE(N'😀') AS unit;  -- 55357 (surrogate half)

SQLite

SELECT unicode('😀') AS cp;  -- 128512

值得了解

  • SQL Server's UNICODE(N'😀') is 55357 (the high surrogate half) under a default collation. Under a supplementary-character (_SC) collation it returns 128512, the code point SQLite's unicode() gives.
  • The reverse call follows the same rule: NCHAR(128512) returns the emoji under an _SC collation and NULL otherwise.
  • First character only: UNICODE('abc') is 97 everywhere.
  • PostgreSQL has no UNICODE(), but in a UTF8 database ascii('😀') already returns 128512. MySQL has no code-point function at all; ORD() returns the UTF-8 bytes as one number.

Questions about UNICODE / unicode()

Why is UNICODE of an emoji 55357?

Under a non-SC collation SQL Server returns UTF-16 code units, and an emoji is a surrogate pair starting at 55357 (0xD83D). An _SC collation, SQLite's unicode() and PostgreSQL's ascii() report the code point 128512.

What is the difference between UNICODE and ASCII?

Scope: ASCII reads the first byte/code of a string and tops out in the single-byte range; UNICODE reads the first Unicode character. On nvarchar data, UNICODE is the correct call.

How do I convert a code point back to a character?

NCHAR(n) on SQL Server (above 65535 only under an _SC collation), char(n) on SQLite, chr(n) on PostgreSQL and Oracle. MySQL's CHAR(n) takes bytes, not code points.

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, SQLite.

// 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.