0
0
MysqlHow-ToBeginner · 3 min read

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 number characters from the start of string.
  • RIGHT(string, number): Returns the last number characters from the end of string.

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 NULL as the string, which results in NULL output.
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

FunctionDescriptionExampleResult
LEFT(str, n)Returns first n charactersLEFT('Apple', 3)'App'
RIGHT(str, n)Returns last n charactersRIGHT('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.