Skip to content

Instantly share code, notes, and snippets.

@rpivo
Last active June 19, 2021 13:33
Show Gist options
  • Save rpivo/340bcb67aff8363c2444cc594c9141e4 to your computer and use it in GitHub Desktop.
Save rpivo/340bcb67aff8363c2444cc594c9141e4 to your computer and use it in GitHub Desktop.
Checking the Length of a String in a MySQL Where Clause

Checking the Length of a String in a MySQL Where Clause

Let's say we have a SQL schema like this:

Create table If Not Exists Tweets(tweet_id int, content varchar(50));
Truncate table Tweets;
insert into Tweets (tweet_id, content) values ('1', 'Vote for Biden');
insert into Tweets (tweet_id, content) values ('2', 'Let us make America great again!');

This will give us the following table:

tweet_id content
1 Vote for Biden
2 Let us make America great again!

If we wanted to select only the tweet_id's where the content length is greater than 15, we can use CHAR_LENGTH() in a WHERE clause.

SELECT tweet_id
FROM Tweets
WHERE CHAR_LENGTH(content) > 15;
tweet_id
2

Note that you can also use LENGTH() rather than CHAR_LENGTH, although CHAR_LENGTH() is more appropriate here. LENGTH() gets the length of the value in bytes, whereas CHAR_LENGTH() gets the length of the value in characters.

SELECT tweet_id
FROM Tweets
WHERE LENGTH(content) > 15;
tweet_id
2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment