[Solved] LEFT JOIN statement is not like a subquery with NOT IN?

EverSQL Database Performance Knowledge Base

LEFT JOIN statement is not like a subquery with NOT IN?

Database type:

I have 2 simple tables USERS and ORDERS and I want to find USERS who don't have make any order. For each order I have a column userId filled. I write a simple query but she doesn't works...

The simple query :

select id from USERS where id not in (select userId from ORDERS);

Please note that USERS.id is a VARCHAR like ORDERS.userId.

Can someone explain that :

> select count(distinct userId) from ORDERS;
+------------------------+
| count(distinct userId) |
+------------------------+
|                   4261 |
+------------------------+
1 row in set (0.04 sec)

> select count(distinct id) from USERS;
+--------------------+
| count(distinct id) |
+--------------------+
|              14960 |
+--------------------+
1 row in set (0.00 sec)

> select id from USERS
> where id not in (select userId from ORDERS);
Empty set (0.47 sec)

I have more users than order's users but THE SET IS EMPTY !!! It must be 14960-4261=10699

But when I do that :

> select count(*)
> from USERS left join ORDERS on ORDERS.userId=USERS.id
> where ifnull(ORDERS.userId,'')='';
+----------+
| count(*) |
+----------+
|    10700 |
+----------+
1 row in set (0.14 sec)

It's OK !!! There is just an error for 1 line (propably due to a null or 0 or empty value...)

Maybe I'm tired but after that... I feel like I do not understand anything to MySQL... !!

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
  2. Replace In Subquery With Correlated Exists (modified query below): In many cases, an EXISTS subquery with a correlated condition will perform better than a non correlated IN subquery.
Optimal indexes for this query:
ALTER TABLE `ORDERS` ADD INDEX `orders_idx_userid` (`userId`);
The optimized query:
SELECT
        USERS.id 
    FROM
        USERS 
    WHERE
        NOT EXISTS (
            SELECT
                1 
            FROM
                ORDERS 
            WHERE
                (
                    USERS.id = ORDERS.userId
                )
        )

Related Articles



* original question posted on StackOverflow here.