LEFT() in SQL

Extracts a specified number of characters from the beginning (left side) of a string.

Syntax

LEFT(string, number_of_characters)
Return type
string: The input string to extract from
number_of_characters: Number of characters to extract from the left

LEFT() Function Example

SELECT LEFT('Hello World', 5);
-- Output: 'Hello'

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

SELECT LEFT(date_column, 4) AS year FROM events;
-- Output:
date_column         year
-----------------  ----
2024-03-15         2024
2023-12-31         2023
2024-01-01         2024
2023-06-30         2023
2024-09-15         2024

-- Get first three characters of product code

SELECT LEFT(product_code, 3) AS product_category FROM products;
-- Output:
product_code    product_category
-------------   ----------------
LAP10023        LAP
MON30045        MON
KEY20089        KEY
MOU40012        MOU
CAB50067        CAB

-- Extract area code from phone number

SELECT LEFT(phone_number, 3) AS area_code FROM contacts;
-- Output:
phone_number        area_code
-----------------  ----------
555-123-4567       555
212-555-7890       212
415-555-1234       415
650-555-9876       650
408-555-3333       408

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

Related Functions:

One place for all your queries,
directly on your SQL editor