SQL SUBSTRING Function

Quick summary: The SQL SUBSTRING() function extracts a portion of a string.

SQL SUBSTRING Syntax

SUBSTRING(string [FROM start] [FOR length])
SQL

SQL SUBSTRING Basic examples

SELECT SUBSTRING('abcdef', 2, 3);
SQL
Output:
bcd

Extracts a substring starting at position 2.

SQL SUBSTRING Real-world usage

SELECT SUBSTRING(email, 1, 5) FROM users;
SQL
Output:
Email prefixes

Extracts partial values.

SQL SUBSTRING Edge cases

SELECT SUBSTRING('abc', 10, 2);
SQL
Output:
Empty string

Returns empty string when start position exceeds length.

SQL SUBSTRING Common mistakes

Assuming zero-based indexes

SUBSTRING positions start at 1.

Incorrect
SUBSTRING('abc', 0, 1)
Correct
SUBSTRING('abc', 1, 1)

Use 1-based indexing.

SQL SUBSTRING Frequently Asked Questions

What does SUBSTRING() do in SQL?

Extracts a portion of a string.

Use case of SUBSTRING()?

Parsing text.

Syntax?

SUBSTRING(str, start, length).

Index start?

Usually starts at 1.

Common mistake?

Wrong index base.

Alternative?

SUBSTR.

Return type?

String.

Performance?

Fast.

Handles out of range?

Returns partial or empty.

Used in SELECT?

Yes.

Supports negative index?

Depends on DB.

Best practice?

Validate indexes.

SQL SUBSTRING Related SQL Keywords