UPDATESQL

Unit 5, Checking AI-written SQL · Checking CASE and NULL

Checking AI-written SQL: following NULLs through a CASE

Check the AI: counting company names

A CASE sends each row to the first WHEN that is true. A row whose tested value is NULL matches no WHEN, because the comparison is unknown, and ends up in ELSE, or NULL if there is no ELSE. When an AI assistant writes a CASE, find the column it tests, check whether that column can be NULL, and follow those rows through. SUM of a CASE that gives 1 or 0 counts the rows that get 1.

Example
SELECT company,
       CASE WHEN company = '' THEN 'blank'
            ELSE 'has a value'
       END AS label
FROM signups;

Review the AI's query

Someone asked an AI assistant: How many sign-ups gave a company name? It wrote this query:

SELECT SUM(CASE WHEN company = '' THEN 0
                ELSE 1
           END) AS gave_company
FROM signups;

Does it answer the question?

  • Yes, it answers the question
  • No: the 8 sign-ups with no company (NULL) fall through to ELSE and are counted, and so is one that is only spaces
  • No: SUM cannot add up a CASE
Show the answer

No: the 8 sign-ups with no company (NULL) fall through to ELSE and are counted, and so is one that is only spaces. company = '' is unknown, not true, when company is NULL, so those 8 rows fall through to ELSE 1 and are counted as giving a company. The sign-up whose company is two spaces is not equal to '' either. The AI's 13 should be 4. Any CASE that tests a column that can be NULL needs to say what happens to the NULLs.

Then fix it

Now fix the query so it counts only sign-ups with a real company name. Keep the column name gave_company.

Tables you will use: signups

Try it in your browserFree, no sign-up. Your query is checked as you go.