Stats 21 - Lecture 24 - Intro SQL in Python
Overview
Miles Chen introduces querying the Chinook music-store database from Python with SQLAlchemy, SQLite, and pandas, emphasizing that writing queries is distinct from administering or designing a database server. He demonstrates selecting and filtering records, sorting, joining related tables, grouping and aggregating results, and using aliases, date conditions, limits, and a derived table to analyze customer purchases and invoices.
Key takeaways
- SQLAlchemy connects Python to a database, while pandas read_sql_query can execute a SQL statement and return its results as a DataFrame.
- A join connects related tables through matching keys, as when album.artist_id matches artist.artist_id; storing a numeric artist ID also avoids inconsistent spellings of artist names.
- LIMIT reduces the number of rows sent back to Python, making it a practical safeguard when testing queries against large databases.
- WHERE filters individual rows before grouping, while HAVING filters the grouped results, such as retaining artists with more than eight albums.
- The Chinook purchase data can be traced across customer, invoice, invoice_line, track, album, and artist tables to analyze what customers bought.
- A grouped query can be placed in an inline derived table and queried again, allowing invoice-level track counts to be summarized with operations such as MAX and MIN.
Chapters
- Miles Chen frames SQL as a way for analysts to retrieve information from an existing database, not a lesson in setting up or administering a server.
- He distinguishes query-writing work from database administrator responsibilities such as designing, maintaining, and managing a database.
- The examples use Chinook, a fictional early-2000s music shop database modeled around individual track purchases.
- The class uses SQLAlchemy and pandas to interact with the local Chinook_SQLite database file.
- SQLAlchemy creates a database engine, and its inspector retrieves table names including album, artist, customer, invoice, invoice_line, and track.
- A local SQLite file avoids the credentials and permissions needed to connect to a company database server.
- SELECT * FROM album returns every column and row from the album table, including album_id, title, and artist_id.
- A query can select only employee fields such as first_name, last_name, and title rather than returning every column.
- Miles demonstrates explicit SQLAlchemy connection and result handling, then uses pandas read_sql_query to fetch results directly into a DataFrame.
- ORDER BY birth_date DESC sorts employee records from the most recent birth date to the oldest.
- SQL tests equality with a single equals sign, as in title = 'IT Staff', rather than Python's double equals.
- Combining employee_id >= 6 with a title condition narrows the results to matching employees, including Robert King and Laura Callahan.
- The album and artist tables are joined by matching album.artist_id to artist.artist_id, connecting album titles to names such as AC/DC and Accept.
- Storing artist IDs separately avoids inconsistent text entries such as AC/DC, AC-DC, or AC DC.
- LIMIT 10 requests only ten rows from the database, which is useful when testing a query against a potentially very large table.
- GROUP BY artist_id collects each artist's albums into a group, and COUNT can report the number of albums per artist.
- The examples also use AVG on album_id to demonstrate aggregation, while noting that averaging an identifier is not substantively meaningful.
- HAVING filters grouped results, such as keeping artists with more than eight albums; Led Zeppelin and Metallica appear among the examples.
- SQL can calculate expressions such as artist_id * 2, illustrating arithmetic directly in a SELECT clause.
- The Chinook relationships connect customers to invoices, invoice lines to tracks, tracks to albums, and albums to artists.
- Table aliases such as customer AS C and invoice AS I make multi-table queries shorter and clarify which customer_id columns are being matched.
- A Brazil filter identifies invoices for customers such as Luis Goncalves and Eduardo Martins.
- Joining customer support_rep_id to employee employee_id links invoices and customers with assigned representatives such as Jane Peacock and Steve Johnson; AS aliases distinguish customer and employee names.
- DISTINCT on invoice billing_country returns unique country values, with 24 distinct countries shown in the example.
- Date conversion and BETWEEN conditions filter invoice dates, including a query for invoices within 2011; the example reports 83 invoices in the database.
- Grouping invoice records by invoice_date and counting invoice_id shows how many purchases occurred on each date.
- Grouping invoice_line records by invoice_id counts tracks per purchase; an inline derived table of invoice counts supports calculating the maximum and minimum line-item counts.
Transcript excerpt
0:02 Okay. All right. Well, um thank you all for joining me and uh happy Wednesday and happy day before Thanksgiving. Um so I hope you guys are all uh well and um and if you're watching the video recording, thanks for watching the video recording. So um I say we have covered what I wanted to cover regarding uh Python programming and getting started in Python. And so the remaining lectures um will just be kind of like miscellaneous topics. I won't put any of this stuff on the exam. So we're going to look at um some SQL sequel today, maybe a little bit next
0:50 week as well. I think uh maybe I'll do a little bit of showing you uh some Vibe coding and some tips uh regarding that and um I don't know, just some other uh things of that nature. Okay. So um regarding uh SQL and sequel, um all I'm going to attempt to do is try to cover how to um write a few queries in order to um access a database and get um desired information from the database. Um this is not a course and uh nor should you attempt to try to set up your
1:38 own uh SQL server. Okay? There's a big difference between setting up a SQL server and then learning how to write a few queries to interact with a SQL server that's already been set up. Okay? So we're going to learn how to just write some queries. Um setting up a server, designing a database, managing and administering a database, that is uh that's an entirely separate topic. Um and so, uh usually if you find a job and the job says you need to know SQL, then they're just asking for someone who's who's able to write queries and interact
This is the start of the transcript. Save this video free for the whole transcript, searchable and time-coded.
Related notes
Summary, takeaways, and chapters were generated by AI from the video's transcript and may contain errors. The video belongs to its creator, Miles Chen.