-3

I am attempting some SQL practice (on Udacity) and I stumbled upon an issue with the SQL JOIN exercises. I am attempting to JOIN 3 tables. The code are as follows:

MY CODE:

SELECT   r.name, s.name, a.name
FROM accounts a
JOIN sales_reps s
ON a.sales_rep_id = s.id
JOIN region r
ON s.region_id = r.id
ORDER BY a.name;

Result: Only the name column is printed

ANSWER PROVIDED:

SELECT r.name region, s.name rep, a.name account
FROM sales_reps s
JOIN region r
ON s.region_id = r.id
JOIN accounts a
ON a.sales_rep_id = s.id
ORDER BY a.name;

Result: All 3 columns are printed.

CODE 1 Result Code 2 Results

I dont quite understand why there are different output. Would appreciate any and all feedback!

I tried joining the 3 tables and ensuring that the PK connects with the FK

I want to print the region name, representative name and account name

2
  • 1
    Inner joins are commutative so the queries are equivalent, other than the column alias there should be no difference. please provide a proper example to illustrate. Commented Jul 15, 2023 at 10:29
  • 1
    It has nothing to do with the order that the joins are written in. In your first query the three columns have the same identifier and whatever the client is, it is unable to distinguish between them. When columns have the same name, you should always alias them so that they have a unique name in the context of the select list. Commented Jul 15, 2023 at 10:37

1 Answer 1

-2

Issue: The query which you have used doesn't have alias defined so db is prioritizing the last column and only one column is getting reflected in the result.

Resolution: The query which you are using and answered provided is both correct.However, in the 'Answered' in select each 'name' column has been differentiated with alias region name, representative name and account name.

HTH.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much for this! I was rly stumped. Rly appreciate this!
@shazam this answer is plainly wrong.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.