SUBSTRING
- SQL course
- Beginner
- Lesson 38/115
- 4 min
Slice a part of a string.
SUBSTRING
With SUBSTRING you take a part of a text. You specify the start and length to pick the slice you want.
SELECT SUBSTRING(name, 1, 3) AS ilk_uc FROM customers;This query returns the first 3 characters of each name.
SUBSTRING(name, 1, 3) AS ilk_uc is selected from customers.
SUBSTRING — details
Some databases use SUBSTR or LEFT. The start index is 1-based, not 0. Without length it goes to the end.
Practice SUBSTRING
Select the first 2 characters of name aliased as first from customers.
Starter code
-- first two letters
SELECT
FROM customersSample solution
SELECT SUBSTRING(name, 1, 2) AS ilk
FROM customersExpected output
ilk Ay Al
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 SUBSTRING: match the terms
| Term | Meaning |
|---|---|
SUBSTRING |
substring |
UPPER |
uppercase |
LENGTH |
length |
TRIM |
trim |
2 Take substring
SELECT ____(name, 1, 3) FROM customers;
SELECT SUBSTRING(name, 1, 3) FROM customers;
Explanation: SUBSTRING is the right answer.
3 What is the SUBSTRING start index?
- 1 Correct answer
- 0
- -1
- 2
Explanation: In SQL the start is 1-based.