[TL;DR] Your main issue is that you appear to be putting the table aliases after the column name where an alias for the column is expected when they should be prefixing the column name to identify which table the columns belong to.
Your query is equivalent to:
select productversion AS columnalias1,
productName AS columnalias2,
productDate AS columnalias3,
comments AS columnalias4,
status AS columnalias5
from table1 t1,
table2 t2
where t1.productVersion = t2.productversion
And all your column aliases are either t1 or t2 so you will get multiple columns with the same name. I do not think this is what you intended as both tables have a productVersion column so the query parser does not know which you intended to use. You probably want the table aliases before the column name to identify which table each column is from:
select t1.productversion,
t1.productName,
t1.productDate,
t2.comments,
t2.status
from table1 t1,
table2 t2
where t1.productVersion = t2.productversion
The second problem is that, while you say it is a query «without joins», you are using a legacy Oracle comma-join syntax and your query can be rewritten to have exactly the same functionality using ANSI/ISO SQL syntax and is equivalent to:
select t1.productversion,
t1.productName,
t1.productDate,
t2.comments,
t2.status
from table1 t1
INNER JOIN table2 t2
ON ( t1.productVersion = t2.productversion )
If you want something without joins then use UNION ALL:
SELECT productVersion,
productName,
productDate,
NULL AS Comments,
NULL AS status
FROM table1
UNION ALL
SELECT productVersion,
NULL AS productName,
NULL AS productDate,
Comments,
status
FROM table2
But it will not correlate the values in the two tables.
I am using PostgreSQL as my database. And I need to create an entry in the database, and if it’s already exists, just update its fields, but one of the fields should be updated only if it’s not set.
I’ve used info from this question: https://stackoverflow.com/questions/13305878/dont-update-column-if-update-value-is-null, it’s quite related to what I have.
I tried to use this query, but when I run it, it errors with Column reference 'affiliate_code' is ambiguous:
INSERT INTO accounts (id, token, affiliate_code)
VALUES (value1, value2, value3)
ON CONFLICT (id) DO
UPDATE SET token = value2,
affiliate_code = COALESCE(affiliate_code, value3);
(the real values are substituted, of course).
If I replace affiliate_code = COALESCE(affiliate_code, value3) with affiliate_code = value3, everything works, but not in the way I want it to work.
How can I make this work?
Here is how my table is defined:
CREATE TABLE accounts (
id VARCHAR NOT NULL UNIQUE,
token VARCHAR NOT NULL,
affiliate_code VARCHAR
);
Содержание
- Solved: SQL ambiguous column name [100% Working]
- What is an ambiguous column name error in SQL?
- What is the cause of this error?
- According to Oracle documents
- ORA-00918 column ambiguously defined
- Example of SQL ambiguous column name
- Solve the “Ambiguous Column Name” Error in SQL
- Summary
- References
- Read More
Solved: SQL ambiguous column name [100% Working]
Table of Contents
What is an ambiguous column name error in SQL?
SQL ambiguous column name is one most common error we are facing while performing a join query with two or more tables, this type of error occurs when we try to retrieve data from two or more tables using SQL join and more than one tables have the same column name appears in the selection.
What is the cause of this error?
The root cause of this error is the same column name in two or more tables and selecting the same column with the same name when performing a join
According to Oracle documents
ORA-00918 column ambiguously defined
- Cause of error: When the same column name exists in more than one table in a join than one table and is thus referenced ambiguously.
- Action: To overcome this error we need to prefix references to column names that exist in multiple tables with either the table name or a table alias and a period (.),
Example of SQL ambiguous column name
Create two tables for patient and doctor as follow
patient_table(patient_id,patient_name,doctor_id,city)
| patient_id | patient_name | doctor_id | city |
|---|---|---|---|
| 101 | Rekha | 11 | Surat |
| 102 | Reema | 12 | Vapi |
| 103 | Jaya | 13 | Navasari |
doctor_table(doctor_id,doctor_name,city)
| doctor_id | doctor_name | city |
|---|---|---|
| 11 | Rahul | Surat |
| 12 | Prashant | Vapi |
| 13 | Asif | Navasari |
Next create PATIENT Table
Next create DOCTOR Table
Example 1: Write SQL query to display all patient data with doctor id and doctor city name
- In the above query, we used an inner join between two tables patient and doctor to retrieve data from both the tables
- In the above query we specify city and doctor_id columns, both the columns are common in both the tables so we will get an ambiguous error for both the columns
OUTPUT: 
Error Message :
Solve the “Ambiguous Column Name” Error in SQL
To solve the ambiguous column name error we need to prefixed column name by its table name when referenced with the SQL select statement, the column should be referenced as TABLE.COLUMN or TABLE_ALIAS.COLUMN
Example 2 : Write SQL query to display all patient data with doctor id and doctor city name , also specify table name with column name in the SQL select statement
OUTPUT:
Summary
In this article on SQL ambiguous column names, we have covered what is ambiguous column name error in SQL, the cause of ambiguous column name error, how this error explained in oracle document ORA-00918 and also explained SSQLambiguous column name error with practical examples.
References
Read More
Related Keywords: ambiguous column name join, sql ambiguous column name, ambiguous column name, ambiguous column name sql, column reference is ambiguous, ms sql ambiguous column name, sql query ambiguous column name
Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud
If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

For any other feedbacks or questions you can either use the comments section or contact me form.
Thank You for your support!!
to stay connected and get the latest updates
Источник
Здравствуйте! Помогите пожалуйста разобраться. Есть таблица RELATIONSHIP в базе данных PostgreSQL, где столбцы STATUS и SEND по умолчанию имеют значение false.
| SURVEY_ID | EMPLOYEE | STATUS (default: false) | SEND (default: false) | ORGANIZATION_NAME |
|--------------------------------------|----------|-------------------------|-----------------------|-------------------|
| d5f9c639-13e6-42c1-9043-30783981724b | Mark | false | false | Apple |
| d5f9c639-13e6-42c1-9043-30783981724b | Bob | true | false | Google |
У меня есть процедура, которая выглядит следующим образом:
CREATE OR REPLACE PROCEDURE creator(SURVEY_IDENTIFIER uuid, EMPLOYEES VARCHAR[], ORGANIZATION_NAMES VARCHAR[]) AS $FUNCTION$
BEGIN
INSERT INTO RELATIONSHIP (SURVEY_ID, EMPLOYEE, ORGANIZATION_NAME)
SELECT
SURVEY_IDENTIFIER AS SURVEY_ID,
EMPLOYEE FROM UNNEST(ARRAY[EMPLOYEES], ARRAY[ORGANIZATION_NAMES]) u(EMPLOYEE, ORGANIZATION_NAME)
ON CONFLICT ON CONSTRAINT RELATIONSHIP_UNIQUE_KEY
DO UPDATE SET ORGANIZATION_NAME = u.ORGANIZATION_NAME
WHERE NOT STATUS;
END;
$FUNCTION$ LANGUAGE plpgsql;
Суть процедуры следующая:
1) Если значения, которые мы хотим добавить в таблицу уникальные в рамках столбцов SURVEY_ID и EMPLOYEE необходимо их записать в таблицу.
2) Если значения, которые мы хотим добавить в таблицу не уникальные в рамках столбцов SURVEY_ID и EMPLOYEE, то не нужно их добавлять в таблицу. При этом нужно обновить значение столбца ORGANIZATION_NAME в случаи, если значение в столбце STATUS у существующей записи равна false.
CALL creator(
'd5f9c639-13e6-42c1-9043-30783981724b',
ARRAY['Mark', 'Bob', 'Kate'],
ARRAY['Google', 'Google', 'HP']
);
Другими словами, вызвав данную процедуру следующим образом, я предполагал следующий результат:
| SURVEY_ID | EMPLOYEE | ORGANIZATION_NAME | STATUS (default: false) | SEND (default: false) | ORGANIZATION_NAME |
|--------------------------------------|----------|-------------------|-------------------------|-----------------------|-------------------|
| d5f9c639-13e6-42c1-9043-30783981724b | Mark | Google | false | false | Google |
| d5f9c639-13e6-42c1-9043-30783981724b | Bob | Apple | true | false | Apple |
| d5f9c639-13e6-42c1-9043-30783981724b | Kate | HP | false | false | HP |
При попытке вызова процедуру вышеупомянутым способом появляется ошибка:
SQL Error [42601]: ERROR: INSERT has more target columns than expressions.
WHERE: PL/pgSQL function creator(uuid,character varying[],character varying[]) line 3 at SQL statement.
Здравствуйте уважаемые коллеги! Предыстория: есть некоторые свои наработки на php — подобие фреймфорка, в нем есть некоторый код который динамически формирует строку SQL-запроса
наподобие такой:
$query="select main_user as TMF from main_users left join main_users_grps_view on main_users_grps_view.main_user_id=main_users.main_user_id left join main_users_auth_view on main_users_auth_view.main_user_id=main_users.main_user_id left join main_grps on main_grps.main_grp_id = main_users_grps_view.main_grp_id left join main_account_types on main_account_types.main_account_type_id=main_users.main_account_type_id where main_users.main_user_id=1294
данный запрос выдает ошибку «ERROR: column reference «main_user» is ambiguous» поскольку колонка main_users повторяется в нескольких включенных таблицах/представлениях. Структура таблиц/представлений такова, что в принципе пофик из какой таблицы брать поле main_user, можно ли как то сказать postgresql об этом? чтоб он не выдавал эту ошибку, в приведенном выше запросе, а брал эту колонку из первой попавшейся ему таблицы?
Если сделать main_user=main_users_grps_view.main_user то естественно все работает, но делать это на стороне PHP в моем случае не очень удобно, возможно на стороне postgres это получится более элегантно. Заранее спасибо за помощь
+1 also happening on SQL Server
com.microsoft.sqlserver.jdbc.SQLServerException:
Ambiguous column name ‘Company_Audit_RecID’.
Full logs:
Aug 21 14:39:46 WARN metabase.query-processor :: {:status :failed,
:class java.util.concurrent.ExecutionException,
:error «com.microsoft.sqlserver.jdbc.SQLServerException: Ambiguous column name ‘Company_Audit_RecID’.»,
:stacktrace
[«driver.generic_sql.query_processor$cancellable_run_query.invokeStatic(query_processor.clj:485)»
«driver.generic_sql.query_processor$cancellable_run_query.invoke(query_processor.clj:477)»
«driver.generic_sql.query_processor$run_query.invokeStatic(query_processor.clj:502)»
«driver.generic_sql.query_processor$run_query.invoke(query_processor.clj:497)»
«driver.generic_sql.query_processor$do_with_auto_commit_disabled.invokeStatic(query_processor.clj:535)»
«driver.generic_sql.query_processor$do_with_auto_commit_disabled.invoke(query_processor.clj:524)»
«driver.generic_sql.query_processor$do_in_transaction$fn__56571.invoke(query_processor.clj:540)»
«driver.generic_sql.query_processor$do_in_transaction.invokeStatic(query_processor.clj:539)»
«driver.generic_sql.query_processor$do_in_transaction.invoke(query_processor.clj:538)»
«driver.generic_sql.query_processor$run_query_without_timezone.invokeStatic(query_processor.clj:553)»
«driver.generic_sql.query_processor$run_query_without_timezone.invoke(query_processor.clj:552)»
«driver.generic_sql.query_processor$execute_query$fn__56595.invoke(query_processor.clj:577)»
«driver.generic_sql.query_processor$do_with_try_catch.invokeStatic(query_processor.clj:519)»
«driver.generic_sql.query_processor$do_with_try_catch.invoke(query_processor.clj:514)»
«driver.generic_sql.query_processor$execute_query.invokeStatic(query_processor.clj:574)»
«driver.generic_sql.query_processor$execute_query.invoke(query_processor.clj:570)»
«driver$fn__28276$G__28083__28283.invoke(driver.clj:104)»
«query_processor$execute_query.invokeStatic(query_processor.clj:54)»
«query_processor$execute_query.invoke(query_processor.clj:48)»
«query_processor.middleware.mbql_to_native$mbql__GT_native$fn__33022.invoke(mbql_to_native.clj:30)»
«query_processor.middleware.annotate_and_sort$annotate_and_sort$fn__31336.invoke(annotate_and_sort.clj:42)»
«query_processor.middleware.limit$limit$fn__32977.invoke(limit.clj:15)»
«query_processor.middleware.cumulative_aggregations$cumulative_aggregation$fn__32827.invoke(cumulative_aggregations.clj:58)»
«query_processor.middleware.cumulative_aggregations$cumulative_aggregation$fn__32827.invoke(cumulative_aggregations.clj:58)»
«query_processor.middleware.results_metadata$record_and_return_metadata_BANG_$fn__36951.invoke(results_metadata.clj:51)»
«query_processor.middleware.format_rows$format_rows$fn__32967.invoke(format_rows.clj:26)»
«query_processor.middleware.binning$update_binning_strategy$fn__31430.invoke(binning.clj:165)»
«query_processor.middleware.resolve$resolve_middleware$fn__30924.invoke(resolve.clj:483)»
«query_processor.middleware.expand$expand_middleware$fn__32707.invoke(expand.clj:607)»
«query_processor.middleware.add_row_count_and_status$add_row_count_and_status$fn__31010.invoke(add_row_count_and_status.clj:15)»
«query_processor.middleware.driver_specific$process_query_in_context$fn__32847.invoke(driver_specific.clj:12)»
«query_processor.middleware.resolve_driver$resolve_driver$fn__35494.invoke(resolve_driver.clj:15)»
«query_processor.middleware.bind_effective_timezone$bind_effective_timezone$fn__31344$fn__31345.invoke(bind_effective_timezone.clj:9)»
«util.date$call_with_effective_timezone.invokeStatic(date.clj:82)»
«util.date$call_with_effective_timezone.invoke(date.clj:71)»
«query_processor.middleware.bind_effective_timezone$bind_effective_timezone$fn__31344.invoke(bind_effective_timezone.clj:8)»
«query_processor.middleware.cache$maybe_return_cached_results$fn__31519.invoke(cache.clj:149)»
«query_processor.middleware.catch_exceptions$catch_exceptions$fn__32758.invoke(catch_exceptions.clj:58)»
«query_processor$process_query.invokeStatic(query_processor.clj:135)»
«query_processor$process_query.invoke(query_processor.clj:131)»
«query_processor$run_and_save_query_BANG_.invokeStatic(query_processor.clj:249)»
«query_processor$run_and_save_query_BANG_.invoke(query_processor.clj:243)»
«query_processor$fn__36989$process_query_and_save_execution_BANG___36994$fn__36995.invoke(query_processor.clj:289)»
«query_processor$fn__36989$process_query_and_save_execution_BANG___36994.invoke(query_processor.clj:275)»
«query_processor$fn__37013$process_query_and_save_with_max_BANG___37018$fn__37019.invoke(query_processor.clj:310)»
«query_processor$fn__37013$process_query_and_save_with_max_BANG___37018.invoke(query_processor.clj:306)»
«api.dataset$fn__43466$fn__43469.invoke(dataset.clj:45)»
«api.common$fn__20623$invoke_thunk_with_keepalive__20628$fn__20629$fn__20630.invoke(common.clj:433)»],
:query
{:query {:source_table 1429, :filter [«time-interval» [«fk->» 17715 15596] -7 «day» {}]},
:type «query»,
:parameters [],
:constraints {:max-results 10000, :max-results-bare-rows 2000},
:info
{:executed-by 1,
:context :ad-hoc,
:card-id nil,
:nested? false,
:query-hash [-102, 117, -24, -10, 9, 122, -101, -122, -49, -72, 80, 40, 51, -21, -113, 57, 127, 44, 74, 16, 75, -79, 81, -110, -79, 89, 56, -106, 127, -103, -62, -41],
:query-type «MBQL»}},
:expanded-query nil}
Aug 21 14:39:46 WARN metabase.query-processor :: Query failure: com.microsoft.sqlserver.jdbc.SQLServerException: Ambiguous column name ‘Company_Audit_RecID’.
[«query_processor$assert_query_status_successful.invokeStatic(query_processor.clj:217)»
«query_processor$assert_query_status_successful.invoke(query_processor.clj:210)»
«query_processor$run_and_save_query_BANG_.invokeStatic(query_processor.clj:250)»
«query_processor$run_and_save_query_BANG_.invoke(query_processor.clj:243)»
«query_processor$fn__36989$process_query_and_save_execution_BANG___36994$fn__36995.invoke(query_processor.clj:289)»
«query_processor$fn__36989$process_query_and_save_execution_BANG___36994.invoke(query_processor.clj:275)»
«query_processor$fn__37013$process_query_and_save_with_max_BANG___37018$fn__37019.invoke(query_processor.clj:310)»
«query_processor$fn__37013$process_query_and_save_with_max_BANG___37018.invoke(query_processor.clj:306)»
«api.dataset$fn__43466$fn__43469.invoke(dataset.clj:45)»
«api.common$fn__20623$invoke_thunk_with_keepalive__20628$fn__20629$fn__20630.invoke(common.clj:433)»]
Aug 21 14:39:46 DEBUG metabase.middleware :: POST /api/dataset 200 (244 ms) (15 DB calls). Jetty threads: 8/50 (11 busy, 1 idle, 0 queued)
Last Modified Date: 24 Aug 2022
Issue
When trying to refresh a data extract containing custom SQL, the following error might occur:
ERROR: column reference «<field name>» is ambiguous; Error while executing the query
Environment
- Tableau Desktop
- Tableau Data Extract
- Custom SQL
Resolution
Verify that the SQL Query completes successfully when run directly against the database. If the query does not complete successfully, work with your database administrator to address issues in the query.
Cause
The error occurs within the data source and is not related to Tableau.
Additional Information
More information on the «Column reference «<name>» is ambiguous error can be found below:
- Identifier Qualifiers at MySQL
- 8 Tips Absolute Beginners can Use to Fix SQL Queries at Vertabelo Academy
#sql #postgresql
Вопрос:
Пытаюсь упростить эту ВСТАВКУ и продолжаю получать эту неоднозначную ошибку ниже. Что я здесь делаю не так, нужен ли мне где-то псевдоним, которого мне не хватает?
<internal.PGError>: {
m: {
82: "scanRTEForColumn",
83: "ERROR",
86: "ERROR",
67: "42702",
77: "column reference "created_at" is ambiguous",
80: "3082",
70: "parse_relation.c",
76: "694",
},
}
Вот инструкция SQL, которую я использую:
INSERT INTO delivery_areas
SELECT
r.drn_id AS restaurant_drn_id,
'initial'::algorithm_name AS algorithm_name,
z.city_drn_id AS city_drn_id,
?::geometry AS delivery_area,
gen_random_uuid() AS drn_id,
?::timestamp AS created_at,
?::timestamp AS updated_at,
'custom'::delivery_area_type AS delivery_area_type
FROM restaurants r
JOIN neighborhood_zones nz ON (nz.hood_drn_id = r.hood_drn_id)
JOIN zones z ON (z.drn_id = nz.zone_drn_id)
WHERE r.drn_id = ?
GROUP BY restaurant_drn_id, algorithm_name, city_drn_id, created_at, updated_at, delivery_area_type
ON CONFLICT ON CONSTRAINT delivery_areas_pkey DO UPDATE
SET
delivery_area = EXCLUDED.delivery_area,
delivery_area_type = EXCLUDED.delivery_area_type,
updated_at = EXCLUDED.updated_at
RETURNING *
Создайте инструкции таблицы для областей доставки и ресторанов:
CREATE TYPE algorithm_name as ENUM ('initial');
CREATE TABLE delivery_areas (
restaurant_drn_id uuid NOT NULL,
algorithm_name algorithm_name NOT NULL DEFAULT 'initial',
city_drn_id uuid NOT NULL,
delivery_area geometry(MultiPolygon,4326) NOT NULL,
drn_id uuid NOT NULL DEFAULT gen_random_uuid(),
created_at timestamp without time zone NOT NULL,
updated_at timestamp without time zone NOT NULL,
PRIMARY KEY (restaurant_drn_id, algorithm_name)
);
CREATE INDEX delivery_areas_algorithm_city_idx on delivery_areas (algorithm_name, city_drn_id);
CREATE INDEX delivery_areas_delivery_area_idx on delivery_areas USING gist(delivery_area);
ALTER TABLE delivery_areas ADD FOREIGN KEY (restaurant_drn_id) REFERENCES restaurants(drn_id);
CREATE TABLE restaurants (
drn_id uuid PRIMARY KEY,
hood_drn_id uuid NOT NULL,
delivery_range_delta_m int4 NOT NULL,
geo_lat double precision NOT NULL,
geo_long double precision NOT NULL,
created_at timestamp without time zone NOT NULL,
updated_at timestamp without time zone NOT NULL
);
Комментарии:
1. Таким образом, все столбцы в delivery_areas находятся в инструкции select. И поскольку я не могу добавить псевдоним в инструкцию INSERT INTO, что я упускаю?
2. Квалифицируйте все ссылки на ваши столбцы, как
delivery_areaи должно бытьdelivery_areas.delivery_area. Одна или несколько ссылок на ваши столбцы разрешаются двумя или более таблицами, и база данных просит вас устранить эту двусмысленность.3. Что
?::geometry AS delivery_area,должно быть ? Заполнитель для позиционного аргумента?4.
?::geometry AS delivery_area,действительно ли заполнитель для позиционного аргумента да5. Я добавил
delivery_areas.в качестве префикса перед всеми именами полей справа внутри выбора, но теперь выдает следующую ошибку:<internal.PGError>: { 77: "syntax error at or near "."", ... }
Ответ №1:
Обратите внимание, что в вашем GROUP BY предложении у вас есть ссылка на created_at :
GROUP BY restaurant_drn_id, algorithm_name, city_drn_id, created_at, updated_at, delivery_area_type
Но этот столбец есть в нескольких ваших таблицах.
Префикс этой ссылки на столбец с правильной таблицей, например:
GROUP BY restaurant_drn_id, algorithm_name, city_drn_id, delivery_areas.created_at, updated_at, delivery_area_type
Я только догадался, на какую таблицу вы хотели сослаться. Это устранит эту ошибку, но это может быть не та дата/отметка времени, по которой вы хотели сгруппироваться.
Вот пример проблемы и решения, а также подробные сведения, которые следует указывать при задании такого рода вопросов:
CREATE TABLE delivery_areas (
id int
, created_at timestamp
);
CREATE TABLE restaurants (
drn_id int
, created_at timestamp
);
CREATE TABLE othertbl (
id int
, created_at timestamp
);
-- The following generates an error:
INSERT INTO delivery_areas
SELECT r.drn_id AS restaurant_drn_id
, current_timestamp AS created_at
FROM restaurants r
JOIN othertbl o
ON o.id = r.drn_id
GROUP BY restaurant_drn_id, created_at
;
-- ERROR: column reference "created_at" is ambiguous
-- LINE 7: GROUP BY restaurant_drn_id, created_at
-- The following is one way to resolve the error:
INSERT INTO delivery_areas
SELECT r.drn_id AS restaurant_drn_id
, current_timestamp AS created_at
FROM restaurants r
JOIN othertbl o
ON o.id = r.drn_id
GROUP BY restaurant_drn_id, r.created_at
;
Обратите внимание на r.created_at . r является определителем, разрешающим двусмысленность.
Вот ссылка на тестовый случай:
Полный рабочий тестовый случай
Комментарии:
1. Итак, у вас здесь противоречивые советы, я должен использовать
r.created_atилиdelivery_areas.created_at? Если я использую последнее, я получу это:72: "There is an entry for table "delivery_areas", but it cannot be referenced from this part of the query.",2. @Уильямроуз Нет, нет. Вы посмотрели ссылку на скрипку, которую я предоставил?
r.created_atбыл в тестовом примере, который я создал. Я также сослался на ваш запрос, добавленный в начало ответа. Вы знаете, какуюcreated_atколонку вы хотелиGROUP BY?3. Ааа, хорошо. Да, я хотел бы сгруппироваться по
delivery_areasверсии4. @WilliamRose Идеально. Тогда мое предположение должно сработать, пока не будет найдена следующая проблема.
5. @WilliamRose
SELECTСписок определяет, что будет вставлено.tbl.created_atВGROUP BYтермины не вставляется, но используется для определения того, какие строки выбраны. Мы могли бы поболтать, если хочешь. Я не уверен, что вы понимаете такоеGROUP BYповедение.

