Recently, I saw a mention of an interview question for SQL developers. It was something along the lines of:
So, how would you do it? Here’s my example.
First, the before look:
|
|
I think we can safely say that the sex column is somewhat back to front. My solution was to use the CASE
statement in an SQL UPDATE
command:
|
|
Finally, the after look:
|
|
It appears to be safe to commit!
Using the CASE
statement is useful. In the old days, we would need something like the following:
|
|
For huge tables, that could have taken a while, and it’s highly unlikely that a sex column would be indexed, so three full table scans would have been the order of the day.
Using CASE
we get away with a single scan, plus, the statement short circuits when it hits the first matching WHEN
clauses. So, if the first sex value was ‘F’ it would be changed to ‘M’ however it would then stop checking and would not change the newly set ‘M’ back to an ‘F’.