Say I have a db schema like this

```
user_id text
photo_id text
date_created timestamp

```

and I want to enforce a constraint that says "a user can only have 30 photos". A naive way to implement this would be to do

```
SELECT COUNT(*) FROM user_photos WHERE user_id='usr_123'

```

compare the result to 30, if it's lower, then do the insert. Naive because if you can trigger multiple requests in a short amount of time, you can win a race and end up writing more than 30 records.

Is there a way to enforce this constraint in the database? eg create some kind of index that says "only 30 rows can be inserted", or something? Is there a way to have a `count` column that increments separately for each userId, and you can limit its range to `0-29`?

If you used a transaction, would that lock the rows you read?