Ambiguous column name как исправить

I get an ambiguous column name error with this query (InvoiceID). I can’t figure out why. They all seem to be joined correctly so why doesn’t SSMS know to display VendorID?

Query:

SELECT 
    VendorName, InvoiceID, InvoiceSequence, InvoiceLineItemAmount
FROM Vendors 
JOIN Invoices ON (Vendors.VendorID = Invoices.VendorID)
JOIN InvoiceLineItems ON (Invoices.InvoiceID = InvoiceLineItems.InvoiceID)
WHERE  
    Invoices.InvoiceID IN
        (SELECT InvoiceSequence 
         FROM InvoiceLineItems
         WHERE InvoiceSequence > 1)
ORDER BY 
    VendorName, InvoiceID, InvoiceSequence, InvoiceLineItemAmount

Amira Bedhiafi's user avatar

asked Sep 30, 2012 at 16:35

jaielob's user avatar

0

We face this error when we are selecting data from more than one tables by joining tables and at least one of the selected columns (it will also happen when use * to select all columns) exist with same name in more than one tables (our selected/joined tables). In that case we must have to specify from which table we are selecting out column.

Following is a an example solution implementation of concept explained above

I think you have ambiguity only in InvoiceID that exists both in InvoiceLineItems and Invoices Other fields seem distinct. So try This

I just replace InvoiceID with Invoices.InvoiceID

   SELECT 
        VendorName, Invoices.InvoiceID, InvoiceSequence, InvoiceLineItemAmount
    FROM Vendors 
    JOIN Invoices ON (Vendors.VendorID = Invoices.VendorID)
    JOIN InvoiceLineItems ON (Invoices.InvoiceID = InvoiceLineItems.InvoiceID)
    WHERE  
        Invoices.InvoiceID IN
            (SELECT InvoiceSequence 
             FROM InvoiceLineItems
             WHERE InvoiceSequence > 1)
    ORDER BY 
        VendorName, Invoices.InvoiceID, InvoiceSequence, InvoiceLineItemAmount

You can use tablename.columnnae for all columns (in selection,where,group by and order by) without using any alias. However you can use an alias as guided by other answers

answered Sep 30, 2012 at 16:45

Sami's user avatar

SamiSami

8,0568 gold badges66 silver badges99 bronze badges

2

You have a column InvoiceID in the Invoices table and also in the InvoiceLineItems table. There is no way for the query execution engine to know which one you want returned.

Adding a table alias will help:

SELECT V.VendorName, I.InvoiceID, IL.InvoiceSequence, IL.InvoiceLineItemAmount
FROM Vendors V
JOIN Invoices I ON (...)
JOIN InvoiceLineItems IL ON (...)
WHERE ...
ORDER BY V.VendorName, I.InvoiceID, IL.InvoiceSequence, IL.InvoiceLineItemAmount

answered Sep 30, 2012 at 16:38

Graeme Perrow's user avatar

Graeme PerrowGraeme Perrow

55.8k21 gold badges80 silver badges121 bronze badges

0

Because you are joining two tables Invoices and InvoiceLineItems that both contain InvoiceID. change to Invoices.InvoiceID to make it correct.

answered Sep 30, 2012 at 16:40

Uchiha_Sasuke's user avatar

Most likely both tables have a column with the same name. Alias each table, and call each column with the table alias.

answered Sep 30, 2012 at 16:39

dotancohen's user avatar

dotancohendotancohen

29.7k36 gold badges136 silver badges195 bronze badges

it’s because some of the fields (specifically InvoiceID on the Invoices table and on the InvoiceLineItems) are present on both table. The way to answer of question is to add an ALIAS on it.

SELECT 
    a.VendorName,  Invoices.InvoiceID, .. -- or use full tableName
FROM Vendors a   -- This is an `ALIAS` of table Vendors
JOIN Invoices ON (Vendors.VendorID = Invoices.VendorID)
JOIN InvoiceLineItems ON (Invoices.InvoiceID = InvoiceLineItems.InvoiceID)
WHERE  
    Invoices.InvoiceID IN
        (SELECT InvoiceSequence 
         FROM InvoiceLineItems
         WHERE InvoiceSequence > 1)
ORDER BY 
    VendorName, InvoiceID, InvoiceSequence, InvoiceLineItemAmount

answered Sep 30, 2012 at 16:39

John Woo's user avatar

John WooJohn Woo

258k69 gold badges494 silver badges490 bronze badges

4

If you join 2 or more tables and they have similar names for their columns SQL server wants you to qualify columns to which they belong.

SELECT  ev.[ID]
    ,[Description]
    FROM   [Events] as ev 
    LEFT JOIN  [Units] as un ON ev.UnitID = un.UnitId  

if Events and Units tables have the same column name (ID) SQL server wants you to use aliases.

answered Aug 26, 2015 at 7:50

Ahmet Arslan's user avatar

Ahmet ArslanAhmet Arslan

5,2202 gold badges33 silver badges35 bronze badges

1

It doesn’t just happen in queries with joins.

It can happen when you use ORDER BY on a single table query with a column name that appears twice in the query.

Eg.

SELECT firstname, * FROM person ORDER BY firstname;`

Because firstname appears twice in the result set it is ambiguous which one you want to sort by (even though they are both the same).

You can solve it by using any of these aliases


SELECT firstname AS fn, * FROM person ORDER BY firstname;

SELECT p.firstname, * FROM person p ORDER BY firstname;

-- Its not really clear to me why this next one works but it does
SELECT p.firstname, p.* FROM person p ORDER BY p.firstname;

answered Aug 27, 2021 at 0:40

Dave Pile's user avatar

Dave PileDave Pile

5,4593 gold badges34 silver badges49 bronze badges

One of your tables has the same column name’s which brings a confusion in the query as to which columns of the tables are you referring to. Copy this code and run it.

SELECT 
    v.VendorName, i.InvoiceID, iL.InvoiceSequence, iL.InvoiceLineItemAmount
FROM Vendors AS v
JOIN Invoices AS i ON (v.VendorID = .VendorID)
JOIN InvoiceLineItems AS iL ON (i.InvoiceID = iL.InvoiceID)
WHERE  
    I.InvoiceID IN
        (SELECT iL.InvoiceSequence 
         FROM InvoiceLineItems
         WHERE iL.InvoiceSequence > 1)
ORDER BY 
    V.VendorName, i.InvoiceID, iL.InvoiceSequence, iL.InvoiceLineItemAmount

answered Nov 29, 2018 at 10:01

Nelson Katale's user avatar

This happens because there are fields with the same name in more than one table, in the query, because of the joins, so you should reference the fields differently, giving names (aliases) to the tables.

answered Dec 19, 2018 at 11:18

Junior Placido's user avatar

At times you may want to join two tables in SQL and there are in the tables, columns with the same name.

Ambiguous error means that you are calling a certain field in which exist in both Table and the SQL has no idea where to get it. Table 1
has a field (column) name “ID” Table 2 has a field (column) name “ID”
as well

Example

SELECT [ID],[Name],[GenderId] FROM [dbo].[TblPerson] AS A
INNER JOIN [dbo].[TblPerson] AS B 
ON A.ID=B.GenderId;

Query Must be

SELECT A.[ID],A.[Name],A.[GenderId] FROM [dbo].[TblPerson] AS A
INNER JOIN [dbo].[TblPerson] AS B 
ON A.ID=B.GenderId;

answered Jul 23, 2022 at 7:56

Ragab Mohamad's user avatar

It outputs (error) ambiguous column name because it gets confused about where to fetch data from since you might have the same query name «InvoiceID» in two different tables or datasets (check all the tables you have used in where clause, InvoiceID should be in at least two of them). To correct this kind of error, you should always specify the query with its tables. Since you are extracting this data from vendors, specify it as «vendors.InvoiceID». To this for all other queries even though it doesn’t give you an error.

answered Aug 16, 2022 at 8:39

aditya14581's user avatar

Когда вы объединяете несколько таблиц в SQL-запросе, если столбец с одинаковым именем присутствует в обеих таблицах, то BigQuery не знает, какой из них использовать (если вы явно не скажете об этом), поэтому он выдает ошибку с неоднозначным именем столбца.

Редактор Bigquery WebUI достаточно умен, чтобы выделить точную строку, в которой присутствует неоднозначный столбец (обратите внимание на красное восклицание на полях редактора sql). Решение может быть в одном из приведенных ниже методов:

Убедитесь, что в списке выбора нет неоднозначных имен столбцов:

select Id, Name, Description
from table1 t1 
join table2 t2
on t2.Id = t1.Id;

В этом примере Идентификатор имени столбца присутствует в обеих таблицах, t1 и t2. Вы можете прояснить это, разметив столбцы, как показано ниже:

select t1.Id, t1.Name, t2.Description
from table1 t1 
join table2 t2
on t2.Id = t1.Id;

Убедитесь, что предложение Where / Join не имеет двусмысленных имен столбцов:

select t1.Id, t1.Name, t2.Description
from table1 t1 
join table2 t2
 on t2.Id = t1.Id
Where Id = 100;

В этом примере, поскольку идентификатор присутствует в обеих таблицах, создайте псевдоним столбца, как показано ниже:

select t1.Id, t1.Name, t2.Description
from table1 t1 
join table2 t2
 on t2.Id = t1.Id
Where t1.Id = 100;

Никогда не используйте запятые в предложении FROM. Всегда используйте правильный, явный синтаксис Join:

select table1.* 
from table1,
 table2,
 table3
where table1.Id = table2.Id;

Использование запятых для Join(соединений) может сбивать с толку, приводить к ошибкам и данный метод имеет меньшую читабельность. Всегда старайтесь использовать явное объединение и явные столбцы объединения. Это значительно сократит количество ошибок, а также упростит работу по устранению неполадок

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 (.),

ALSO READ: SQL BETWEEN Explained with Practical Examples

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

Create table patient_table
(
   patient_id int primary key, 
   patient_name varchar(20),
   doctor_id int,
   city varchar(20)
)

Next create DOCTOR Table

Create table doctor_table
(
   doctor_id int primary key, 
   doctor_name varchar(20),
   city varchar(20)
)

Example 1: Write SQL query to display all patient data with doctor id and doctor city name

select patient_id as 'Patient ID' ,patient_name as 'Patient Name',doctor_id as 'Doctor ID',city as 'Doctor City' from patient_table , doctor_table where patient_table.doctor_id=doctor_table.doctor_id
  • 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:
Solved: SQL ambiguous column name [100% Working]
Error Message :

Msg 209,Level 16,State 1,Line 1
Ambiguous column name 'doctor_id'
Msg 209,Level 16,State 1,Line 1
Ambiguous column name 'city'

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

ALSO READ: How to alter table and add column SQL [Practical Examples]

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

select patient_table.patient_id as 'Patient ID' ,patient_table.patient_name as 'Patient Name',doctor_table.doctor_id as 'Doctor ID',doctor_table.city as 'Doctor City' from patient_table , doctor_table where patient_table.doctor_id=doctor_table.doctor_id

OUTPUT:

Solved: SQL ambiguous column name [100% Working]

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

SQL joins

Read More

SQL Ambiguous Column Name

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

January 5, 2019
MSSQL, TSQL

When reading data from tables, we may need to give different names to tables and columns. We can do this by defining alias to columns or tables.

In our first example we will give different names to the tables.

Example1:

We usually need to give Alias when we join the tables.

First, let’s create two tables as below and add a few records to these tables.

USE [TestDB]

GO

CREATE TABLE [dbo].[MyTable_1](

[ID] [int] IDENTITY(1,1) NOT NULL,

[Name] [varchar](50) NULL

) ON [PRIMARY]

GO

CREATE TABLE [dbo].[MyTable_2](

[ID] [int] IDENTITY(1,1) NOT NULL,

[SurName] [varchar](50) NULL,

) ON [PRIMARY]

GO

INSERT INTO [dbo].[MyTableTarget] VALUES (‘Nurullah’),(‘Faruk’)

INSERT INTO [dbo].[MyTableSource] VALUES (‘CAKIR’),(‘ERDEM’)

Then try to run the following join query.

SELECT [ID],[Name],[Surname] FROM [dbo].[MyTable_1]

INNER JOIN [dbo].[MyTable_2] ON [dbo].[MyTable_1].[ID]=[dbo].[MyTable_2].[ID]

When we run the query we will get the error as follows.

Msg 209, Level 16, State 1, Line 17

Ambiguous column name ‘ID’.

The reason for the error is that the ID column exists in both tables.

In this case, the problem will be solved when we write the query using alias. We can use alias as follows.

SELECT tbl1.[ID],tbl1.[Name],tbl2.[Surname] FROM [dbo].[MyTable_1] tbl1

INNER JOIN [dbo].[MyTable_2] tbl2 ON tbl1.[ID]=tbl2.[ID]

In the second example we will describe the alias to the columns.

Example2:

When joining the first table and the second table, combine the name and surname with the + operator. As a result, let’s give the column a different name with an alias.

SELECT tbl1.[ID],tbl1.[Name] +‘ ‘+tbl2.[Surname] AS ‘Name_Surname’ FROM [dbo].[MyTable_1] tbl1

INNER JOIN [dbo].[MyTable_2] tbl2 ON tbl1.[ID]=tbl2.[ID]

Loading

  • Remove From My Forums
  • Вопрос

  • I am working on my first table join, so I might have a couple of errors.  Let’s start with the column «Status».  This query works:

    select * from tblCsCases
    where [Status] = ‘REVIEW’

    However, this query does not work:

    select MAX(FileNumber) as FileNumber, MAX(PaStartDate) as PaStartDate, A.LastName, COUNT(A.LastName) as Attorneys

    from tblCsCases E INNER JOIN tblCtAttorney A
    on E.ProsecutingAttorney = A.BarCode
    where [Status] = ‘REVIEW’
    and PaStartDate BETWEEN ‘20100101’ AND ‘20161231’
    group by A.LastName

    I am getting the following error:

    Msg 209, Level 16, State 1, Line 4
    Ambiguous column name ‘Status’.

    Any idea what is the problem.  If you need more information, please let me know.  Thank you for your help.


    Kurt

Ответы

  • Just prepend with the table alias, e.g. E.[Status]

    • Помечено в качестве ответа

      12 сентября 2016 г. 4:52

Понравилась статья? Поделить с друзьями:
  • Щербинка между передними зубами как исправить
  • Истинная высота как найти
  • Как найти деньги для операции
  • Как найти переходы по локациям
  • Равнобедренный остроугольный треугольник как найти сторону