2

I'm trying to insert multiple rows whose values are not taken from an existing table but provided from outside along with a where condition using INSERT ... SELECT ... WHERE.

The following query is not working:

mysql> insert into `my_table` SELECT 1 as a, 2 as b, 3 as c from dual UNION ALL SELECT 4 , 5 , 6 from dual UNION ALL SELECT 7 , 8 , 9  from dual where 1>2 ;
Query OK, 2 rows affected (0.01 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> select * from my_table;
+---+---+------+
| a | b | c    |
+---+---+------+
| 1 | 2 |    3 |
| 4 | 5 |    6 |
+---+---+------+
2 rows in set (0.00 sec)

I want to query to not insert any row because the where condition is false. But, the where clause is applied only for the last select and 1st 2 selects are not affected by where clause.

How can I correct it?

Pankaj Singhal
  • 15,283
  • 9
  • 47
  • 86

1 Answers1

3

Just wrap the UNION ALL subqueries in a subquery so as to apply WHERE to the whole result set:

insert into `my_table` 
select a, b, c 
from (
   SELECT 1 as a, 2 as b, 3 as c 
   from dual 

   UNION ALL 

   SELECT 4 , 5 , 6 
   from dual 

   UNION ALL 

   SELECT 7 , 8 , 9  
   from dual ) as t
where a > b ;
Giorgos Betsos
  • 71,379
  • 9
  • 63
  • 98