// strings reference

SQL INSTR function

Returns the position of the first occurrence of a substring, or 0 when it is not there. The argument order is the portability trap: SQL Server puts the needle first, most others put the haystack first.

Categoria
Strings
Returns
integer
In this category
10 of 172

Sintaxe

CHARINDEX(needle, haystack)
POSITION(needle IN haystack)
INSTR(haystack, needle)

Each block is a separate form. The support table and the examples show which engine takes which.

Suporte a mecanismos

MotorSupportNotas
SQL Server Different name or syntax CHARINDEX(needle, haystack [, start])
PostgreSQL Different name or syntax POSITION(needle IN haystack) or STRPOS(haystack, needle)
MySQL Sim INSTR(haystack, needle), plus LOCATE(needle, haystack [, start]) and POSITION
SQLite Sim Supported under this name.
Oracle Sim Supported under this name.

Exemplos

SQL Server

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

MySQL

SELECT INSTR(email, '@') AS at_sign FROM users;

PostgreSQL

SELECT POSITION('@' IN email) AS at_sign FROM users;

Oracle

SELECT INSTR('[email protected]', '@', -1) AS last_at FROM dual;  -- 2

Bom saber

  • Positions are 1-based and 0 means not found on all five engines.
  • SQL Server's CHARINDEX and MySQL's LOCATE take the needle first; INSTR on MySQL, SQLite and Oracle takes the haystack first. Swapping them returns a wrong number, not an error.
  • Oracle's INSTR has optional occurrence and start-position arguments: INSTR(s, 'a', -1) searches backwards.

Questions about INSTR / CHARINDEX / POSITION

What does INSTR return when the substring is not found?

0 on every major engine. Combined with 1-based positions, that makes INSTR(s, x) > 0 the portable contains test.

Why do CHARINDEX and INSTR have different argument orders?

They come from different vendors' traditions: SQL Server's CHARINDEX is (needle, haystack), while INSTR on MySQL, SQLite and Oracle is (haystack, needle). Nothing errors when you swap them; you just get a wrong number.

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.