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.
Related on SQLly
- Extract the domain from an email address in SQL Snippet
- Mask an email address in SQL for display Snippet
- Split a full name into first and last name in SQL Snippet
- Truncate text on a word boundary in SQL Snippet
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.