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.
Example of LEFT()
Here’s an example where I select the first 5 characters from a string:
SELECT LEFT('Toothbrush', 5) AS Result;
Result:
+--------+ | Result | +--------+ | Tooth | +--------+
Example of RIGHT()
Now I select the last 5 characters from the same string. In this case, all I need to do is change LEFT
to RIGHT
:
SELECT RIGHT('Toothbrush', 5) AS Result;
Result:
+--------+ | Result | +--------+ | brush | +--------+
Example of LEFT() using a Database Query
Here’s another example, this time using a database query:
USE Music; SELECT ArtistName AS Original, LEFT(ArtistName, 3) AS Modified FROM Artists LIMIT 5;
Result:
+------------------+----------+ | Original | Modified | +------------------+----------+ | Iron Maiden | Iro | | AC/DC | AC/ | | Allan Holdsworth | All | | Buddy Rich | Bud | | Devin Townsend | Dev | +------------------+----------+
In this example, we get the first 3 characters from the ArtistName
column and compare it to the original string.
Example of RIGHT() using a Database Query
And here’s the same example as the previous one, except this time we select the 3 rightmost characters:
USE Music; SELECT ArtistName AS Original, RIGHT(ArtistName, 3) AS Modified FROM Artists LIMIT 5;
Result:
+------------------+----------+ | Original | Modified | +------------------+----------+ | Iron Maiden | den | | AC/DC | /DC | | Allan Holdsworth | rth | | Buddy Rich | ich | | Devin Townsend | end | +------------------+----------+