SQL Server LEFT() Function
The LEFT()
function in SQL Server extracts a specified number of characters from the left-hand side of a string. It's a very useful tool for working with text data and retrieving specific parts of strings.
LEFT(): Definition and Usage
LEFT()
is particularly helpful for extracting prefixes or initial parts of strings. You specify the string and the number of characters you want from the left. If the number of characters you request exceeds the string's length, the entire string is returned.
Syntax
Syntax
LEFT(string, number_of_chars)
Parameter Values
Parameter | Description |
---|---|
string |
The string from which you want to extract characters. This is required. |
number_of_chars |
The number of characters to extract from the left side of the string. If this number is larger than the length of the string, the entire string will be returned. This is required. |
Examples
Extracting Characters from a Literal String
This example extracts the first three characters ('SQL') from the string 'SQL Tutorial'.
Syntax
SELECT LEFT('SQL Tutorial', 3) AS ExtractString;
Output
SQL
Extracting Characters from a Column
This example extracts the first five characters from the 'CustomerName' column in a 'Customers' table (assuming such a table and column exist).
Syntax
SELECT LEFT(CustomerName, 5) AS ExtractString
FROM Customers;
Output
ExtractString
-------------
(The first five characters of each CustomerName will be displayed here.)
Extracting More Characters Than Exist
If you request more characters than are present, the entire string is returned.
Syntax
SELECT LEFT('SQL Tutorial', 100) AS ExtractString;
Output
SQL Tutorial