How to use LEN in Sql Server

05.10.2022

Intro

The LEN function is a string helper function in SQL Server that returns the number of characters in a string. The length function takes characters, varchar, or text and will return the count for each of these. In this article, we will learn how to use length in SQL Server.

The Syntax

The basic syntax of a LEN is as follows:

SELECT LEN(string);
  • Where string is either a char, varchar or text field.

Getting Setup

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

Getting the Number of Characters

By default, the LEN function will return the number of characters in a string. Let's see a few examples.

select len('Hello');
length
5
select len(' ');
length
0
select len('♥');
length
1