0

How can I rewrite

SELECT x, "noflowizts tidbits" AS n, z, bloflvopitz AS b

Just as

SELECT x,y,n,b

Then I could even write

SELECT x, CONCAT(n,z), y

For this one query, I simply want to have a clearer way of writing it, where I can rearrange the terms at ease without careful editing work.

It is great that we can declare aliases at the same time we SELECT them, but sometimes I would like to do it separately. Yes, all I need to affect is just this one query.

1
  • No, you can not use an ALIAS before you've defined it. Nor should you want to, because at some point someone else may have to read your code, and if they didn't know what those aliases pointed to, they couldn't make sense of the code. In fact, neither will you when you revisit it six months from now when you've been away from the code for a while. Don't work so hard on writing short code, and focus instead on writing good, easy to maintain code. A few keystrokes aren't worth the extra effort.
    – Ken White
    5 mins ago

1 Answer 1

0

You could rely on a common table expression (CTE), which allows defining the column aliases outside of the CTE code block itself. Consider:

WITH cte (a, b, c) AS (
    SELECT 1, 2, 3
)

SELECT a, b, c
FROM cte;

To change the alias names, you only need to modify the WITH clause itself, but the SQL code inside the CTE can remain the same.

Demo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.