MySQL LEFT() String Function



MySQL LEFT() String Function

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.


Syntax

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.

Example MySQL LEFT() String Function

Let's look at some examples of the MySQL LEFT() string function:

Step 1: Using the Database

USE mydatabase;

This query sets the context to the database named mydatabase.

MySQL USE DATABASE

Step 2: Creating a Table

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.

MySQL CREATE TABLE

Step 3: Inserting Initial Rows

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.

MySQL INSERT INTO TABLE

Step 4: Using LEFT() with WHERE Clause

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.

MySQL LEFT() WITH WHERE CLAUSE

Step 5: Using LEFT() with Multiple Columns

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.

MySQL LEFT() WITH MULTIPLE COLUMNS

Step 6: Using LEFT() with Constants

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'.

MySQL LEFT() WITH CONSTANTS

Conclusion

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.