Search code examples
sqldatabasedb2delete-row

How to delete rows from a table with multiple select in DB2


I want to delete only the rows that the following statement returns, how can I do that?

  select usersernum,username,useremail 
    from core.appuser
   where usersernum in (
              select ch.usersernum
                from core.appusersession ch
               where ch.usersernum not in (
                          select usersernum
                            from (
                                       select max(starttime) as maxstarttime
                                            , usersernum
                                         from core.appusersession  vip
                                        where vip.starttime >= '2011-01-01 00:00:00'
                                     group by usersernum
                                 )
                     )
            group by usersernum
         )
order by useremail
       ;

Solution

  • Sometimes it helps to take a step back and ask yourself, What is the real goal here, in "business terms" or every-day language rather than SQL.

    Your query looks like it has a bunch of unnecessary layers. It appears that what you really want to do is remove any inactive users, meaning those who have not started a session since the beginning of 2011.

    DELETE  FROM core.appuser 
      WHERE usersernum NOT IN 
        ( SELECT DISTINCT usersernum
            FROM core.appusersession  
            WHERE starttime>='2011-01-01 00:00:00'
        );
    

    Isn't that much simpler?