Search code examples
sqlsubquerysap-asecorrelated-subquery

Can one use a correlated sub-query in Sybase ASE that has "TOP 1 column"?


I tried to use a proposed query on Sybase ASE 12, and it complained about syntax error.

SELECT 
    item, 
    ( SELECT TOP 1 tags.tag
      FROM #tags tags
        LEFT JOIN t o
          ON  tags.tag = o.tag
          AND o.item_id = n.item_id 
      WHERE o.tag IS NULL
      ORDER BY tags.tag
    ) 'tag',
    value  
FROM
    t_new n

ERROR: Incorrect syntax near the keyword 'top'.

However, the same query worked when I replaced (TOP 1 tag... ORDER BY tag) with MAX():

SELECT 
    item, 
    ( SELECT max(tags.tag)
      FROM #tags tags
        LEFT JOIN t o
          ON  tags.tag = o.tag
          AND o.item_id = n.item_id 
      WHERE o.tag IS NULL
        --  ORDER BY tags.tag
    ) 'tag',
    value  
FROM
    t_new n
  • Why is using (TOP 1 tag... ORDER BY tag) a problem in Sybase's correlated sub queries?

  • Is there any fix to the original query that does NOT use min()/max()?


Solution

  • Adaptive Server Enterprise version 12.5.3 supports the top n clause in outer query select statements, but not in the select list of a subquery. This differs from Microsoft SQL Server. Any attempt to use the top n clause with Adaptive Server in a subquery yields a syntax error.

    From the ASE 12.5.3 documentation here