SQL Server String LEFT() Function
SQL Server LEFT() Function
The SQL Server LEFT() function is used to extract a specified number of characters from the left side of a string. This function is useful for string manipulation tasks, such as extracting substrings from a larger string.
Syntax
SELECT LEFT(string, number_of_characters);
The LEFT() function takes two arguments:
- string: The string from which to extract characters.
- number_of_characters: The number of characters to extract from the left side of the string.
Example SQL Server LEFT() Function Queries
Let's look at some examples of SQL Server LEFT() function queries:
1. Basic LEFT() Example
SELECT LEFT('Hello World', 5) AS result;
This query extracts the first 5 characters from the string 'Hello World'. The result will be:
result
------
Hello
2. LEFT() with a Column
SELECT first_name, LEFT(first_name, 3) AS short_name
FROM employees;
This query extracts the first 3 characters from the first_name column for each employee. The result will show the first_name and the extracted substring as short_name.
3. LEFT() with a Variable
DECLARE @myString VARCHAR(50);
SET @myString = 'SQL Server';
SELECT LEFT(@myString, 3) AS result;
This query uses a variable to store a string and then extracts the first 3 characters from it. The result will be:
result
------
SQL
Full Example
Let's go through a complete example that includes creating a table, inserting data, and using the LEFT() function.
Step 1: Creating a Table
This step involves creating a new table named example_table to store some sample data.
CREATE TABLE example_table (
    id INT PRIMARY KEY,
    description VARCHAR(50)
);
In this example, we create a table named example_table with columns for id and description.
Step 2: Inserting Data into the Table
This step involves inserting some sample data into the example_table.
INSERT INTO example_table (id, description) VALUES (1, 'Apple');
INSERT INTO example_table (id, description) VALUES (2, 'Banana');
INSERT INTO example_table (id, description) VALUES (3, 'Cherry');
Here, we insert data into the example_table.
Step 3: Using the LEFT() Function
This step involves using the LEFT() function to extract characters from the description column.
SELECT id, description, LEFT(description, 3) AS short_description
FROM example_table;
This query retrieves the id, description, and the first 3 characters of the description column for each row in the example_table. The result will be:
id  description  short_description
--- ------------ ----------------
1   Apple        App
2   Banana       Ban
3   Cherry       Che
Conclusion
The SQL Server LEFT() function is a powerful tool for extracting a specified number of characters from the left side of a string. Understanding how to use the LEFT() function and its syntax is essential for effective string manipulation and data processing in SQL Server.
