How LEFT() Works in MariaDB

In MariaDB, LEFT() is a built-in string function that returns a given number of characters from the leftmost part of a string.

LEFT() accepts two arguments; the string, and the number of characters to return from the left part of that string.

Syntax

The syntax goes like this:

LEFT(str,len)

Where str is the string, and len is the number of characters to extract from the left part of the string.

Example

Here’s a basic example:

SELECT LEFT('Aerospace', 4);

Result:

+----------------------+
| LEFT('Aerospace', 4) |
+----------------------+
| Aero                 |
+----------------------+

A Database Example

Here’s an example of getting the left part of the values in a database column:

SELECT 
    LEFT(ProductDescription, 15) AS "Short Desc",
    ProductDescription AS "Full Desc"
FROM Products;

Result:

+-----------------+-----------------------------------------+
| Short Desc      | Full Desc                               |
+-----------------+-----------------------------------------+
| Purple. Include | Purple. Includes left handed carry box. |
| Blue. Includes  | Blue. Includes right handed carry box.  |
| Approximate 45  | Approximate 45 minute waiting period.   |
| Approximate 30  | Approximate 30 minute waiting period.   |
| Wooden handle.  | Wooden handle. Free wine glasses.       |
| Orange. Include | Orange. Includes spare fingers.         |
| Tied with vines | Tied with vines. Very chewable.         |
| Brown ceramic w | Brown ceramic with solid handle.        |
+-----------------+-----------------------------------------+

See How to Truncate Text with an Ellipsis for an example of truncating text over a certain length, and adding an ellipsis to only the text that was truncated.

Null Arguments

If any (or all) of the arguments are null, the LEFT() function returns null:

SELECT 
    LEFT(null, 3),
    LEFT('Coffee', null),
    LEFT(null, null);

Result:

+---------------+----------------------+------------------+
| LEFT(null, 3) | LEFT('Coffee', null) | LEFT(null, null) |
+---------------+----------------------+------------------+
| NULL          | NULL                 | NULL             |
+---------------+----------------------+------------------+

Missing Arguments

Calling LEFT() without passing any arguments results in an error:

SELECT LEFT();

Result:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ')' at line 1