SQLPathLab
String Functions · Basic

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

Table:products
products
code
PRD-001-A
PRD-002-B
PRD-003-C

Run result

result
SUBSTRING(code, 1, 3)
PRD
PRD
PRD

Common issues

What happens when a string function receives NULL?

Check each function; with CONCAT, use COALESCE first when a fallback value is required.

Where does SUBSTRING indexing begin?

Common MySQL syntax starts at 1; verify argument rules when moving to another database.

Does TRIM remove spaces inside a string?

The default removes leading and trailing spaces only, not spaces within the value.

Tags

CommonString

Was this explanation clear?