MySQL LEFT() Function with Examples

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_idcustomer_codecustomer_namecountry
1#CID_40010Josh WarnerJapan
2#CID_40011Lisa RamseyJapan
3#CID_40012Clifton ChristensenJapan
4#CID_40013Iris WilkersonUnited State
5#CID_40014Charles HarmonJapan
6#CID_40015Glen WoodUnited State
7#CID_40016Francis LewisGermany
8#CID_40017William BarnettGermany

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 ChristensenClifto
Charles HarmonCharle

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.


See also:
MySQL LIKE Operator Pattern Matching and Examples
MySQL SUBSTRING_INDEX Function with Examples
MySQL EXISTS Operator with Examples
MySQL ROW_NUMBER Function with Examples
MySQL CONCAT() Function | Concatenate Strings in MySQL

Leave a Comment