SELECT FORMAT(COUNT(1),’N’) FROM TableName WITH (NOLOCK);

9

December 26, 2023 by Kenneth Fisher

Alternate title: How do I tell how far I am on that command?

This little command (frequently with a WHERE clause) is a great way to tell how far along you are on any given command. Specifically, I’ve been running a bunch of DELETEs recently. I’ve got something like 5-50 million rows of data to delete and I’d like to know how far along I am. A common way to do this would be just a simple count.

SELECT COUNT(1) FROM TableName WHERE ToBeDeleted = 1;

Unfortunately, while the DELETE is running I’m not going to get a result. Blocking is a thing, which makes this one of the few times where NOLOCK is useful. I don’t need my results to be 100% accurate and I need to read some data while someone else is writing. So we run:

SELECT COUNT(1) FROM TableName WITH (NOLOCK) WHERE ToBeDeleted = 1;

And for years this is what I used. With lots of results like this:

And then some mental effort to add commas and I know I’ve got something like 23 million rows left. I’m tired, it’s a holiday, and mental effort is not my friend (James, Andrew, you didn’t see that last bit.) So I decided to try adding FORMAT.

SELECT FORMAT(COUNT(1),'N') FROM TableName WITH (NOLOCK) WHERE ToBeDeleted = 1;

I don’t know about y’all but I find that a LOT easier to read. And adding the FORMAT was not that hard. Yes, it added a decimal, but really, who cares?

9 thoughts on “SELECT FORMAT(COUNT(1),’N’) FROM TableName WITH (NOLOCK);

  1. JeffModen says:

    p.s. For a “onesy” like this, FORMAT is ok (Although I just flat avoid it to keep from developing a bad habit). Just don’t use it for lots of rows. See the following for why.

  2. JeffModen says:

    Eh… not sure why my first coded post didn’t show up. Add just one more character to get rid of the decimal places….

    SELECT FORMAT(COUNT(1),’N0′) FROM TableName WITH (NOLOCK) WHERE ToBeDeleted = 1;

  3. JeffModen says:

    @Ken,

    I submitted another post yesterday. I had a test data generator, some code, some and some run results. It also had a link to another article. It hasn’t shown up yet and I wonder if Akismet may have eaten it.

  4. Pete says:

    Also simple enough to put something like COUNT(1)/1000 or COUNT(1)/1000000 if you only want a rough count of a large number.

  5. Chad Estes says:

    For what it’s worth, you can modify the number of decimal places displayed by including an integer after the N such as this:

    SELECT FORMAT(COUNT(1),’N0’) FROM TableName WITH (NOLOCK)
    to display 23,521,401
    or
    SELECT FORMAT(COUNT(1),’N4’) FROM TableName WITH (NOLOCK)
    to display 23,521,401.0000

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 6,758 other subscribers

Follow me on Twitter

Archives

ToadWorld Pro of the Month November 2013