The left function provides a way to retrieve the first n (number you specify) characters from a string. One often use of this function is to extract dates from a string, although SQL Server does provide some better functions for getting dates. In this article, we will learn how to use left with SQL Server.
The basic syntax of a LEFT is as follows:
SELECT LEFT(string, n);
For this, we will be using docker. This is recommended for more than just using SQL Server. To find how to install docker go here: https://docs.docker.com/engine/install/
Now create a file called docker-compose.yml
and add the following.
version: "3.9"
services:
db:
image: "mcr.microsoft.com/mssql/server"
ports:
- 1433:1433
environment:
SA_PASSWORD: "Your_password123"
ACCEPT_EULA: "Y"
Open a terminal and go to the folder the file is located. Then run the following.
docker-compose up
If you are looking for another good reference, you can check here: https://docs.docker.com/samples/aspnet-mssql-compose/.
Let's try this on a table. We can create an employee table and insert some rows.
CREATE TABLE employees (
first_name VARCHAR (50) NOT NULL,
last_name VARCHAR (50) NOT NULL,
);
insert into employees (first_name, last_name)
values
('keith', 'holliday'),
('jon', 'doe'),
('jon', 'dane'),
('jane', 'done'),
('anna', 'smith');
Below is an example of extracting the first 3 characters from each of the employees last name. This could be use to construct a unique id or an email.
select
left(last_name, 3) as LastName
from employees e;
LastName |
---|
hol |
doe |
dan |
ket |