How to Use the MySQL LEFT() Function
In this tutorial, you'll learn how to use the MySQL LEFT() function. LEFT() returns a specified number of characters from the left of a given string.
MySQL LEFT() Syntax
The following is the syntax of the LEFT() function:
LEFT(string, length)
Remarks
- This function returns NULL if either string or length is NULL.
- If you want to extract characters from the right of a given string, you can use the RIGHT() function.
- If you want to extract characters from the string starting at the specified position, use the SUBSTRING() function.
Examples
Example 1
The following statement extracts 30 characters from the left of the string:
SELECT LEFT("If you want to learn more, here is the list of MySQL tutorials", 30) AS SubString;
Result:
If you want to learn more, her
Example 2
Below is our demo customers table:
customer_id | customer_code | customer_name | country |
---|---|---|---|
1 | #CID_40010 | Josh Warner | Japan |
2 | #CID_40011 | Lisa Ramsey | Japan |
3 | #CID_40012 | Clifton Christensen | Japan |
4 | #CID_40013 | Iris Wilkerson | United State |
5 | #CID_40014 | Charles Harmon | Japan |
6 | #CID_40015 | Glen Wood | United State |
7 | #CID_40016 | Francis Lewis | Germany |
8 | #CID_40017 | William Barnett | Germany |
The following statement extracts 6 characters from the left of the text in the customer_name column:
SELECT customer_name, LEFT(customer_name, 6) AS ExtractCustomerName
FROM customers
WHERE country = "United State";
Result:
customer_name | ExtractCustomerName |
Clifton Christensen | Clifto |
Charles Harmon | Charle |
Example 3
The following statements all return NULL:
SELECT LEFT(NULL, 4) AS SubString;
or:
SELECT LEFT(NULL, NULL) AS SubString;
or:
SELECT LEFT("If you want to learn more, here is the list of SQL tutorials", NULL) AS SubString;
As mentioned above, if either of both arguments is NULL, LEFT() returns NULL.
In this tutorial, you've learned how to use the MySQL LEFT() function to extract a specified number of characters from the left of a given string. If you want to extract characters from the right of the string, use the RIGHT() function. However, if you need to extract characters from the string starting at the specified position, use the SUBSTRING() function.