SQL LEFT()

The SQL LEFT() function extracts a specified number of characters from the left side of a given string. This function is particularly useful when you want to retrieve the starting characters of a string, such as extracting initials, codes, or parts of text fields.

The LEFT() function is widely supported in SQL databases, including SQL Server, MySQL, and PostgreSQL.

In this tutorial, we will go through SQL LEFt() String function, its syntax, and how to use this function in SQL statements for string operations, with the help of well detailed examples.


Syntax of SQL LEFT() Function

The basic syntax of the SQL LEFT() function is:

</>
Copy
LEFT(string, number_of_characters);

Each part of this syntax has a specific purpose:

  • string: The string from which you want to extract characters.
  • number_of_characters: The number of characters to extract from the left side of the string.

The LEFT() function returns the specified number of characters from the start of the string.


Setup for Examples: Creating the Database and Table

We’ll create a sample customers table with fields customer_name, customer_code, phone_number, and customer_id to demonstrate the LEFT() function examples.

1. First, create a new database called business:

</>
Copy
CREATE DATABASE business;

2. Select the business database to work with:

</>
Copy
USE business;

3. Create a table named customers with fields customer_id, customer_name, customer_code, and phone_number:

</>
Copy
CREATE TABLE customers (
    customer_id INT PRIMARY KEY AUTO_INCREMENT,
    customer_name VARCHAR(50),
    customer_code VARCHAR(10),
    phone_number VARCHAR(15)
);

4. Insert sample data into the customers table to use with the LEFT() function examples:

</>
Copy
INSERT INTO customers (customer_name, customer_code, phone_number)
VALUES 
('John Doe', 'CUST001', '1234567890'),
('Jane Smith', 'CUST002', '2345678901'),
('Alice Johnson', 'ALC003', '3456789012'),
('Bob Martin', 'CUST004', '4567890123');