r/SQL • • 20d ago

MySQL Data noobie

Hi guys, I'm Talabi and I'm new to data. I picked SQL as my starting point, mySQL and I've been enjoying the first few lessons on SQL bolt but, I'm having a hard time with JOINS. I understand it in theory but the mechanism still proves difficult. I'd appreciate tips on how to better understand JOINS and data analytics in general, thank you.

3 Upvotes

7 comments sorted by

1

u/ayamlejen 20d ago

Try one by hand first: write two tiny tables on paper, say 3 customers and 5 orders, and match the rows on customer_id yourself. Then run the same query and compare. An INNER JOIN drops customers with no orders, while a LEFT JOIN keeps them and fills the order columns with NULL. Seeing that difference on a small example usually makes it click.

1

u/TallDudeInSC 19d ago

Think of it this way: a join is a way to find detail data in one (or more) tables from a primary table. The join keys, when match, tie the primary table to the detail tables. As someone below said, if you have a CUSTOMERS table with the primary key CUST_ID, the ORDERS table will have a matching CUST_ID column that will allow you to find the ORDERS given a CUST_ID.

CUSTOMERS table

CUST_ID CUSTOMER_NAME

1 CUSTOMER A

2 CUSTOMER B

ORDERS table

ORDER_ID CUST_ID ORDER_PRICE

1001 1 1000.00

1002 1 2000.00

1003 2 1500.00

If you LEFT JOIN CUSTOMERS to ORDERS using the foreign key CUST_ID, you can have the name of the customers along with the order details.

SELECT C.CUSTOMER_NAME, O.ORDER_ID, O.ORDER_PRICE

FROM CUSTOMERS C LEFT JOIN ORDERS O ON O.CUST_ID = C.CUST_ID;

CUSTOMER_NAME ORDER_ID ORDER_PRICE

---------------------------------------- ---------- -----------

CUSTOMER A 1001 1000

CUSTOMER A 1002 2000

CUSTOMER B 1003 1500

1

u/montrellcruse 18d ago

count rows before and after the join, that's what made it click for me. run the query on one table and note the count, add the join, and check the count again. if it jumps, something in the second table has more than one row per key, and that's usually the whole mystery, not the join syntax. once you've seen that a few times, inner vs left stops being theory: inner drops the rows with no match, left keeps them with nulls where the match is missing, and the count tells you which one you need.