Skip to content
Advertisement

RUN IF ELSE STATEMENT in MYSQL to run different querys

I need to run a query with an if else statement(if possible in MYSQL)

I want to: SELECT id FROM user_name_table WHERE user_name = @name;

If the result of the query returns null i want to insert @name to user_name_table and get the autoincrement generated id i need to store this result in a variable to use it later in another insert query.

This is as far as i got, in this case if “Sam” exists will return the ID twice, if not it will return ID and ‘0’

Advertisement

Answer

If you don’t want duplicates for name, then add a unique constraint or index:

Then, if you want to insert a new name, you can simply use:

This will return an error if there is a duplicate. If you don’t want an error, I would suggest:

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement