SQL STARTS_WITH function
starts_with('alpha', 'al') is true. Outside PostgreSQL the prefix test is LIKE 'al%', which works everywhere and can use an index.
- カテゴリ
- 条件付き
- Returns
boolean- In this category
- 42 of 43
構文
starts_with(string, prefix)
string ^@ prefix
string LIKE 'prefix%'
Each block is a separate form. The support table and the examples show which engine takes which.
エンジンサポート
| エンジン | Support | メモ |
|---|---|---|
| SQL Server | Different name or syntax | no function; col LIKE 'abc%' or LEFT(col, 3) = 'abc' |
| PostgreSQL | はい | starts_with() and the ^@ operator |
| MySQL | Different name or syntax | no function; col LIKE 'abc%' or LEFT(col, 3) = 'abc' |
| SQLite | Different name or syntax | no function; col LIKE 'abc%' or substr(col, 1, 3) = 'abc' |
| Oracle | Different name or syntax | no function; col LIKE 'abc%' or SUBSTR(col, 1, 3) = 'abc' |
例
PostgreSQL
SELECT starts_with('alpha', 'al') AS a, 'alpha' ^@ 'al' AS b, starts_with('alpha', 'AL') AS c; -- t, t, f
PostgreSQL
SELECT starts_with('50%_off', '50%') AS literal, '5000' LIKE '50%' AS wildcard; -- t, t
MySQL
SELECT 'alpha' LIKE 'al%' AS a, LEFT('alpha', 2) = 'al' AS b; -- 1, 1
知っておくと便利なこと
- starts_with treats % and _ literally; LIKE treats them as wildcards. When the prefix comes from user input, escape those characters before building a LIKE pattern.
- starts_with is case-sensitive. LIKE follows the collation, so on SQL Server and MySQL defaults the prefix test ignores case.
- LEFT(col, 3) = 'abc' wraps the column in a function, which stops a plain index from being used; LIKE 'abc%' does not.
Questions about STARTS_WITH
Is there an ENDS_WITH?
Not on these engines. Use LIKE '%abc' or RIGHT(col, 3) = 'abc'; neither can use a normal index on col.
Does a prefix LIKE use an index on PostgreSQL?
Yes under the C collation. With other collations, create the index with text_pattern_ops (or varchar_pattern_ops).
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
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.