3

I am having a hard time understanding why the following query is not working?

select id,sold_dealer_id from myi_corporate where sold_dealer_id != 36;

When I do the following I am getting the result

select id,sold_dealer_id from myi_corporate where sold_dealer_id = 36;

However for != I am not getting the opposite results.

I am returning to psql after a long time after using MongoDB and might have forgotten the basics. Any suggestion is much appreciated

Sijan Shrestha
  • 313
  • 5
  • 15

3 Answers3

7

You can use != rather than the SQL standard operator <>, but I recommend using the latter. That has no influence on your problem though.

Your table must contain some NULL values in sold_dealer_id.

Now NULL = 36 is not true, but NULL <> 36 is also not true, so such lines are excluded from both query results.

You can use sold_dealer_id IS DISTINCT FROM 36 to get the opposite of sold_dealer_id = 36. That operator will treat NULL values as if they were normal values.

Laurenz Albe
  • 51,298
  • 4
  • 39
  • 69
2

You are getting the results because a null value will never match anything else. If you know you are going to have null values I would also exclude those from the result.

select id,
       sold_dealer_id 
from   myi_corporate 
where  sold_dealer_id = 36
and    sold_dealer_id is not null;


select id,
       sold_dealer_id 
from   myi_corporate 
where  sold_dealer_id != 36
and    sold_dealer_id is not null;

You can also do a quick search to find any with a null value

select id,
       sold_dealer_id 
from   myi_corporate 
where  sold_dealer_id is null;
Joe W
  • 1,039
  • 9
  • 20
-3

By using correct postgres-Syntax...

select id,sold_dealer_id from myi_corporate where NOT (sold_dealer_id = 36);

Postgres is a database, not a c-family programming language

https://www.techonthenet.com/postgresql/not.php with some examples

eagle275
  • 684
  • 5
  • 6
  • I tried that, did not work! Thanks though :). I am getting 195 result for a select query but no luck with NOT or != – Sijan Shrestha Nov 11 '19 at 16:10
  • FYI, it is a foriegn key, does it make a difference ? – Sijan Shrestha Nov 11 '19 at 16:13
  • Okay turns out something I am doing is wrong, I tried with a string field example select * from myi_corporate where NOT (company_reg_id = '9990000000000'); which seems to work but for that field which is an integer and a foreign key its not working , any solutions? – Sijan Shrestha Nov 11 '19 at 16:19
  • 5
    Although the SQL standard defines <> as the "not equals" operator, Postgres does support using != as well. Changing the condition to a negated equals condition won't change a thing. NOT (sold_dealer_id = 36) is the same as sold_dealer_id <> 36 which is the same as (sold_dealer_id != 36 –  Nov 11 '19 at 16:20