1

I have a table

id(PK, AI)  name(UQ)
1             mike
2             ashly
3             nash

I want users are able to add new names. But if name already exists I don't want to add it again, and get the already existing name's id. If name does not exist I want new id of new name

I have tried many queries but none of them worked. That's why I am not going to write them here.

Thanks for help.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user3301042
  • 352
  • 2
  • 14
  • Just do a **Select * FROM Table Where name = ashly** if no results **Insert Into Table name = ashly** – code Jul 21 '15 at 16:52
  • I'm confused about what you want. You say that if `name` already exists, you don't want to get back the existing ID for that `name`, you want a new row with a new ID. But you indicate that the `name` column is constrained `unique` (I assume that is what `UQ` means). You cannot have two rows with the same `name` if that column is constrained with `UNIQUE`. – Dan Lowe Jul 21 '15 at 16:53
  • **You say that if name already exists, you don't want to get back the existing ID for that name,**. where did i said that? i said i want existing names id back – user3301042 Jul 21 '15 at 16:56
  • @code how i am gonna write **if no results** in sql? – user3301042 Jul 21 '15 at 16:57
  • If you get no results then you know you can insert this new name into your database – code Jul 21 '15 at 16:59

0 Answers0