// strings reference

SQL MID function

Extracts part of a string from a 1-based position. In MySQL it is another name for SUBSTRING.

Catégorie
Strings
Returns
string
In this category
99 of 172

Syntaxe

MID(str, start, length)
MID(str, start)

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

Prise en charge des moteurs

MoteurSupportNotes
SQL Server Different name or syntax Use SUBSTRING(str, start, length).
PostgreSQL Different name or syntax Use SUBSTRING or SUBSTR.
MySQL Oui Supported under this name.
SQLite Different name or syntax Use SUBSTR.
Oracle Different name or syntax Use SUBSTR.

Exemples

MySQL

SELECT MID('hello world', 7) AS tail;  -- world

MySQL

SELECT MID(iso_code, 1, 2) AS country
FROM locales;

Bon à savoir

  • MID is exactly SUBSTRING in MySQL: same 1-based positions, same omitted-length behaviour, NULL in gives NULL out.
  • Position 0 is not clamped to 1: MID('abc', 0) and MID('abc', 0, 2) both return an empty string.
  • Negative positions count from the end: MID('hello world', -5) is 'world'.

Questions about MID

Is MID the same as SUBSTRING in MySQL?

Yes, argument for argument. SUBSTRING is the portable spelling; MID only works in MySQL and MariaDB.

Why does MID('abc', 0) return an empty string?

MySQL positions start at 1 and a start of 0 points before the string, so nothing is returned. Oracle's SUBSTR treats 0 as 1, which is why code ported from Oracle breaks here.

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.