Search code examples
sybasenetezzacorrelated-subquery

Netezza correlated query


I am migrating from Sybase to Netezza and Netezza does not support this type of query. Can someone show me how to rewrite it?

UPDATE table1 t1 
SET t1.col1=t2.col1
FROM table2 t2
WHERE t1.col2=t2.col2
AND t2.col3=(SELECT MAX(t3.col3) FROM table2 t3 WHERE t3.col2=t1.col2);

Solution

  • This sort of correlated subquery will actually work in Netezza depending on your version.

    I happen to be running 7.2, and it works just fine.

    [nz@netezza ~]$ nzrev
    Release 7.2.0.3 [Build 42210]
    [nz@netezza ~]$ k^C
    [nz@netezza ~]$ set -o vi
    [nz@netezza ~]$ nzsql -d testdb
    Welcome to nzsql, the IBM Netezza SQL interactive terminal.
    
    Type:  \h for help with SQL commands
           \? for help on internal slash commands
           \g or terminate with semicolon to execute query
           \q to quit
    TESTDB.ADMIN(ADMIN)=> UPDATE table1 t1
    TESTDB.ADMIN(ADMIN)-> SET t1.col1=t2.col1
    TESTDB.ADMIN(ADMIN)-> FROM table2 t2
    TESTDB.ADMIN(ADMIN)-> WHERE t1.col2=t2.col2
    TESTDB.ADMIN(ADMIN)-> AND t2.col3=(SELECT MAX(t3.col3) FROM table2 t3 WHERE t3.col2=t1.col2);
    UPDATE 1
    TESTDB.ADMIN(ADMIN)=>
    

    Less recent versions (pre 7.1) won't handle that, though. Here is how you couldrewrite that particular case as a join rather than a correlated subquery.

    UPDATE table1 t1
    SET t1.col1=t2.col1
    FROM table2 t2,
       (
          SELECT col2,
             MAX(col3) col3
          FROM table2
          GROUP BY col2
       )
       t3
    WHERE t1.col2 = t2.col2
    AND t2.col2  = t3.col2
    AND t2.col3  = t3.col3;
    

    The documentation for v7.2.0 has this to say about correlated subquery support.

    If you choose to use correlated subqueries, keep in mind the following restrictions on the form and placement of correlated subqueries:

    You can use correlated subqueries in WHERE clauses.

    You can use correlated subqueries in inner join conditions and with the equal join condition operator.

    You can use correlated subqueries in mixed correlated expressions only in the following form:

        expr(corr_columA, corr_columnB,...) = expr(local_columnX, local_columnY,...)
    

    You cannot use correlated subqueries in SET operations (UNION, INTERSECT, EXCEPT, and MINUS).

    You cannot use correlated subqueries in aggregates with GROUP BY and HAVING clauses.

    You cannot use correlated subqueries in ORed clauses or in CASE/WHEN expressions.

    You cannot use correlated subqueries in IN lists. You cannot use correlated subqueries in SELECT lists.