The SQL Server LEFT() function returns a specified number of characters from the beginning (left side) of a character string. For example, SELECT LEFT('Microsoft', 4) returns Micr. This function is part of the standard string manipulation toolkit in T-SQL and is widely used for extracting prefixes, formatting codes, and parsing data.
What Exactly Does LEFT() Do?
LEFT() takes two arguments: the input string (or an expression that evaluates to a string) and the number of characters to extract. The syntax is:
LEFT ( character_expression , integer_expression )
The character_expression can be a string literal, a column of type char, varchar, nchar, nvarchar, or any data type that implicitly converts to a string (like int or date). The integer_expression specifies how many characters to take. If the integer is 0, an empty string is returned. If it is negative, an error is raised. If it is larger than the length of the string, the entire string is returned.
For Unicode data types (nchar, nvarchar), the function counts characters, not bytes. For non-Unicode types, it also counts characters, but be aware that if the string contains multi-byte characters (e.g., in a code page like UTF-8), the behavior may vary. In practice, most SQL Server installations use Unicode or single-byte collations, so this is rarely an issue.
How to Use LEFT() in Queries
The most common use is in a SELECT statement. Suppose you have a table Employees with a column FullName that stores names like ‘John Smith’. To get the first initial, you could write:
SELECT LEFT(FullName, 1) AS Initial FROM Employees;
You can also use it in a WHERE clause to filter rows based on a prefix. For example, to find all employees whose names start with ‘A’:
SELECT * FROM Employees WHERE LEFT(FullName, 1) = 'A';
However, for performance, using LIKE 'A%' is often better because it can leverage indexes, whereas LEFT() on a column prevents index usage. This is a key point to remember.
LEFT() vs. SUBSTRING() vs. RIGHT()
SQL Server offers several string functions. RIGHT() is the mirror image of LEFT(), returning characters from the end. SUBSTRING() is more flexible: it extracts a substring starting at any position and of any length. For example, SUBSTRING('abcdef', 2, 3) returns ‘bcd’.
When should you use which? Use LEFT() when you need a fixed number of characters from the start. Use RIGHT() for the end. Use SUBSTRING() when you need a middle portion or when the starting position is dynamic. In terms of performance, all three are similar, but LEFT() and RIGHT() are simpler to read.
Another function, STRING_SPLIT(), is for splitting strings into rows, not for extracting substrings. CHARINDEX() finds a position, which you might combine with SUBSTRING() to extract a variable-length part.
Common Use Cases and Examples
- Extracting area codes from phone numbers: If a phone number is stored as ‘555-1234’,
LEFT(Phone, 3)returns ‘555’. - Getting the first letter of a first name:
LEFT(FirstName, 1)gives the initial. - Truncating long text for display:
LEFT(Description, 100)shows only the first 100 characters. - Parsing fixed-width data: If a code has a two-letter country prefix,
LEFT(Code, 2)extracts it. - Creating abbreviated labels:
LEFT(ProductName, 10)might form a short label.
Here’s a more complete example using a derived table:
SELECT OrderID, LEFT(OrderDate, 7) AS YearMonth FROM Orders;
If OrderDate is a datetime, converting it to a string implicitly may produce a format like ‘2023-05-…’, so LEFT(OrderDate, 7) would give ‘2023-05’. This is a quick way to group by year-month, though using FORMAT() or date functions is more reliable.
Performance Considerations and Pitfalls
Using LEFT() on a column in a WHERE clause can cause a full table scan because the function must be applied to every row before comparison. If you frequently filter by prefix, consider using LIKE 'prefix%' or a computed column with an index. Also, be careful with data types: if you pass an integer to LEFT(), it will be implicitly converted to a string, but the conversion follows the default database collation, which might not be what you expect. For example, LEFT(12345, 2) returns ’12’ as a string, not a number.
Another pitfall is trimming. LEFT() does not trim spaces; it returns exactly the number of characters, including trailing spaces if the string is padded. For char columns, trailing spaces are included, so you might want to use RTRIM() first. For example, LEFT(RTRIM(LastName), 5) avoids getting spaces.
Finally, when the integer expression is a variable or column, ensure it is non-negative and of type int. A bigint value will be implicitly converted, but if it exceeds the range of int, you’ll get an arithmetic overflow error.
LEFT() in Different SQL Server Versions
The LEFT() function has been available since SQL Server 2000 and remains unchanged in all later versions, including SQL Server 2019, 2022, and Azure SQL Database. There is no difference in syntax or behavior across these versions. However, in Azure SQL Database and SQL Server 2022, you might also have access to LEFT_OPENJSON or other functions, but those are unrelated. The function is also compatible with older versions, so code using LEFT() is highly portable.
One subtle change: in SQL Server 2017 and later, the STRING_AGG function was introduced, but that doesn’t affect LEFT(). The function is deterministic, meaning it always returns the same result for the same inputs, which makes it safe for indexed computed columns.
Alternatives and Related Functions
If you need to extract from the right side, use RIGHT(). For a substring from anywhere, use SUBSTRING(). To find the position of a pattern, use CHARINDEX() or PATINDEX(). For splitting strings into parts, STRING_SPLIT() is available in SQL Server 2016 and later. If you need to remove characters from the start or end, LTRIM() and RTRIM() are useful, but they only remove spaces.
For more advanced parsing, you might combine LEFT() with CHARINDEX() to extract a variable-length prefix. For example, to get everything before the first space in a full name:
SELECT LEFT(FullName, CHARINDEX(' ', FullName + ' ') - 1) AS FirstName FROM Employees;
This adds a space to avoid an error when no space exists. Such patterns are common in data cleaning.
Frequently Asked Questions
Q: What does LEFT() return if the string is shorter than the specified length?
A: It returns the entire string. For example, LEFT('abc', 5) returns ‘abc’. No error is raised.
Q: Can I use LEFT() on a column of type INT?
A: Yes, SQL Server implicitly converts the integer to a string before applying LEFT(). However, the conversion uses the default database collation, which is fine for simple numbers. For example, LEFT(12345, 2) returns ’12’ as a string.
Q: Does LEFT() count characters or bytes for Unicode strings?
A: It counts characters. For nvarchar columns, each character is a Unicode code point, so LEFT(N'Hello', 2) returns N’He’. This is true even for supplementary characters (like emojis) in SQL Server 2012 and later, which use UTF-16.
Q: Is there a performance difference between LEFT() and LIKE for prefix search?
A: Yes. LIKE 'abc%' can use an index on the column, while LEFT(col, 3) = 'abc' cannot because the function must be evaluated for every row. For large tables, prefer LIKE.
Q: Can I use LEFT() in a computed column?
A: Yes, because it is deterministic. For example, you can create a computed column as LEFT(FullName, 1) and then index it if needed.
Q: What happens if the second argument is NULL?
A: The function returns NULL. Similarly, if the first argument is NULL, the result is NULL.
Related
- Data Entry Operator WFH: Real Jobs, Pay & How to Start
- Balloon with Number 1 Birthday: Meaning & Ideas
- Split String in Java 8: Methods and Examples
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- SUMIFS Excel Less Than: Criteria and ExamplesTo sum values in Excel only when a related value is less than a limit, use SUMIFS with…
- Excel Formula Showing Instead of Result? Causes and FixesIf Excel is showing a formula instead of its result, first check whether Show Formulas is turned on;…
- SUBSTITUTE Formula in Excel: Examples and UsesWith the text to edit in cell A2, use =SUBSTITUTE(A2,"-","") to remove every hyphen; if A2 contains INV-204-INV,…
- BMI Calculator for Excel: Formula, Setup, and TipsTo make a BMI calculator in Excel, enter height in centimeters in A2 and weight in kilograms in…
- XLOOKUP Wildcards: Examples, Rules, and Common FixesWith region names in A2:A6 and matching IDs in B2:B6, use =XLOOKUP("North*",A2:A6,B2:B6,"Not found",2) to return 101, the ID…
- Excel COUNTIF Range Examples: Text, Numbers, and DatesUse Excel’s COUNTIF function to count cells in a range that match one condition: for example, =COUNTIF(A2:A20,"East") counts…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.