The LEFT() function in MySQL is used to extract a specified number of characters from the start (left) of a string.
Syntax
LEFT(string, number_of_chars)
Parameters
| Parameter | Description |
|---|---|
string |
Required. The string to extract characters from. |
number_of_chars |
Required. The number of characters to extract from the left of the string. |
Definition and Use
- Purpose: Returns the specified number of characters from the beginning of a string.
- Behavior:
- If
number_of_charsexceeds the length of the string, the entire string is returned. - If
number_of_charsis0, an empty string is returned.
- If
Usage Examples
Example 1: Basic Extraction
Extract 3 characters from the string "SQL Tutorial":
SELECT LEFT("SQL Tutorial", 3) AS ExtractString;
Output:
| ExtractString |
|---|
| SQL |
Example 2: Extraction from a Column
Extract the first 5 characters from the CustomerName column:
SELECT CustomerName, LEFT(CustomerName, 5) AS ExtractString
FROM Customers;
Output (example data):
| CustomerName | ExtractString |
|---|---|
| John Smith | John |
| Alice Brown | Alice |
Example 3: number_of_chars Exceeds String Length
Extract 15 characters from "SQL" (string length is 3):
SELECT LEFT("SQL", 15) AS ExtractString;
Output:
| ExtractString |
|---|
| SQL |
Explanation: The length of "SQL" is less than 15, so the entire string is returned.
Example 4: number_of_chars is 0
Extract 0 characters from "SQL Tutorial":
SELECT LEFT("SQL Tutorial", 0) AS ExtractString;
Output:
| ExtractString |
|---|
| (empty string) |
Technical Details
- Availability: Available from MySQL 4.0 onwards.
- Return Type: Returns a string with the extracted characters.
Applications
- Substring Extraction: Use
LEFT()to retrieve the beginning portion of strings. - Data Transformation: Extract prefixes, initials, or specific parts of text data.
- Formatting: Simplify or shorten strings for display or reporting.
Related Functions
- RIGHT(): Extracts characters from the end of a string.
- SUBSTRING(): Extracts a substring from a string starting at any position.
Key Notes
- Ensure
number_of_charsis a non-negative integer. Negative values result in an error. - For multi-byte characters (e.g., Unicode), ensure proper handling using character set configurations.
The LEFT() function is a versatile tool for extracting text from the beginning of strings, making it essential for text processing in MySQL.