Skip to content
Advertisement

“IS NOT NULL” not producing the required results in mySQL

I am trying to build a report based of my table. Here is my table:

enter image description here
Following is the SQL query to get desired results.

SELECT
  `user`,
  SUM(
    CASE
      WHEN `event_time` >= '2021-04-01 00:00:00'
      AND `event_time` <= '2021-04-16 23:59:59'
      AND `sub_status` = 'TB'
      THEN pause_sec
    END
  ) AS 'Training Break',
  SUM(
    CASE
      WHEN `event_time` >= '2021-04-01 00:00:00'
      AND `event_time` <= '2021-04-16 23:59:59'
      AND `sub_status` = 'SB1'
      THEN pause_sec
    END
  ) AS 'Short Break 1',
  SUM(
    CASE
      WHEN `event_time` >= '2021-04-01 00:00:00'
      AND `event_time` <= '2021-04-16 23:59:59'
      AND `sub_status` = 'SB2'
      THEN pause_sec
    END
  ) AS 'Short Break 2',
  SUM(
    CASE
      WHEN `event_time` >= '2021-04-01 00:00:00'
      AND `event_time` <= '2021-04-16 23:59:59'
      AND `sub_status` = 'LB'
      THEN pause_sec
    END
  ) AS 'Long Break'
FROM
  `vicidial_agent_log`
GROUP BY `user`

enter image description here
I am looking to exclude entries which have all null values and following is my syntax but it is not working and produces the same results.

FROM
  `vicidial_agent_log`
WHERE 'Training Break' IS NOT NULL
  AND 'Short Break 1' IS NOT NULL
  AND 'Short Break 2' IS NOT NULL
  AND 'Long Break' IS NOT NULL
GROUP BY `user`

Kindly help here or share a post that can help. I have been trying to find but

Advertisement

Answer

Don’t use single quotes for column names/aliases, because for example 'Training Break' in an expression like 'Training Break' IS NOT NULL is interpreted as a string literal which of course is not null.

In MySql you can use backticks to surround column names.

Also, the columns Training Break, Short Break 1, Short Break 2 and Long Break are the result of aggregate functions so they can’t be used in a WHERE clause. Instead use a HAVING clause.

Finally, since you want the rows where at least 1 of these columns is not null you should use the operator OR instead of AND:

FROM
  `vicidial_agent_log`
GROUP BY `user`
HAVING `Training Break` IS NOT NULL
    OR `Short Break 1` IS NOT NULL
    OR `Short Break 2` IS NOT NULL
    OR `Long Break` IS NOT NULL

Or:

FROM
  `vicidial_agent_log`
GROUP BY `user`
HAVING COALESCE(`Training Break`, `Short Break 1`, `Short Break 2`, `Long Break`) IS NOT NULL
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement