Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL 'NOT IN' and subquery

I'm trying to execute this query:

SELECT mac, creation_date  FROM logs  WHERE logs_type_id=11 AND mac NOT IN (select consols.mac from consols) 

But I get no results. I tested it, and I know that there is something wrong with the syntax. In MySQL such a query works perfectly. I've added a row to be sure that there is one mac which does not exist in the consols table, but still it isn't giving any results.

like image 258
kskaradzinski Avatar asked Dec 11 '11 09:12

kskaradzinski


People also ask

WHERE Not Exists in Postgres?

The NOT EXISTS Operator in Postgres The NOT EXISTS operator can be defined as the opposite of the EXISTS operator. It will evaluate to true if the subquery returns no rows; otherwise, it evaluates to true .

What is <> in PostgreSQL?

<> is the standard SQL operator meaning "not equal". Many databases, including postgresql, supports !=

How do I write not a query in PostgreSQL?

Syntax: value NOT IN (value1, value2, …) The syntax for using NOT IN operator to return the matching values(except for the specified values) in contrast with the SELECT statement is as below: Syntax: value NOT IN (SELECT value FROM tbl_name);

How subquery works in PostgreSQL?

A subquery or Inner query or Nested query is a query within another PostgreSQL query and embedded within the WHERE clause. A subquery is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved.


1 Answers

When using NOT IN you should ensure that none of the values are NULL:

SELECT mac, creation_date  FROM logs  WHERE logs_type_id=11 AND mac NOT IN (     SELECT mac     FROM consols     WHERE mac IS NOT NULL -- add this ) 
like image 194
Mark Byers Avatar answered Sep 28 '22 00:09

Mark Byers