LEFT() in SQL
Extracts a specified number of characters from the beginning (left side) of a string.
Syntax
Return type
LEFT() Function Example
What is LEFT() in SQL?
The LEFT()
function in SQL extracts a specified number of characters from the beginning (left side) of a string. It is commonly used for parsing text data, extracting fixed-length identifiers, and formatting string outputs. This function is widely supported in SQL Server and some other database systems, while databases like MySQL and PostgreSQL use SUBSTRING()
for similar functionality. LEFT()
is useful in scenarios where only the first few characters of a string are needed, such as extracting country codes, abbreviations, or date segments from formatted text.
Parameters:
original_string: The string to perform replacements in
search_string: The substring to find and replace
replacement_string: The string to replace occurrences with
Example Use Cases:
-- Extract year from date string
-- Get first three characters of product code
-- Extract area code from phone number
Notes:
Behavior: Returns the entire string if the requested length exceeds the string length, returns an empty string for non-positive lengths, and counts spaces as characters.
Performance Considerations: Efficient for basic string operations
Version Info: Common function, but not available in all DBMS
Error Handling:
Error: Returns NULL if either parameter is NULL
Recommendation: Use COALESCE for NULL handling if needed
Supported Databases:
DBMS
Function / Syntax
Example
Behavior with NULL
MySQL
LEFT()
LEFT('Hello', 2)
Returns NULL
PostgreSQL
LEFT()
LEFT('Hello', 2)
Returns NULL
SQL Server
LEFT()
LEFT('Hello', 2)
Returns NULL
SQLite
LEFT()
LEFT('Hello', 2)
Returns NULL
BigQuery
LEFT()
LEFT('Hello', 2)
Returns NULL
Snowflake
LEFT()
LEFT('Hello', 2)
Returns NULL
Athena
LEFT()
LEFT('Hello', 2)
Returns NULL