How to Use LEFT and RIGHT Functions in MySQL
In MySQL, use the
LEFT(string, number) function to get the first number characters from the start of a string, and use RIGHT(string, number) to get the last number characters from the end of a string. These functions help extract specific parts of text easily.Syntax
The LEFT and RIGHT functions extract a substring from a string.
- LEFT(string, number): Returns the first
numbercharacters from the start ofstring. - RIGHT(string, number): Returns the last
numbercharacters from the end ofstring.
Both functions require two arguments: the string to extract from, and how many characters to take.
sql
LEFT(str, len); RIGHT(str, len);
Example
This example shows how to use LEFT and RIGHT to get parts of a string.
sql
SELECT LEFT('Hello World', 5) AS left_part, RIGHT('Hello World', 5) AS right_part;
Output
left_part | right_part
----------|-----------
Hello | World
Common Pitfalls
Common mistakes include:
- Using a negative number for the length, which causes an error.
- Requesting more characters than the string length, which returns the whole string without error.
- Passing
NULLas the string, which results inNULLoutput.
sql
/* Wrong: negative length causes error */ -- SELECT LEFT('Hello', -3); /* Correct: use positive length */ SELECT LEFT('Hello', 3) AS correct_left;
Output
correct_left
------------
Hel
Quick Reference
| Function | Description | Example | Result |
|---|---|---|---|
| LEFT(str, n) | Returns first n characters | LEFT('Apple', 3) | 'App' |
| RIGHT(str, n) | Returns last n characters | RIGHT('Apple', 2) | 'le' |
Key Takeaways
Use LEFT(string, number) to get characters from the start of a string.
Use RIGHT(string, number) to get characters from the end of a string.
Length must be a positive integer; negative values cause errors.
If length is longer than the string, the whole string is returned.
Passing NULL as string returns NULL.