Enjoy Your SQL Riscriviamo le nostre NOT IN - Francesco Quaratino

Riscriviamo le nostre NOT IN

Un interessante post di Alexander Kuznetsov mette in guardia dall'uso di NOT IN ( ..., ...)  là dove nell'insieme di elementi confrontati sia presente almeno un NULL.

Rimandando la spiegazione del tutto all'eloquente post originale, riporto di seguito un esempio completo che dimostra l'osservazione di Kuznetso:


/*
    creo due tabelle temporanee
    la prima che contiene un set di due colonne (FirstName ,LastName)
*/

create table #t1 (
    FirstName varchar(20),
    LastName varchar(20)
)
go
insert #t1
    values
        ('David', 'Gilmour'),
        ('Nick', 'Mason'),
        ('Richard', 'Wright'),
        ('Roger', 'Waters'),
        ('Syd', 'Barrett')
go



/*
    la seconda che contiene un set della sola colonna (LastName)
*/

create table #t2 (
    LastName varchar(20)
)
go
insert #t2
    values
        ('Gilmour'), (NULL), ('Wright')
go



/*
    nessuna riga restituita per la presenza del NULL in #t2
*/

select
    FirstName, LastName
from
    #t1
where
    LastName NOT IN (select LastName from #t2)
go



/*
    OK perchè ho escluso i NULL
*/

select
    FirstName, LastName
from
    #t1
where
    LastName NOT IN (select LastName from #t2 where LastName IS NOT NULL)
go


/*
    clean temporary tables
*/
drop table #t1, #t2
go
 

Filed under: ,

Comments

# fdechirico said:

Eppure io quei cinque nomi li ho già sentiti ... :-)

martedì 28 ottobre 2008 11.39
# sgainz said:

"sentiti" è la parola giusta :-)

martedì 28 ottobre 2008 14.23