// strings reference

SQL STRPOS function

PostgreSQL's function-call form of POSITION: the string to search comes first, the substring second.

Categoría
Strings
Returns
integer
In this category
86 of 172

Sintaxis

STRPOS(string, substring)

Soporte del motor

MotorSupportNotas
SQL Server Different name or syntax Use CHARINDEX(substr, str); note the reversed order.
PostgreSQL Sí Same result as POSITION(substr IN str).
MySQL Different name or syntax Use INSTR(str, substr) or LOCATE(substr, str).
SQLite Different name or syntax Use INSTR(str, substr).
Oracle Different name or syntax Use INSTR(str, substr).

Ejemplos

PostgreSQL

SELECT STRPOS('hello world', 'world') AS pos;  -- 7

PostgreSQL

SELECT STRPOS(lower(path), '/admin') AS admin_pos
FROM page_views;

Conviene saberlo

  • The string comes first, like INSTR and unlike CHARINDEX or POSITION: STRPOS('hello world', 'world') is 7.
  • Matching is case-sensitive: STRPOS('Hello', 'hello') is 0. Compare lower() of both sides, or use ILIKE when you only need a yes or no.
  • An empty substring matches at position 1, so STRPOS(s, '') is 1 for any non-NULL s. SQL Server's CHARINDEX returns 0 for the same search.

Questions about STRPOS

What is the difference between STRPOS and POSITION in PostgreSQL?

Only the syntax. STRPOS(str, substr) is a normal function call; POSITION(substr IN str) is the standard keyword form. Both return the same 1-based index.

Why does STRPOS return 0 instead of NULL for a missing substring?

0 is the not-found answer. NULL is reserved for a NULL input, so STRPOS(s, x) > 0 works as a contains test as long as s is not NULL.

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