// conditional reference

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.

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.