Using Len() in a Select Statement

By Damian Maclennen on 1 August 2001 | 15 Comments | Tags: Queries

Maya writes "My select statement returns a resultset with one field, 'ResultText'. I would like to get a length of that field. Is there a way in SQL to do it like in Visual Basic ?"

Yes Maya, there are two ways of doing this.

The first is the Len() function which works just like Visual Basic's Len() function.

Use Pubs

SELECT Title, Len(Notes) as LengthOfNotes from Titles

Will produce

The Busy Executive's Database Guide			101
Cooking with Computers: Surreptitious Balance Sheets	76
You Can Combat Computer Stress!				119
Straight Talk About Computers				91
Silicon Valley Gastronomic Treats			52
The Gourmet Microwave					72
The Psychology of Computer Cooking			NULL

As you can see, the Len of a NULL value is NULL.


If you try to use len() on a Text field, you will get an error Argument data type text is invalid for argument 1 of len function.

The answer to this is the Datalength() function which will return the length of any expression. This can be used on all data types including text, ntext, image and varbinary.

Hope that clears it all up.


Discuss this article: 15 Comments so far. Print this Article.

If you like this article you can sign up for our weekly newsletter. There's an opt-out link at the bottom of each newsletter so it's easy to unsubscribe at any time.

Email Address:

Related Articles

Using Dynamic SQL in Stored Procedures (7 March 2011)

Joining to the Next Sequential Row (2 April 2008)

Writing Outer Joins in T-SQL (11 February 2008)

Aggregating Correlated Sub-Queries (23 October 2007)

How to Use GROUP BY with Distinct Aggregates and Derived tables (31 July 2007)

How to Use GROUP BY in SQL Server (30 July 2007)

Returning Complex Data from User-Defined Functions with CROSS APPLY (11 June 2007)

Returning a week number for any given date and starting fiscal month (2 May 2007)

Other Recent Forum Posts

postal barcode (15 Replies)

Report spam here (951 Replies)

Database Diagram not showing relationship of table (2 Replies)

Report model security (1 Reply)

Single variable across multiple packages (2 Replies)

SQL uninstallation errors (2 Replies)

High number of pubications and subscribers (3 Replies)

More data extract - expert opinion (1 Reply)

Subscribe to

Weekly SQL Server newsletter with articles, forum posts, and blog posts via email. Subscribers receive our white paper with performance tips for developers. Articles via RSS Weblog via RSS

- Advertisement -