// strings reference

SQL CHARINDEX function

SQL Server's substring search: it returns where a substring starts, or 0 when it is not there.

카테고리
Strings
Returns
integer
In this category
87 of 172

구문

CHARINDEX(substr, string)
CHARINDEX(substr, string, start_position)

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 Different name or syntax Use POSITION(substr IN str) or STRPOS(str, substr).
MySQL Different name or syntax LOCATE(substr, str, start) has the same argument order.
SQLite Different name or syntax Use INSTR(str, substr); no start argument.
Oracle Different name or syntax Use INSTR(str, substr, start).

예시

SQL Server

SELECT CHARINDEX('@', email) AS at_pos
FROM users;

SQL Server

SELECT CHARINDEX('/', url, CHARINDEX('//', url) + 2) AS path_start
FROM links;

알아 두면 좋은 정보

  • The substring comes first: CHARINDEX(substr, string). INSTR in Oracle, MySQL and SQLite takes the string first, so ported code silently searches the wrong way round.
  • The optional third argument is where the search starts, and the result is still counted from the start of the string: CHARINDEX('a', 'banana', 3) is 4.
  • Case sensitivity follows the collation: the default case-insensitive collations find 'A' in 'apple'; a _CS or _BIN collation does not.

Questions about CHARINDEX

How do I search from the end of a string with CHARINDEX?

There is no reverse flag. For a single character, LEN(s) - CHARINDEX(x, REVERSE(s)) + 1 gives the last position, but it returns LEN(s) + 1 when x is absent, and LEN ignores trailing spaces.

Does CHARINDEX respect case?

Only through collation. Under a case-insensitive collation (the usual install default) it matches any casing; add COLLATE Latin1_General_CS_AS to the column for an exact match.

What does CHARINDEX return for an empty substring?

0. CHARINDEX('', 'abc') treats the empty string as not found, while PostgreSQL's STRPOS(s, '') returns 1.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

// 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.