// strings reference

SQL string sorting and collation

ORDER BY on text follows the column's collation or locale, which decides where capitals, accents and spaces land. Pin it per query when the order matters.

類別
Strings
Returns
ordering
In this category
72 of 172

語法

ORDER BY name COLLATE collation_name
ORDER BY NLSSORT(name, 'NLS_SORT=XGerman')

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

引擎支援

引擎Support備註
SQL Server 是 Supported under this name.
PostgreSQL 是 Supported under this name.
MySQL 是 Supported under this name.
SQLite 是 Supported under this name.
Oracle 是 Supported under this name.

範例

SQL Server

SELECT name FROM users ORDER BY name COLLATE Latin1_General_BIN2;
-- byte order: 'Zebra' before 'apple'

PostgreSQL

SELECT name FROM users ORDER BY name COLLATE "de-x-icu";

Oracle

SELECT name FROM users ORDER BY NLSSORT(name, 'NLS_SORT = XGERMAN');

小知識

  • Binary order puts 'Zebra' before 'apple' (Z is 90, a is 97). Case-insensitive collations reorder the alphabet; the default differs per engine and per column.
  • PostgreSQL: the database locale decides, with per-expression COLLATE "de-x-icu" overrides on ICU installs.
  • SQL Server: per-column and per-query collations (Latin1_General_BIN2 for byte order, _CI variants for case-insensitive listings).
  • Oracle: NLS_SORT is BINARY by default; ORDER BY NLSSORT(name, 'NLS_SORT=XGERMAN') or NLS_COMP=LINGUISTIC switches to linguistic order.

Questions about Sorting strings

Why does the same query sort differently on two servers?

The columns carry different collations, or the database locales differ. Sorting is a collation property, not an ASCII constant. State the collation for stable cross-server order.

How do I sort case-insensitively?

Use a case-insensitive collation (SQL Server default _CI, MySQL _ci, ICU collations on PostgreSQL) rather than ORDER BY UPPER(name), which defeats indexes.

Does collation affect WHERE comparisons too?

Yes. The same collation decides equality, so PAD SPACE and accent rules show up in both ORDER BY and = at once.

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.