1

Assume I Have an SQL query like this

     SELECT player_name,weight,
     CASE WHEN weight > 250 THEN 'over 250'
          WHEN weight > 200 THEN '201-250'
          WHEN weight > 175 THEN '176-200'
        ELSE '' END AS weight_group
   FROM benn.college_football_players

I want to display the records which are not null(Weight not null) without disturbing the ELSE ' ',because that would cause so many unnecessary errors in the query,is there a workaround for this? I have used

    where weight_group is not null 

at the end,but it's throwing an error as 'Invalid Identifier'

Any other work around other than putting this entire select condition in another select statement?

2 Answers2

1

NULL is not equal to '' in MySQL. NULL means no data and empty string means empty string, they are two different things.

You need to filter data on the basis of empty string like

where weight_group != '';

Now you can achieve desired result in more than one way.

1. Using Sub-Query

SELECT * 
FROM (SELECT player_name,weight,
             CASE 
                WHEN weight > 250 THEN 'over 250' 
                WHEN weight > 200 THEN '201-250' 
                WHEN weight > 175 THEN '176-200' 
                ELSE '' 
            END AS weight_group 
      FROM benn.college_football_players) AS t 
WHERE weight_group != '';

2. Using Group By

SELECT player_name,weight,
         CASE WHEN weight > 250 THEN 'over 250'
              WHEN weight > 200 THEN '201-250'
              WHEN weight > 175 THEN '176-200'
              ELSE '' 
          END AS weight_group
FROM benn.college_football_players
GROUP BY weight_group, weight, player_name
HAVING weight_group != '';
Yousaf
  • 27,861
  • 6
  • 44
  • 69
0

You can add just where condition where weight > 175

SELECT player_name,weight,
 CASE WHEN weight > 250 THEN 'over 250'
      WHEN weight > 200 THEN '201-250'
      WHEN weight > 175 THEN '176-200'
    ELSE '' END AS weight_group FROM benn.college_football_players where weight > 175

Here else part not return any thing. Also you can use below code too

SELECT player_name,weight,
 CASE WHEN weight > 250 THEN 'over 250'
      WHEN weight > 200 THEN '201-250'
      WHEN weight > 175 THEN '176-200'
END AS weight_group FROM benn.college_football_players where weight > 175
Sabash
  • 127
  • 1
  • 5