SQL inline conditional in Select
6 answers
If you are using a database that supports them, then one of the easiest ways is to use a user defined function, then you will have
SELECT udfPreferredName() FROM users
where udfPreferredName()
will encapsulate the logic needed to choose between the name and alternative_name fields.
One of the benefits of using a function is that you can abstract away the selection logic and apply it across multiple SQL statements wherever you need it. Doing inline logic using a case is fine, but it will usually be (much) more difficult to maintain the system. In most DBMSs the additional overhead of a function call will not be significant unless you are handling very large tables.
0
source to share