The MySQL LEFT()
string function returns a specified number of characters from the left side of a string. This function is essential for extracting substrings from the beginning of strings in SQL queries.
SELECT LEFT(string, number_of_characters) AS result
FROM table_name;
The LEFT()
function has the following components:
string
: The string from which to extract the substring.number_of_characters
: The number of characters to extract from the left side of the string.result
: An alias for the resulting substring.table_name
: The name of the table from which to retrieve the data.Let's look at some examples of the MySQL LEFT()
string function:
USE mydatabase;
This query sets the context to the database named mydatabase
.
Create a table to work with:
CREATE TABLE sample_strings (
id INT AUTO_INCREMENT PRIMARY KEY,
value VARCHAR(255) NOT NULL
);
This query creates a table named sample_strings
with columns for id
and value
.
Insert some initial rows into the table:
INSERT INTO sample_strings (value)
VALUES ('Hello world'),
('MySQL database'),
('String function'),
('Left example'),
('Test case');
This query inserts five rows into the sample_strings
table.
Use the LEFT()
function to extract a specified number of characters from the left side of a string:
SELECT value, LEFT(value, 5) AS left_value
FROM sample_strings;
This query retrieves the value
column from the sample_strings
table and returns the first 5 characters from the left side of the string.
Use the LEFT()
function with multiple columns:
SELECT id, value, LEFT(value, 7) AS left_value
FROM sample_strings;
This query retrieves the id
and value
columns from the sample_strings
table and returns the first 7 characters from the left side of the string.
Use the LEFT()
function with constants:
SELECT LEFT('Sample text', 6) AS left_constant;
This query extracts the first 6 characters from the left side of the constant string 'Sample text'.
The MySQL LEFT()
function is a powerful tool for extracting substrings from the beginning of strings in SQL queries. Understanding how to use the LEFT()
function is essential for effective data querying and manipulation in MySQL.