The SQL LEFT() function returns the specified number of characters starting from the left side of a given character expression.
SQL LEFT Usage Notes
- The character expression as the first argument of the LEFT() function can be a constant string, a variable string, or a database column.
- Integer value, as the second argument of the LEFT() function, is a positive value. If the value is negative, an error returns.
- If the data type of character expression value is non-Unicode, the LEFT() function returns a varchar data type value. In the case of Unicode data type, it returns nvarchar data type value.
LEFT(character_expression, integer value)
SQL LEFT Examples
We will use the AdventureWorks2019 database for all the examples.
In the following example, the LEFT() function returns the given number of characters starting from the left side of the input character string.
SELECT LEFT('first 5 characters', 5) outputstring;
The query returns ‘first’ as the leftmost five characters in the literal string.
In the second example, we pass the FirstName column of the Person table as our first argument. The SQL LEFT() function returns the leftmost five characters of each FirstName column value.
/* Answer */ SELECT LEFT(FirstName, 5) firstname FROM Person.Person;
Next, let’s use LEFT() with an order by clause. We select the vendor name using SQL LEFT to select the leftmost six characters of the vendor name. The order by clause orders them in decreasing values of the credit ratings.
/* Answer */ SELECT LEFT(Name, 6) VendorName, CreditRating FROM Purchasing.Vendor ORDER BY CreditRating desc;
This query returns the six characters from the left side of every vendor’s name and orders them from highest to lowest credit rating.