MySQL MID() Function
MySQL MID() Function
The MID() function extracts a slice of characters from a string starting at a 1-based position. In MySQL, MID() is a direct synonym for SUBSTRING().
Syntax
MID(str, pos, len)
MID(str, pos)
- str: The source string to slice.
- pos: Starting 1-based position (
1is the first character; negative values count from the end). - len: Optional number of characters to extract.
- Return value: Extracted substring,
''ifpos = 0, orNULLif any argument isNULL.
Although MID() originated in Visual Basic style syntax with three arguments, MySQL also accepts the two-argument form MID(str, pos) to read through the end of the string.
Practical Example
Suppose demo_products uses structured SKU strings like 'EL-AUD-9042' where the three-letter department code always sits at character 4. MID() pulls out that middle token cleanly.
SELECT
product_id,
sku,
MID(sku, 4, 3) AS dept_code,
MID(sku, -4) AS model_suffix
FROM demo_products
ORDER BY product_id;
| product_id | sku | dept_code | model_suffix |
|---|---|---|---|
| 1 | EL-AUD-9042 | AUD | 9042 |
| 2 | HM-KIT-1180 | KIT | 1180 |
| 3 | OF-DSK-0045 | DSK | 0045 |
Using -4 in the second call counts backward four characters from the end to grab '9042'.
Common Mistakes & NULL Behavior
- Passing 0 as pos: MySQL uses
1-based indexing. CallingMID('EL-AUD', 0, 2)returns an empty string'', not'EL'. - Negative or zero len: Passing
len <= 0returns''. - Portability caveats:
MID()works in MySQL and MS Access, but PostgreSQL and SQLite do not supportMID(). UseSUBSTRING()orSUBSTR()if you write cross-database queries. - NULL inputs: If any argument is
NULL,MID()returnsNULL.
Frequently Asked Questions
Is MID() faster or slower than SUBSTRING()?
They execute the exact same internal function in MySQL, so performance is identical.
What happens if len goes past the end of the string?
MySQL returns all available characters from pos through the end of str without adding spaces.
Does MID() count characters or bytes on UTF-8 text?
It counts characters, so multibyte UTF-8 text slices cleanly at character boundaries.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.