P
P
PyotR3213ty542022-02-25 09:00:20
SQL
PyotR3213ty54, 2022-02-25 09:00:20

Why doesn't LENGTH accept a new column alias as an argument in SQL?

There is a table in the database:

id       first_name 
-------  ----------
3001     Пётр
3002     Василий
3003     Олег
3004     Дмитрий
3005     Евгений

I am writing an sql query that would display the phrase "Name is <here is the username>" and the length of this phrase:
select 'Name is ' || first_name as new_name, length('Name is ' || first_name) from table;

Conclusion:
Name is Пётр      | 12
Name is Василий   | 15
Name is Олег      | 12
...

I want to write a shorter query by making an alias to the first column and passing it to the length function parameter:
select 'Name is ' || first_name as new_name, length(new_name) from table;

One throws an exception:
"NEW_NAME": недопустимый идентификатор
 "%s: invalid identifier"

Is it possible to shorten the query length in this case? Why doesn't lenght accept a new column alias as an argument?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Michael, 2022-02-25
@PyotR3213ty54

Wrap in a subquery and everything will be OK

SELECT new_name, length(new_name) FROM (
  select 'Name is ' || first_name as new_name from table
);

Example (for MySQL)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question