Wednesday, December 25, 2024

SQL Server LEFT() Function

 The LEFT() function in SQL Server is used to extract a specified number of characters from the start (left side) of a string.

Syntax

LEFT(string, number_of_characters)

Parameters

  • string: The string from which to extract characters.
  • number_of_characters: The number of characters to extract from the start of the string.

Example Usage

Basic Example

SELECT LEFT('Hello World', 5) AS Result;

Result:

Hello

Using LEFT() with a Table Column

Suppose you have a table named Employees with a column FullName:

SELECT FullName, LEFT(FullName, 3) AS FirstThreeChars
FROM Employees;

This will extract the first 3 characters from each name in the FullName column.

Combining with Other Functions

You can use LEFT() with other string functions:

SELECT LEFT('SQL Server', CHARINDEX(' ', 'SQL Server') - 1) AS FirstWord;

Here, it extracts the first word (SQL) by finding the position of the first space and using it to determine the number of characters.

Handling Edge Cases

  • When number_of_characters is greater than the string length:
    The entire string is returned.

    SELECT LEFT('Short', 10) AS Result;
    

    Result: Short

  • When number_of_characters is 0:
    An empty string is returned.

    SELECT LEFT('Hello', 0) AS Result;
    

    Result: `` (empty)

  • When number_of_characters is negative:
    An error occurs.

Practical Applications

  • Extracting specific parts of a string, such as initials or abbreviations.
  • Formatting data for reports or displays.
  • Cleaning and processing data in ETL pipelines.

Would you like further examples or guidance?

No comments:

Post a Comment