SUBSTRING
extracting part of a string.
Overview
SUBSTRING extracts text from a starting position and may also accept a length. Common MySQL positions begin at 1, while a negative position can count from the end; an out-of-range position generally returns an empty string. Character length and byte length differ, so use text-aware functions and a suitable character set for multibyte data.
Basic syntax
SELECT SUBSTRING(code, 1, 3) FROM products;
Examples
SUBSTRING example
Extract three characters from the beginning of products.code to create a grouping prefix.
Sample table
products| code |
|---|
| PRD-001-A |
| PRD-002-B |
| PRD-003-C |
Run result
| SUBSTRING(code, 1, 3) |
|---|
| PRD |
| PRD |
| PRD |
Common issues
Check each function; with CONCAT, use COALESCE first when a fallback value is required.
Common MySQL syntax starts at 1; verify argument rules when moving to another database.
The default removes leading and trailing spaces only, not spaces within the value.
Tags
Was this explanation clear?
Thanks. This feedback will inform the next content review.