// strings reference

SQL POSITION function

Returns the 1-based position of the first occurrence of a substring, or 0 when it is not found. It is the SQL-standard spelling, but only PostgreSQL and MySQL accept it.

类别
Strings
Returns
integer
In this category
85 of 172

语法

POSITION(substr IN str)

引擎支持

引擎Support备注
SQL Server Different name or syntax No POSITION; use CHARINDEX(substr, str).
PostgreSQL 是 Supported under this name.
MySQL 是 POSITION(substr IN str) is a synonym for LOCATE(substr, str).
SQLite Different name or syntax No POSITION; use INSTR(str, substr).
Oracle Different name or syntax No POSITION; use INSTR(str, substr).

示例

PostgreSQL

SELECT POSITION('world' IN 'hello world') AS pos;  -- 7

MySQL

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

值得了解

  • Positions are 1-based and 0 means not found, so POSITION(x IN s) > 0 is the containment test.
  • A NULL argument returns NULL, not 0, so WHERE POSITION('@' IN email) = 0 silently skips rows where email is NULL.
  • PostgreSQL always matches case exactly. MySQL follows the collation, and its default utf8mb4_0900_ai_ci ignores case: POSITION('B' IN 'abc') is 2 there.

Questions about POSITION

What does POSITION return if the substring is not found?

Zero. NULL comes back only when one of the arguments is NULL.

Is POSITION the same as CHARINDEX or INSTR?

Same answer, different spelling and argument order: CHARINDEX(substr, str) in SQL Server, INSTR(str, substr) in SQLite, Oracle and MySQL. Only PostgreSQL and MySQL accept the standard POSITION(substr IN str) form.

How do I find the second occurrence of a substring?

POSITION has no start argument. In PostgreSQL search the remainder: POSITION('x' IN SUBSTRING(s FROM p + 1)) + p, remembering that a miss returns p rather than 0. MySQL's LOCATE('x', s, p + 1) and Oracle's INSTR(s, 'x', 1, 2) do it directly.

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: PostgreSQL, SQL Server, MySQL, 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.