In MySQL, the LEFT() function returns the leftmost characters from a string. The number of characters returned is determined by the second argument.
Syntax
The syntax goes like this:
LEFT(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 1 – Basic Usage
Here’s an example where I select the first 2 characters from a string:
SELECT LEFT('Forest', 2) AS Result;
Result:
+--------+ | Result | +--------+ | Fo | +--------+
Example 2 – Spaces
The function returns any spaces within the string (and includes them in its calculation). For example, if I add a leading space to the previous example, here’s the result:
SELECT LEFT(' Forest', 2) AS Result;
Result:
+--------+ | Result | +--------+ | F | +--------+
If this is undesirable, you can always use the TRIM() function to remove the space.
SELECT LEFT(TRIM(' Forest'), 2) AS Result;
Result:
+--------+ | Result | +--------+ | Fo | +--------+
Example 3 – Database Query
Here’s an example of how this function might look within 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 4 – NULL Arguments
The function returns NULL if any of the arguments is NULL. Here’s an example where the first argument is NULL:
SELECT LEFT(NULL, 5) AS Result;
Result:
+--------+ | Result | +--------+ | NULL | +--------+
And here’s an example where the second argument is NULL:
SELECT LEFT('Forest', NULL) AS Result;
Result:
+--------+ | Result | +--------+ | NULL | +--------+