r/SQL • • 13d ago

SQLite Help with Harvard CS50 Subquery and Joins

Due to an unfortunate but also fortunate promotion at work, I now have to learn SQL. I had some familiarity with looking at it before, but never writing it and my understanding of it is basically null

So, enter Harvard CS50 Subquery with SQLite, get through week 0 in about 3 hours, single query gave me basically no trouble

Enter week 1, and I've spent over 12 hours trying to figure out what the hell is going on. The course material basically just shows one or two examples of subquery, and very modest examples of joining, then the course practice questions are combining different concepts and way more advanced and my brain hurts like hell. I'm really having trouble with subquery and joins both, I think I'm taking them too literally, but the course material I have really isn't helping, I had ChatGPT write me 100 practice questions, and I got through 50 just fine, then as soon as I hit subquery and grouping, it's like I hit a wall.

Can someone help explain this to me? I think I'm just failing to understand the architecture, the syntax kind of makes sense to me, I need someone to break down subquery and joins in... human language

Update:

Thanks to everyone here I was actually able to figure it out, I have only been learning sql for 5 days, but was able to complete all of the problem sets with some dedicated research and practice, I actually feel like now I am quite good with joins and subquery

Thank you everyone :D

9 Upvotes

18 comments sorted by

5

u/McBurgerQueen 13d ago

Can you share a problem you’re struggling with

1

u/StickWarm9316 13d ago edited 13d ago

Yeah, here'sone actually taken directly from the CS50 problem set I'm on:

DESE would like you to determine in what cities additional public schools might be needed. In 5.sql, write a SQL query to find cities with 3 or fewer public schools. Your query should return the names of the cities and the number of public schools within them, ordered from greatest number of public schools to least. If two cities have the same number of public schools, order them alphabetically.

I'm really struggling to understand subquerying and joining, I'm very familiar with aggregate single query from a single table, but the introduction of multiple tables has me scratching my head, I mostly get very confused keeping unique identifiers and foreign keys tucked away in my head for each individual table,

For example, with question one:

Okay, I need to return cities with three of fewer public schools, in a single table, I would just;

SELECT "city", COUNT("id") AS "school_count" FROM "schools" WHERE "type" = 'Public' GROUP BY "city" HAVING "school_count" <= 3 ORDER BY "school_count" DESC, "city" ASC;

How the hell would I do this with multiple tables? That's where my head starts hurting, given the fields, etc. I've been given joining the multiple tables together just makes my brain spasm-- how do I apply single query theory of sorting, grouping, and filtering to multiple tables?

In the lecture, the only example of subquery I'm given is to take a unique identifier so I can pull one value from one table into another, but it doesn't explain syntax/how to order, group, etc when working with multiple tables

https://cs50.harvard.edu/sql/psets/1/dese/

2

u/Bud_Light_Official 13d ago
SELECT "city", COUNT("id") AS "school_count"
FROM "schools"
WHERE "type" = 'Public'
GROUP BY "city"
HAVING "school_count" <= 3
ORDER BY "school_count" DESC, "city" DESC

This looks good for answering that question, although I think it probably should be 'Public School' not 'Public'. That question didn't ask for relating tables. Do you have one of the questions I could help you walk through that does?

2

u/StickWarm9316 13d ago

Here's one from the same problem set, where three different tables have to be considered

Is there a relationship between school expenditures and graduation rates? In 11.sql, write a SQL query to display the names of schools, their per-pupil expenditure, and their graduation rate. Sort the schools from greatest per-pupil expenditure to least. If two schools have the same per-pupil expenditure, sort by school name.

  • You should assume a school spends the same amount per-pupil their district as a whole spends.

districts table

The districts table contains the following columns:

  • id, which is the ID of the district
  • name, which is the name of the district
  • type, which denotes the type of district. In Massachusetts, there are public school districts (denoted “Public School District”) and charter districts (denoted “Charter District”). No need to learn the difference, though you can do so from Wikipedia if curious!
  • city, which is the city in which the district is located
  • state, which is the state in which the district is located
  • zip, which is the ZIP Code in which the district is located

schools table

The schools table contains the following columns:

  • id, which is the ID of the school
  • district_id, which is the ID of the district to which the school belongs
  • name, which is the name of the school
  • type, which denotes the type of school. In Massachusetts, there are public schools (denoted “Public School”) and charter schools (denoted “Charter School”). No need to learn the difference, though you can do so from Wikipedia if curious!
  • city, which is the city in which the school is located
  • state, which is the state in which the school is located
  • zip, which is the ZIP Code in which the school is located

graduation_rates table

The graduation_rates table contains the following columns:

  • id, which is the ID of the graduation rate
  • school_id, which is the ID of the school with which the graduation is associated
  • graduated, which is the percentage of students, 0–100, who graduated on time
  • dropped, which is the percentage of students, 0–100, who dropped out of school before graduation
  • excluded, which is the percentage of students, 0–100, who were “excluded” (i.e., expelled)

expenditures table

The expenditures table contains the following columns:

  • id, which is the ID of the expenditure
  • district_id, which is the ID of the district with which the expenditure is associated
  • pupils, which is the number of pupils attending the given district
  • per_pupil_expenditure, which is the amount of money spent, in dollars, on each student attending the district

staff_evaluations table

The staff_evaluations table contains the following columns:

  • id, which is the ID of the evaluation report
  • district_id, which is the ID of the district with which the evaluation is associated
  • evaluated, which is the percentage of district staff, 0–100, formally evaluated
  • exemplary, which is the percentage of district staff, 0–100, evaluated as “exemplary”
  • proficient, which is the percentage of district staff, 0–100, evaluated as “proficient”
  • needs_improvement, which is the percentage of district staff, 0–100, evaluated as “needing improvement”
  • unsatisfactory, which is the percentage of district staff, 0–100, evaluated as “unsatisfactory”

1

u/SnooSprouts4952 13d ago

Eww, the same name (id) being used for different things in each table is messy. Be careful on your joins.

Select * //enter all your desired fields here From districts Join schools on schools.district_id = districts.id Join graduation_rates on graduation_rates.school_id = schools.id //.... continue with the rest of your table joins. Note 1: I called the table name.column because shared names will usually throw an error because SQL doesn't know which ID you are referencing otherwise. Note 2: If you don't have evaluations for a district, you may want to do a left join so you still pull in all your other data.

If you have schools not assigned districts you may want a full outer join. You will get null values in district for the specific school missing data, along with all the good matches.

These are pretty simple joins (id to *_id). Sometimes you will need id and city for example. It would be 'on district.id = school.district_id and district.city = school.city'. Then it gets more fun as you go deeper.

2

u/Zestyclose-Turn-3576 13d ago

> Eww, the same name (id) being used for different things in each table is messy. Be careful on your joins.

Not uncommon, and in fact the default for ActiveRecord-generated schemas, but it's a good habit IMHO to prefix all column names with a table alias in a query with joins, to help future developer understanding

1

u/BarelyAirborne 13d ago

SQL databases has things called "foreign keys". What that is, is a column that references a key in another table. Example, an order table might reference a customer code in the customer table. If your database's designer was sane, they named the field logically and consistently i.e. they all end in "Key" or "Id" for example. And hopefully the table name ref, i.e. "CustomerId" and not "JRandomFieldX".

To collect the entire order data, you may need to join the order header to the customer table, and the order header to the order detail rows as well. These can all be mixed into the same query output.

SELECT tells SQL the columns

FROM tells SQL the tables

JOIN tells SQL how to fit them together.

1

u/Far_Swordfish5729 13d ago

Start here. https://ptgmedia.pearsoncmg.com/images/9780735685048/samplepages/9780735685048.pdf

Best explanation I’ve read. Sql lite will use a limit clause instead of top and apply is sql server specific.

I’ve explained this in this forum several times and others have written good explanations as well. Let us know what doesn’t make sense.

1

u/Hour-Measurement-835 13d ago

Build the query in the order the database actually runs it, and look at the rows after every step. SQLite runs FROM and the joins first, then WHERE, then GROUP BY, and SELECT comes last even though you write it first. That's a lot of why it reads backwards.

So start with just the FROM and the JOIN, with SELECT * so every column shows. A join glues each row on one side to every row that matches on the other, so if a customer has 3 orders, that customer is now on 3 rows. Stare at that before you go any further. When a grouping question gives you a count that's too high, it's almost always because the join quietly multiplied the rows and nobody looked.

Add the WHERE and run it again. Only then add GROUP BY. Think of it as sorting the rows you can already see into piles, one pile per value, and COUNT or SUM squashes each pile down to one line.

Subqueries are the same habit. Copy whatever's inside the brackets, run it on its own, and see what comes back. If it's a list of ids, the outer query is just using that list like you'd typed it in.

1

u/mirinai_ai 13d ago

For joins in general, it helps to think of a join as building one wider table first. Everything you already know (WHERE, GROUP BY, HAVING, ORDER BY) then runs on that wider table as if it were a single table. The ON line is the only new part. It says which row on one side lines up with which row on the other, usually one table's id matched to the other table's ..._id column.

A subquery is similar: the inner query runs first and hands back a value or a list, and the outer query uses it as if you had typed it in by hand. Running the inner query on its own first, to see what it returns, takes a lot of the mystery out of them.

1

u/ontirius 12d ago

cs50 goes from one tiny example to a problem set that needs three concepts at once, that wall is normal. at work i almost never write nested subqueries, i write them as CTEs (with x as (...)) so every block has a name and i can run it alone and check the rows. nested or CTE is the same query, one is just readable. the ones worth learning separately are correlated subqueries, they run once per outer row and thats where the confusion actually lives

1

u/Discordbothost 12d ago

Try drawing two customers and three orders on paper. For each order, copy its matching customer's columns beside it. That's the joined table your WHERE and GROUP BY work on. Predict those three rows first; it separates understanding the join from learning the syntax.

1

u/squadette23 12d ago

the course material basically just shows one or two examples of subquery, and very modest examples of joining

I need someone to break down subquery and joins in... human language

You may be interested in: https://kb.databasedesignbook.com/posts/systematic-design-of-join-queries/ and its prerequisites (see "A modern guide to SQL JOINs")

1

u/nicopassaglia 1d ago

Late to this, and glad you got through it. For anyone who lands here stuck on the same week, the framing that tends to unlock it:

A JOIN makes one wider table. It glues each row of one table to the rows of another that match on a key, and then you query that wide table like any other. If a customer has three orders, they show up three times. Most join confusion is forgetting that.

A subquery is just a query whose answer you use somewhere. It comes in three shapes, and it helps to ask which one you need:

- one value: WHERE amount > (SELECT AVG(amount) FROM orders)

- a list: WHERE id IN (SELECT customer_id FROM orders WHERE ...)

- a table: FROM (SELECT ...) or a WITH block

Read them inside out, and run the inner query on its own first. If you can't say in a sentence what the inner one returns, the outer one won't make sense either.

The next wall after this is usually NULLs: NOT IN with a NULL in the list returns nothing, with no error. Worth ten minutes before it bites you at work.

If more practice helps: I built a free set of short drills for exactly these two topics, in the browser on SQLite, no sign-up. Joins: https://getsheetdrill.com/sql/lessons/3 and subqueries: https://getsheetdrill.com/sql/lessons/4. Disclosure, it's my project.