0

I have a table dbo.People in a database and one of the columns is Name. Some of the fields however are missing a Name value. So I am trying to replace the empty field with No Name. There is also an ID column with values 1, 2, 3, 4, and so on.

What I have so far:

SELECT ISNULL(Name, 'No Name') FROM dbo.People;

I then want to group and count how many times that name occurs

SELECT COUNT(ID), Name
FROM dbo.People
GROUP BY Name;

This works, however my result still shows a blank value with how many times that blank value occurs, rather than No Name.

8
  • 4
    you didn't use the ISNULL(Name, 'No Name' ) in your second query at all Commented Sep 14, 2018 at 7:09
  • 1
    Simply selecting on your first query doesn't change the underlying data at all. It only changes how you see the results after you run that SELECT. You need to use UPDATE if you want it changed forever, or include the ISNULL again on your 2nd query. Commented Sep 14, 2018 at 7:11
  • ISNULL() is not update NULL values. It just display as No Name.. Commented Sep 14, 2018 at 7:11
  • 3
    Your question aside, I can tell you you're probably making more trouble for yourself than if you left the names null (or even an empty string would be better, if you're not a fan of nulls). I've run across many a data set that contains things like -32768 for nulls or NaN when a null indicates that universally. Commented Sep 14, 2018 at 7:19
  • 1
    Use COALESCE() instead of that old ISNULL()... Commented Sep 14, 2018 at 7:22

3 Answers 3

4

I realised thanks to Squirrel and other commenters that the way I was typing the query was making it two separate queries.

The correct way I found was to combine them into one:

SELECT COUNT(ID), ISNULL(Name, 'No Name')
FROM dbo.People
GROUP BY Name;
Sign up to request clarification or add additional context in comments.

Comments

3

use case when

select sum(case when name='No Name' then 1 else 0 end) as cnt,name from
(
 SELECT coalesce(Name, 'No Name' ) as name
 FROM dbo.People
) t group by name

Comments

0

Do you only want to get the NULL occurences?

No need to overcomplicate things then, just remember that you cannot compare against a lack of value/data but you can check for it.

SELECT Count(ID) 
FROM dbo.People 
WHERE Name IS NULL

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.