I found a SQL query in some Java code that looks like this:
SELECT * FROM tableA JOIN tableB ON ...
Both tableA
and tableB
contain the field named id
, and the Java code that executes this query does this:
Integer id = (Integer)rs.getObject("id");
Does the JDBC spec have anything to say about which field value will be returned? I haven't been able to find anything that says one way or another. I see that some databases throw an error, but MySQL/MariaDB (the database in use, here) do not complain and the value returned seems to be tableA.id
, or the "leftmost" field whose name is "id".
I'm asking if there is spec-defined behavior in this case, or if it's up to the database and/or JDBC driver to decide how to behave.
Needless to say, I'll be fixing this to work predictably and unambiguously while I'm looking at the code, but I'm curious as to the answer.
The API documentation of ResultSet
answers your question:
Column names used as input to getter methods are case insensitive. When a getter method is called with a column name and several columns have the same name, the value of the first matching column will be returned.
The JDBC 4.3 specification document in section 15.2.3 Retrieving Values also says:
The columns are numbered from left to right, as they appear in the select list of the query, starting at 1.
Column labels supplied to getter methods are case insensitive. If a select list contains the same column more than once, the first instance of the column will be returned.
The index of the first instance of a column label can be retrieved using the method
findColumn
. If the specified column is not found, the methodfindColumn
throws anSQLException
.
So, if a result set has multiple columns with the same (case insensitive(!)) name, then the value of the first matching column is returned.