sqlcmd.net validated sql reference
beginner string-processing MySQL MariaDB SQL Server PostgreSQL SQLite

Get The Length Of A String

Return the number of characters in a string using `LENGTH` or `LEN`.

Docker-validated Not currently validation-green

Get the character count of each product name

'Keyboard' has 8 characters, 'Mouse' has 5, and 'Monitor' has 7. The results are identical across engines for these inputs because none of the values have trailing spaces that would cause LEN() and LENGTH() to differ.

MySQL MariaDB PostgreSQL SQLite
Engine-specific syntax
Setup
CREATE TABLE products (id INT, name VARCHAR(50));

INSERT INTO
  products (id, name)
VALUES
  (1, 'Keyboard'),
  (2, 'Mouse'),
  (3, 'Monitor');
SQL
SELECT
  id,
  name,
  LENGTH (name) AS name_length
FROM
  products
ORDER BY
  id;
idnamename_length
1Keyboard8
2Mouse5
3Monitor7
SQL Server
Engine-specific syntax
Setup
CREATE TABLE products (id INT, name VARCHAR(50));

INSERT INTO
  products (id, name)
VALUES
  (1, 'Keyboard'),
  (2, 'Mouse'),
  (3, 'Monitor');
SQL
SELECT
  id,
  name,
  LEN (name) AS name_length
FROM
  products
ORDER BY
  id;
idnamename_length
1Keyboard8
2Mouse5
3Monitor7

SQL Server uses LEN() while other engines use LENGTH(). Results are identical for strings without trailing spaces.

Where this command helps.

  • measuring the length of text values for validation or reporting
  • ordering or filtering results by string length

What the command is doing.

MySQL, MariaDB, and PostgreSQL use LENGTH(string) to return the number of characters. SQL Server uses LEN(string), which also trims trailing spaces before counting. For byte length of multi-byte strings, use OCTET_LENGTH (MySQL/PostgreSQL) or DATALENGTH (SQL Server).