0

I have a table in a database that looks as follows (parent_id is a fk to the same table):

+----+-----------+---------+
| id | parent_id | enabled |
+----+-----------+---------+
|  1 | null      |       1 |
|  2 | 1         |       1 |
|  3 | null      |       1 |
+----+-----------+---------+

The query:

SELECT * FROM category WHERE parent_id = 1

returns rows successfully as I would expect, however

SELECT * FROM category WHERE parent_id != 1

returns nothing.

1
  • You should read this and then you'll have a better understanding on handling nulls. Commented Feb 3, 2017 at 10:43

1 Answer 1

3

The correct query about NULL value is the following:

SELECT * FROM category
WHERE parent_id IS NULL OR parent_id != 1

If you try to check is a NULL field is != by a value, it return always false (unknown for precision)

Sign up to request clarification or add additional context in comments.

2 Comments

For goodness sake, I totally forgot you cannot use equality on null. I knew it was something daft I had overlooked. #facepalm
@Unflux: It happens ;) Have a nice day

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.