SQL LOCATE function
MySQL's substring search: returns the first position of a substring, optionally searching from a given position.
- Kategorie
- Strings
- Returns
integer- In this category
- 88 of 172
Syntax
LOCATE(substr, str)
LOCATE(substr, str, start_position)
Each block is a separate form. The support table and the examples show which engine takes which.
Engine-Unterstützung
| Engine | Support | Notizen |
|---|---|---|
| SQL Server | Different name or syntax | CHARINDEX(substr, str, start) has the same argument order. |
| PostgreSQL | Different name or syntax | Use POSITION or STRPOS; no start argument. |
| MySQL | Ja | Supported under this name. |
| SQLite | Different name or syntax | Use INSTR(str, substr). |
| Oracle | Different name or syntax | Use INSTR(str, substr, start). |
Beispiele
MySQL
SELECT LOCATE('@', email) AS at_pos FROM users;
MySQL
SELECT LOCATE('-', sku, LOCATE('-', sku) + 1) AS second_dash
FROM products;
Gut zu wissen
- LOCATE puts the substring first; INSTR(str, substr) puts it second. Mixing the orders silently searches for the wrong needle.
- The third argument is the position to start searching at, and the answer is still counted from the start of the string: LOCATE('bar', 'foobarbar', 5) is 7.
- Returns 0 when not found and NULL when any argument is NULL. Matching follows the collation, which is case-insensitive under MySQL's defaults.
Questions about LOCATE
What is the difference between LOCATE and INSTR in MySQL?
Argument order and the start offset. LOCATE(substr, str [, pos]) takes the substring first and accepts a start position; INSTR(str, substr) takes the string first and has no start argument. POSITION(substr IN str) is a synonym for two-argument LOCATE.
Is LOCATE case-sensitive?
It depends on the collation of the arguments. The common *_ci collations make it case-insensitive; a _bin collation, or a BINARY operand, makes it exact.
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: MySQL, SQL Server, PostgreSQL, 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.