Blog

Blog

How to retrieve a set of characters using SUBSTRING in SQL?

Retrieve a set of characters using SUBSTRING

Retrieve a set of characters using SUBSTRING

Retrieving a set of characters with SUBSTRING in SQL

Sometimes, you may want to retrieve only a certain portion of a string from a column in your database. This is where the SUBSTRING function comes in handy.

To use SUBSTRING, you can use the following syntax:

SELECT SUBSTRING(column_name, starting_position, number_of_characters)
FROM table_name
WHERE condition;

For example, if you want to retrieve the first 5 characters from the name column of the customers table, you can use the following query:

SELECT SUBSTRING(name, 1, 5)
FROM customers
WHERE condition;

You can also use SUBSTRING with a condition, like this:

SELECT SUBSTRING(name, 1, 5)
FROM customers
WHERE city = 'New York';

This will return the first 5 characters of the name column for all customers who live in New York.

You can also use SUBSTRING in the SELECT clause to give the result column a different name:

SELECT SUBSTRING(name, 1, 5) AS shortened_name
FROM customers
WHERE condition;

Certainly! Here is an example of how to use the SUBSTRING function to retrieve a set of characters from a column, along with the resulting output.

Suppose we have the following customers table:

idnamecity
1JohnNew York
2JaneLos Angeles
3RobertChicago
4SusanNew York
5MichaelLos Angeles

If we want to retrieve the first 5 characters of the name column for all customers who live in New York, we can use the following query:

SELECT SUBSTRING(name, 1, 5)
FROM customers
WHERE city = 'New York';

This will give us the following output:

SUBSTRING(name, 1, 5)
John
Susan
Select the fields to be shown. Others will be hidden. Drag and drop to rearrange the order.
  • Image
  • SKU
  • Rating
  • Price
  • Stock
  • Availability
  • Add to cart
  • Description
  • Content
  • Weight
  • Dimensions
  • Additional information
Click outside to hide the comparison bar
Compare

Subscribe to Newsletter

Stay ahead of the rapidly evolving world of technology with our news letters. Subscribe now!