// SQL snippet

Test whether a string starts or ends with a value in SQL

Prefix tests select product families; suffix tests select regional codes. Both should stay index-friendly where possible.

Main statement
All engines

The task

LIKE with a wildcard only at the end is a prefix test that can use an index; a leading wildcard is a suffix test that cannot.

The snippet

Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.

All engines
-- starts with AB-
SELECT sku
FROM products
WHERE sku LIKE 'AB-%';

-- ends with -XY (cannot use a plain index)
SELECT sku
FROM products
WHERE sku LIKE '%-XY';

仕組み

LIKE 'AB-%' keeps the constant prefix first, so a b-tree index on sku can seek it on SQL Server, MySQL and Oracle. PostgreSQL only does that with the C collation or an index built with text_pattern_ops, and SQLite only when the LIKE's case sensitivity matches the column's collation. LIKE '%-XY' must scan every row because any position could match; large tables deserve an indexed computed column of REVERSE(sku) for suffix searches.

Variations

PostgreSQL 11+: starts_with

PostgreSQL
SELECT sku
FROM products
WHERE starts_with(sku, 'AB-');

MySQL, Oracle, SQLite, SQL Server varchar: prefix as a range

SQL Server MySQL SQLite Oracle
SELECT sku
FROM products
WHERE sku >= 'AB-' AND sku < 'AB.';

Questions that come up

Why does the range trick avoid a scan?

The upper bound is the prefix with its last character bumped by one ('-' is 0x2D, '.' is 0x2E), so every string starting with 'AB-' sorts between 'AB-' and 'AB.' and the predicate becomes a range an index can seek. That only holds where '-' sorts as an ordinary character. PostgreSQL's default en_US collation, and SQL Server's nvarchar columns and Windows collations, give the hyphen almost no weight, so the range returns only the bare value 'AB-'. Add COLLATE "C" on PostgreSQL or COLLATE Latin1_General_BIN2 on SQL Server.

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.