Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()?

like image 579
DVK Avatar asked Feb 13 '13 18:02

DVK


People also ask

How correlated sub query can be applied in having clause?

A correlated subquery can also be used in the HAVING clause of an outer query. This construction can be used to find the types of books for which the maximum advance is more than twice the average within a given group.

What is difference between subquery and correlated subquery?

A noncorrelated (simple) subquery obtains its results independently of its containing (outer) statement. A correlated subquery requires values from its outer query in order to execute.

What makes a subquery correlated?

A correlated subquery is a subquery that refers to a column of a table that is not in its FROM clause. The column can be in the Projection clause or in the WHERE clause. In general, correlated subqueries diminish performance.

WHERE is correlated subquery used?

It is used whenever a subquery must return a different result or set of results for each candidate row considered by the main query. In other words, you can use a correlated subquery to answer a multipart question whose answer depends on the value in each row processed by the parent statement.


1 Answers

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

like image 95
Michael Gardner Avatar answered Sep 30 '22 02:09

Michael Gardner