Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ambiguous column name - is it though?

Tags:

sql

tsql

If I want to write a query with a simple join, I can do this:

select * from customer c
join order o
on c.customerid = o.customerid
where c.customerid = 100

and it all works fine. In this query, is there a reason why I have to specify a table alias - ie. c.customerid? Why can't I just write this:

select * from customer c
join order o
on c.customerid = o.customerid
where customerid = 100

I get the error Ambiguous column name 'customerid'. In this case, where there's only one column in the WHERE clause and it's the column on which I'm JOINing, is this actually "ambiguous"? Or is it just to comply with the ansi-standard (I'm guessing here - I don't know if it does comply) and to encourage good coding conventions?

like image 231
Paul Spangle Avatar asked Dec 17 '22 08:12

Paul Spangle


1 Answers

For your specific example I can't think of any circumstances in which it would make a difference. However for an INNER JOIN on a string column it could do as below.

DECLARE @customer TABLE
(customerid CHAR(3) COLLATE Latin1_General_CI_AS)

INSERT INTO @customer VALUES('FOO');

DECLARE @order TABLE
(customerid CHAR(3) COLLATE Latin1_General_CS_AS)

INSERT INTO @order VALUES('FOO');


SELECT * 
FROM @customer c
JOIN @order o
ON c.customerid = o.customerid COLLATE Latin1_General_CS_AS
WHERE c.customerid = 'Foo' /*Returns 1 row*/

SELECT * 
FROM @customer c
JOIN @order o
ON c.customerid = o.customerid COLLATE Latin1_General_CS_AS
WHERE o.customerid = 'Foo' /*Returns 0 rows*/
like image 73
Martin Smith Avatar answered Jan 10 '23 02:01

Martin Smith