Ahmad
Ahmad

Reputation: 214

MYSQL SELECT only if rows are less than 5

i have a table named iv6_posts i want to select records only if records are less than 5 rows it should be in one query

something like this:

   select IF((select count(*) from iv6_posts)<5,select * from iv6_posts,null)

Upvotes: 4

Views: 1046

Answers (1)

Alma Do
Alma Do

Reputation: 37365

You can't achieve that with plain WHERE since COUNT() is a group function and you can't use plain HAVING since it will group rows into one.

Instead you'll have to evaluate total count in distinct query and combine it with, for instance, CROSS JOIN:

SELECT
  iv6_posts.*
FROM 
  iv6_posts
    CROSS JOIN 
      (
       SELECT 
         COUNT(1) AS c
       FROM 
         iv6_posts
      ) AS init
WHERE
  c<5

Check the fiddle for it.

Upvotes: 1

Related Questions