in SQL, why is this JOIN returning the key column twice?

Viewed 4381

I'm sorry if this is a stupid question, but I can't seem to get my head around it. I'm fairly new to SQL and this behavior would be strange in R or Pandas or other things that I'm used to using.

Basically, I have two tables in two different databases, with a common key user_id. I want to join all the columns with

SELECT * FROM db1.first_table t1 
JOIN db2.second_table t2 
ON t1.user_id = t2.user_id

Great, it works. Except there are two (identical) columns called user_id. This wouldn't really matter, except that I am doing this in pyspark and when I try to export the joined table to a flat file I get an error that two of the columns have the same name. There are work-arounds for this, but I'm just wondering if someone can explain why the join returns both user_id columns. It seems like it is an inner join so by definition the columns are identical. Why would it return both?

As a side question, is there an easy way to avoid this behavior?

Thanks in advance!

6 Answers

All of these answers (except the one that OP wrote himself) seem to assume that we are operating on really small tables where we can manually type out every column we need.

The simplest solution in PySpark would be to use the DataFrame join syntax:

df = left_df.join(right_df, ["name"])

This will not duplicate the column and behave like a pandas merge. If there is no special reason why you have to write it as an sql command, I would recommend this. Contrast this to

df = left_df.join(right_df, left.name == right.name) 

which will behave like a SQL join and keep both columns!

This also applies to Scala and R, see here.

Another solution would be to rename the second target column to something like "target_dataframe2", then joining with sql, then simply dropping "target_dataframe2" again.

If you want only one column of user_id to get printed then you should use Inner join with USING keyword.

When you use USING keyword with a column name, it filters out that common column from both the tables and displays only one. But when you use ON with a condition t1.user_id = t2.user_id then it's just a coincidence of column with the same name is used in condition.

ON is also used to compare different columns of two tables so it does not filter out the columns on the basis of condition. So, if you want to display common columns only once after joining then you should use USING keyword.

Related