MySQL - LEFT() Function



The MySQL LEFT() function accepts a string value and a numerical value (say N), and returns the specified string up to N characters from left to right.

This function is useful when you want to extract a certain number of characters from the left end of a string. It can be used in various scenarios such as extracting a file extension, area code or any other text string from the left end of the string.

Syntax

Following is the syntax of MySQL LEFT() function −

LEFT(str,len)

Parameters

This function takes a string and a specified number of characters as parameter.

Return Value

This function returns the leftmost portion of the string with the specified length.

Example

In the following example, we are extracting the first 5 characters from the left side of the string 'TUTORIALSPOINT' −

SELECT LEFT('TUTORIALSPOINT', 5);

Following is the output of the above code −

LEFT('TUTORIALSPOINT', 5)
TUTOR

Example

If the second argument provided to this function is greater than the length of the given string, it returns the string without any changes −

SELECT LEFT('TUTORIALSPOINT', 20);

The output obtained is as follows −

LEFT('TUTORIALSPOINT', 20)
TUTORIALSPOINT

Example

When the second argument is a negative value, the function returns an empty string −

SELECT LEFT('TUTORIALSPOINT', -4);

We get the output as follows −

LEFT('TUTORIALSPOINT', -4)

Example

If any of the arguments passed to this function is NULL, it returns NULL −

SELECT LEFT(NULL, 5);

The result produced is as shown below −

LEFT(NULL, 5)
0x

Example

You can also pass numerical values to this function −

SELECT LEFT(763275825171, 6);

The result produced is as shown below −

LEFT(763275825171, 6)
763275

Example

You can also pass the name of a table column to this function and print the desired characters in it.

Let us create a table named "EMP" and insert records into it using CREATE and INSERT statements as shown below −

CREATE TABLE EMP(
   FIRST_NAME  CHAR(20) NOT NULL,
   LAST_NAME  CHAR(20),
   AGE INT,
   INCOME FLOAT
);

Now, let us insert records into it using the INSERT statement −

INSERT INTO EMP VALUES 
('Krishna', 'Sharma', 19, 2000),
('Raj', 'Kandukuri', 20, 7000),
('Ramya', 'Ramapriya', 25, 5000),
('Mac', 'Mohan', 26, 2000);

The EMP obtained is as follows −

FIRST_NAME LAST_NAME AGE INCOME
Krishna Sharma 19 2000
Raj Kandukuri 20 7000
Ramya Ramapriya 25 5000
Mac Mohan 26 2000

Following query retrieves first 3 characters in the column 'FIRST_NAME' using the LEFT() function −

SELECT FIRST_NAME, LAST_NAME, AGE, LEFT(FIRST_NAME, 3) as RESULT 
FROM EMP;

After executing the above code, we get the following output −

FIRST_NAME LAST_NAME AGE LEFT(FIRST_NAME, 3)
Krishna Sharma 19 Kri
Raj Kandukuri 20 Raj
Ramya Ramapriya 25 Ram
Mac Mohan 26 Mac
mysql-left-function.htm
Advertisements