SQL: very slow negative queries
Problem
The SQL negative queries take forever.
- SELECT empno, salesqty, salesprice FROM sales WHERE not (sal.salestype = 'B');
- go
This due to the fact that the SQL engine always have to do a full table scan when having negative queries even if there is an index on that column.
Applies to
- IBM DB2
- Microsoft SQL Server
- Oracle Database 9i+
- I cannot give the usual data because small data sets are actually processed as table scans, since small tables are kept in memory.
- I had to run the query at a customer against a multi-gigabyte and multiple tables that are more than a million rows. That customer did not give me the authorization to display the data.
SQL transformation
- You should rewrite the SQL select query so that it becomes an AND/OR query. The rewriting of the select query is called a transformation.
- You should remove the NOT clause.
- ----------------------------- Commands Entered ------------------------------
- SELECT emp.empno, emp.firstnme, emp.lastname, sal.salesqty, sal.salesprice
- FROM employee emp, sales sal
- WHERE emp.empno = sal.empno
- and
- not (sal.salestype = 'B');
- ------------------------------------------------------------------------------
- Access PLAN:
- employee: TABLE scan: 57.69
- sales: TABLE scan: 129.23
- hsjoin: 186.92
- Total cost: 186.92
- Total TIME FOR execution: 1 mn 22 sec
Here is an alternative query with the same results.
- ------------------------------ Commands Entered ------------------------------
- SELECT emp.empno, emp.firstnme, emp.lastname, sal.salesqty, sal.salesprice
- FROM employee emp, sales sal
- WHERE emp.empno = sal.empno and
- sal.salestype in ('A','E','F','X','Z');
- ------------------------------------------------------------------------------
- Access PLAN:
- employee: TABLE scan: 57.69
- sales: TABLE scan: 63.34
- hsjoin: 121.03
- Total cost: 121.03
- Total TIME FOR execution: 46 sec
That's a 41% improvement!













