2

trying to write a sql which will keep first N number of rows of a table and delete the rest. I'm have comeup with this sql but the its saying I can't use the count here. Please help me to re write the sql.

DELETE 
  FROM ZZ_TEST_FINTABLE
 WHERE PROCESS_INSTANCE = ( 
 SELECT MIN(B.PROCESS_INSTANCE) 
  FROM ZZ_TEST_FINTABLE B) 
   AND COUNT(PROCESS_INTANCE) > 9
user3396478
  • 176
  • 2
  • 13

3 Answers3

0

You should use HAVING instead of AND.

   DELETE 
   FROM ZZ_TEST_FINTABLE
   WHERE PROCESS_INSTANCE = ( 
                            SELECT MIN(B.PROCESS_INSTANCE) 
                             FROM ZZ_TEST_FINTABLE B
                            ) 
   HAVING COUNT(PROCESS_INTANCE) > 9

or this

    DELETE 
    FROM ZZ_TEST_FINTABLE A
    INNER JOIN ZZ_TEST_FINTABLE B ON A.PROCESS_INSTANCE= MIN(B.PROCESS_INSTANCE)
    HAVING COUNT(PROCESS_INTANCE) > 9
Karim Daraf
  • 226
  • 2
  • 9
0

Maybe this works for you (with Oracle DB)

DELETE FROM
    ZZ_TEST_FINTABLE 
WHERE
    PROCESS_INSTANCE NOT IN 
    (
        SELECT PROCESS_INSTANCE 
        FROM ZZ_TEST_FINTABLE 
        WHERE ROWNUM < 9
    );
Orhun D.
  • 589
  • 7
  • 14
0

You'll have to modify this for your table, but should work:

DELETE FROM myschema.mytable WHERE pkey NOT IN (SELECT pkey FROM myschema.mytable ORDER BY pkey FETCH FIRST 10 ROWS ONLY)
crig
  • 859
  • 6
  • 19