Hi, In my database i have user table contains user_id,password,email. To insert a new row i am checking for the email.if email already exists i am generating error message the email already exist. Here my problem is i am interacting db twice. 1.select query returns true if user exists 2.insert data if select query returns false.
But i want this should happen in a single query. Can you tell me how to do it.
Originally posted by Purushothaman Thambu: One simple thing you can do is declare email as primary key. You don't have to fire the query to check if email already exists or not.
This is only a good idea is you know for certain that a user's email address will never change. Far safer is a surrogate key.
But i want this should happen in a single query.
Can't be done in a single query. Well, you could wrap the two steps up in a Stored Procedure, but then all you are doing is hiding that it has two steps. You could define a unique index on email and report the constraint violation to the user. However, this is using Exceptions as conditionals which is not usually considered a good thing to do. Your two query idea is probably the best way to handle this. If your email address has to be unique, I'd declare the constraint too.
INSERT INTO your_table (pk_col, col1, col2, ...) SELECT pk_val, val1, val2, ... FROM dual WHERE NOT EXISTS (SELECT 1 FROM your_table WHERE pk_col = pk_val1);
Where DUAL is a supplied table guaranteed to have one row. For other RDBMS you can create your own version.
If you wrap this in a stored procedure and return SQL%ROWCOUNT then this will be 1 if the insert succeded and 0 if it failed. And you are only hitting the database once in the stored procedure, and only making one network roundtrip. [ April 12, 2007: Message edited by: Chris Hendy ]