My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Can you limit the number of rows per user just by using SQL?

Lila Fowler's photo
Lila Fowler
·Feb 4, 2019

Hi everyone :)

I've got a small issue with my code...

Say you want to limit the amount of messages a user can send on your website... I'd typically do this by using PHP, in pseudo-code:

SELECT messages FROM table WHERE user_id = 123
if messages > 10, return 'message limit reached'
else, INSERT message INTO table

But I'm wondering if this can be done purely with SQL in MySQL, something like this, in pseudo-code:

INSERT message INTO table if messages < 10 where user_id = 123

This is my best try, but I keep receiving a syntax error...

INSERT INTO message_user_map 
(user, 
 (select count(user) 
  FROM product_image_map 
  WHERE user='123') < 10) 
VALUES ('123', 'hey! this is a new message!')

Can anyone give me a tip on how to correct this statement?