简体   繁体   中英

How to resolve 'ambiguous column naming in select list' when 'select col, t.*' is used with an order by clause

This is related to: Why is selecting specified columns, and all, wrong in Oracle SQL?

The query:

select is_parent, animals.* from animals order by is_parent

throws the error:

[Error] ORA-00960: ambiguous column naming in select list

Which makes sense as is_parent is duplicated.

Can anyone tell me a simple fix for this, as the original query select is_parent, animals.* from animals is very nice and quick to return all other columns. I looked at this link but the technique to remove the ambiguity does not seem to apply.

Something you can try:

1) Use the table name (or its alias) in the ORDER BY clause:

SQL> select is_parent, animals.*
  2  from animals
  3  order by animals.is_parent;

no rows selected

2) Write your ordering clause based on the position of fields in your select list:

SQL> select is_parent, animals.*
  2  from animals
  3  order by 1;

no rows selected

3) Use an alias for explicitly written columns:

SQL> select is_parent as parent, animals.*
  2  from animals
  3  order by is_parent;

no rows selected

Each of these solutions may be more or less readable; the second is the easiest one, and seems to match you need to order by the "most important" fields. However, I would not recommend any of these in writing an application, using them only for one-shot queries.

Use a alias name. Like:

select is_parent as check_is_parent, animals.* from animals order by is_parent

you get is_parent column for two times, so its create ambiguity. Use alias Like :

select is_parent as is_parent1, animals.* from animals order by is_parent1

As there are 2 column names with the same name, so Oracle throws the error. Use an alias for the column name as

select is_parent as PARENT, animals.* from animals order by is_parent

Work for me.

I have managed to come up with a neat solution thanks to the very helpful comments and answers that say that I will confuse the compiler if I don't use an alias.

I find having to rename the columns cumbersome, for example, if I had selected more columns:

select is_parent, age, animals.* from animals order by is_parent, age

The quick and dirty solution is to tell Oracle to order using column numbers:

select is_parent, age, animals.* from animals order by 1, 2

This removes the ambiguity in column names.

Why are you duplicating the column name as * will return all columns?

Either use this

select animals.* from animals order by is_parent

or explicitly type out all the columns

确保您没有重复列:

SELECT CAT,DOG,CAT FROM ANIMALS

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM