How to Use the LEFT() Function in MySQL

Contents
In this article, you will learn how to use the LEFT() function in MySQL.
Using the LEFT() function in MySQL
In MySQL, the LEFT() function is used to extract a specified number of characters from the beginning of a string.
Syntax
LEFT(str, length);
Examples
Here are some examples of using the LEFT() function in MySQL:
Extracting the first N characters of a string
To extract the first N characters of a string, you can use the LEFT() function.
Syntax
SELECT LEFT(str, length);
Example
SELECT LEFT('Hello World', 5);
Output:
+------------------------+
| LEFT('Hello World', 5) |
+------------------------+
| Hello |
+------------------------+
In this example, the LEFT() function returns the first 5 characters of the string ‘Hello World’, which are ‘Hello’.
Extracting the first N characters of a column value
You can also use the LEFT() function to extract the first N characters of a column value.
Syntax
SELECT LEFT(column_name, length) FROM table_name;
Example
SELECT LEFT(name, 3) FROM employees;
Output:
+--------------+
| LEFT(name, 3) |
+--------------+
| Joh |
| Ann |
| Mic |
| Sara |
+--------------+
In this example, the LEFT() function returns the first 3 characters of the name column in the employees table.
Using the first N characters of a string in a WHERE clause
You can use the LEFT() function in a WHERE clause to filter records based on the first N characters of a string.
Syntax
SELECT * FROM table_name WHERE LEFT(column_name, length) = string_value;
Example
SELECT * FROM employees WHERE LEFT(name, 3) = 'Joh';
Output:
+----+------+--------+--------+
| id | name | salary | hire_date |
+----+------+--------+--------+
| 1 | John | 50000 | 2020-01-01 |
+----+------+--------+--------+
In this example, the SELECT statement returns all the records from the employees table where the first 3 characters of the name column are equal to ‘Joh’.