Search code examples
mysqlsubquerywhere-clause

MySQL WHERE clause usage


MySQL I was trying to get values of category_id in between 9 to Maximum category id (use sub-query), without using Max function.

I tried the MySQL query given below. It works for the latter part, i.e. it gives category_id uptil maximum category_id. But, it gives all category ids from the very beginning (1), i.e. it does not start from '9'.

SELECT columns 
FROM table_name 
WHERE (9 <= category_id <=  (
                 SELECT category_id 
                 FROM table_name 
                 ORDER BY category_id 
                 DESC LIMIT 1 )
       );

Solution

  • Logically your query is

    SELECT { columns }
    FROM table_name 
    WHERE 9 <= category_id;
    

    Your condition which uses subquery makes no sense - column value cannot be greater than maximal value in this column.