mysqlsqlsubqueryradians

Mysql query inside radians function not working. Why?


This works:

SELECT
    (
        radians(
            44.43763930
        )
    )

This doesn't:

SELECT
    (
        radians(
            SELECT
                latitude
            FROM
                coords
            WHERE
                coord_id = '1234'
        )
    )

I don't get it. Where is the problem ?

I try to cast the query result into decimal, but stil doesn't work.


Solution

  • Assuming that the subquery does return one row (not more), this works:

    SELECT radians( (SELECT latitude FROM coords WHERE coord_id = 1234) )
    

    The key is that the subquery needs to be surrounded with parentheses, so the database can understand it as a scalar subquery - that is, a query that returns one column and at most one row.

    Note, on the other hand, that the parentheses around radians() are unnecessary - in both queries.

    If the subquery returns more than one row, the query fails at runtime. In that case, you might want to switch to the more conventional phrasing:

    SELECT radians(latitude) FROM coords WHERE coord_id = 1234
    

    Note that I removed the single quotes around the literal value given to coord_id; it looks like a number, so it should be treated as such (if the column is of a string-like datatype, you can revert that change).