Tuesday 4 September 2018

The SQL query does not work as expected (from the beginner's point of view)

I am trying to get all the rows with the specific session_id and also that do not have '3223' for the group_with column. So I have this SQL statement :

SELECT * FROM pr_cart WHERE session_id=203130570714 AND group_with != 3223

Which to me it looks fine, but for some reason it does not return anything.
In my table I have entries that should not meet the criteria. i.e.
session_id=203130570714 | group_with=3225 which should be returned. session_id=203130570714 | group_with=NULL which should be returned. session_id=203130570714 | group_with=3223 which should not be returned.
I tried:
  1. <> instead of !=
  2. NOT (group_with=3223)
  3. group_with NOT LIKE '3223'
How can I get all the rows with the specified session_id and that also have a different number than 3223 for the group_with
edit session_id is varchar and group_with is int

NULL is a special value which you must take special care of:
SELECT * FROM pr_cart WHERE session_id="203130570714" AND
  (group_with != 3223 OR group_with IS NULL)

General recommendation

Basically all operations, which involve NULL as one operand, yield NULL as result.
SELECT NULL + 5; # NULL
SELECT NULL * 5; # NULL
SELECT NULL NOT IN (234); # NULL
SELECT 5 IN (NULL); # NULL

NULL will never be interpreted neither as true nor as false and is therefore literally useless for deciding if a row should be contained in the result set or not.
Whenever one has a column definition, which allows NULL values, one must take special care of these values.

0 comments:

Post a Comment