// strings reference

SQL LOCATE function

MySQL's substring search: returns the first position of a substring, optionally searching from a given position.

Категория
Strings
Returns
integer
In this category
88 of 172

Синтаксис

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.

Поддержка движка

ДвижокSupportЗаметки
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 Да Supported under this name.
SQLite Different name or syntax Use INSTR(str, substr).
Oracle Different name or syntax Use INSTR(str, substr, start).

Примеры

MySQL

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

MySQL

SELECT LOCATE('-', sku, LOCATE('-', sku) + 1) AS second_dash
FROM products;

Полезно знать

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

Cheat sheets for the engines that have it: MySQL, SQL Server, PostgreSQL, 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.