How to Return the Left or Right Part of a String in MySQL

When working with MySQL databases, you might occasionally find yourself needing to select only a certain number of characters from the left or right of a string. In such cases, you can use the LEFT() and RIGHT() functions to do just that.

Here’s the syntax for both of these functions:

LEFT(str,len)
RIGHT(str,len)

Where str is the string that contains the substring you need to return, and len is the number of characters from the left you want returned.

Continue reading

The Easiest Way to Add Multiple Spaces to a String in MySQL – SPACE()

Occasionally when working with MySQL databases, you might find yourself needing to add multiple space characters to a string.

Maybe you need to pad a string by adding leading or trailing spaces. Or maybe you need to replace a single space within the string with many spaces. Either way, MySQL has the SPACE() function to help you.

The SPACE() function is an easy way for you to return as many space characters as you need.

Continue reading

How to Remove Leading Whitespace in MySQL

MySQL has the LTRIM() function that enables you to remove leading whitespace from a string (space at the start of the string).

MySQL also has the TRIM() function that enables you to remove leading space, trailing space (at the end), space from both sides, or to remove other specified characters from either side (or both sides) of the string.

This article demonstrates how to remove leading space using each of these functions.

Continue reading

How to Remove Trailing Whitespace in MySQL

MySQL has an RTRIM() function that enables you to remove trailing whitespace from a string (space at the end of the string).

MySQL also has the TRIM() function that enables you to remove trailing space, leading space (at the start), space from both sides, or to remove other specified characters from either side (or both sides) of the string.

This article demonstrates how to remove trailing space using each of these functions.

Continue reading

How to Select Everything Before/After a Certain Character in MySQL – SUBSTRING_INDEX()

You can use the MySQL SUBSTRING_INDEX() function to return everything before or after a certain character (or characters) in a string.

This function allows you to specify the delimiter to use, and you can specify which one (in the event that there’s more than one in the string).

Syntax

Here’s the syntax:

SUBSTRING_INDEX(str,delim,count)

Where str is the string, delim is the delimiter (from which you want a substring to the left or right of), and count specifies which delimiter (in the event there are multiple occurrences of the delimiter in the string).

Note that the delimiter can be a single character or multiple characters.

Continue reading