Name

LEFT()

Synopsis

LEFT(string, length)

This function returns the first length characters from a string. If you want to extract the end of the string instead of the beginning, use the RIGHT() function. Both are multibyte-safe. Here is an example:

SELECT LEFT(phone_home, 3) AS 'Area Code',
COUNT(*)
FROM students
GROUP BY LEFT(phone_home, 3);

Using the LEFT() function, this statement extracts the first three digits of phone_home for each row, which is the telephone area code (i.e., city code). It then groups the results, using the same function in the WHERE clause. This returns a count of the number of students living in each telephone area code.

Get MySQL in a Nutshell, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.