Skip to main content

SQL SUBSTRING()

In this tutorial, you will learn about the SQL SUBSTRING() function with the help of examples.

In SQL, the SUBSTRING() function is used to extract substring from a string.

Example

-- extract the first 3 characters from the first names of each customer

SELECT customer_id, SUBSTRING(first_name, 1, 3) AS first_name_short
FROM Customers;

Here, we have used SUBSTRING() to extract the first three characters of each customer's first names.

The function takes three arguments: the string column, the start position, and the length of the substring.


SUBSTRING() With JOIN

In SQL, the SUBSTRING() function can also be used in more complex scenarios, such as in conjunction with JOIN operations.

Let's look at an example.

-- extract part of item names in order details

SELECT o.order_id, SUBSTRING(o.item, 1, 5) AS item_short, o.amount
FROM Orders o
JOIN Customers c ON o.customer_id = c.customer_id
WHERE c.country = 'UK';