In my server, which is connected to postgresql, should I check if the username already exists in the table by doing "select * ..." and then getting the number of rows in the resultset and i the number of rows is equal to zero, then insert the username?
Or just insert the username in the table. If it already exists, then it will throw an error which can then be caught.
Note:The username is the primary key
Doing which of the above two is better?
You should do the “try-and-catch exception” method simply because you have to do it anyway.
If you check first, there’s nothing to stop someone inserting a row for that user between your check and your insert, in which case the user will be in the table even though your check didn’t find it.
Short of being able to run the check-and-insert within some sort of transaction (so that nobody else can insert that user in the interim). you can’t be certain that the non-exception will work.
And although many DBMS’ provide transactional support, I don’t know of any that will lock a row you have yet to insert 🙂
Of course, if your application is designed in such a way that only your process will be inserting users (and serialised), you can use the check-first method. But I’d be putting in copious comments to the effect that it will need to be revisited if ever you scale up.