hardcoded ID vs query

1.2k views Asked by At

There's situation when I have table named "status", which only contains ID (PK) and name (string, unique). Also, other table has reference to this status (e.g. status_id)

let's say, there's two statuses:

1 - status1
2 - status2

Now, I'd like to insert/update record in table2 (which has reference to status table). What is the best way to do it, should I hardcode ID of status that I'd like to set or should I query by name, then get ID and assign it after?

NOTES: this is also general programming question (no direct SQL queries). I was not able to find a tag for it.

3

There are 3 answers

1
Eray Balkanli On BEST ANSWER

If name is a column including unique values, you can use name field to get the ID and then use the ID. However, Usually the name column does not include unique values, so it is required to use other columns to receive only 1 id instead of multiple.

See the situation:

ID name
1  John White
2  John White

Here, if you use name field, you will get 2 different IDs returned which will cause an error. That's why you'll need another approach like:

..
where name = @name and dateOfBirth = @dob and MothersName=@mothersname

to make sure one unique id is being returned.

To sum up, if you are sure the name field includes unique values, use the field to get the ID instead of using the ID value hardcoded. Otherwise, you can try to create a key in the config file like "lookupid" and use its value instead of using the ID hardcoded still, will be better to maintain for the future.

0
user3439907 On

Hardcoding is never a good idea but depends on how often the value changes throughout the life of code...using the query is better

sql

1
Himanshu On

Name isnt the best choice to check whats the id its the opposite because name at most of the times (can be same general case) would result into duplicates leading to redundancy of rows as you proceed with adding new columns as well making it worst. better choice as always is the primary key of the table or unique column you can have a unique constraint on your column to deal with duplicates in case you want it to be used as for a search for an id