There's no good way to handle this if you write the SQL yourself.
You either have to add branches to your code, or use an abstraction layer.