SQL Server LEFT() Function

The LEFT() function is a SQL Server function used to extract the characters on the left side of a string. Its syntax is very simple, requiring only the string to be processed and the number of characters to be returned. This function is often used in conjunction with other string functions to analyze and manipulate strings.

Syntax

LEFT(string, count)

Parameter explanation:

  • string: the string to be processed.
  • count: the number of characters to be returned.

Return value: returns the specified number of characters on the left side of the string.

Usage

The LEFT() function is widely used in SQL Server for processing text data. Here are some usage scenarios:

  • Extracting a specified number of characters from a string.
  • Comparing only the leftmost characters in a string comparison.
  • Processing date and time information contained in strings.
  • Extracting substrings from a string.

Examples

Here are two examples of using the LEFT() function:

Example 1

Assuming we have a table called employee that contains columns for first and last names, and we want to extract the first three characters from the last name column. We can use the following code:

SELECT LEFT(last_name, 3) as last_name_shortened
FROM employee;

Result:

last_name_shortened
Smi
Joh
Doe

Example 2

Assuming we have a string “2022-03-11 12:34:56” containing date and time information, and we want to extract the date. We can use the following code:

SELECT LEFT('2022-03-11 12:34:56', 10) as date

Result:

date
2022-03-11

Conclusion

The LEFT() function is one of the important functions in SQL Server for processing strings. It can be used to extract characters from the left side of a string and used in conjunction with other functions to process and analyze text data.