// SQL snippet

Strip diacritics and accents in SQL

Match accented names against ASCII ones: search for 'jose' and still find José.

Main statement
PostgreSQL
Также охватывает
MySQL Oracle

The task

Searches for 'jose' never find 'José' unless the accents are gone. PostgreSQL can do this cleanly with the unaccent extension.

The snippet

Written for PostgreSQL. Versions for MySQL and Oracle are under Variations.

PostgreSQL
SELECT unaccent(last_name) AS plain_name
FROM customers
WHERE unaccent(lower(last_name)) = 'jose';

Как это работает

unaccent() maps each accented letter to its base letter. The extension ships with PostgreSQL but must be installed once per database (CREATE EXTENSION unaccent) and used with an IMMUTABLE wrapper for expression indexes. Results for non-Latin scripts can be surprising.

Variations

Oracle: CONVERT to US7ASCII

Oracle
SELECT CONVERT(last_name, 'US7ASCII') AS plain_name
FROM customers;

MySQL (replaces accented letters with ?, does not transliterate)

MySQL
SELECT CONVERT(last_name USING ascii) AS plain_name
FROM customers;

Questions that come up

Why is this not portable?

None of the engines agree. PostgreSQL transliterates with unaccent. Oracle's CONVERT to US7ASCII turns 'José García' into 'Jose Garcia' but some letters, Ñ and ñ among them, come back as '?', and it only works on VARCHAR2 values, not NVARCHAR2. MySQL's USING ascii replaces every accented letter with '?'. SQL Server has no function; the known trick CAST(name COLLATE SQL_Latin1_General_CP1253_CI_AI AS varchar(100)) strips accents through a Greek code page, but comparing with an accent-insensitive collation is usually the better fix.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.