SQL for data scientists in 100 queries
gvwilson.github.io
gvwilson.github.io
- Rachel has a master’s degree in cell biology and now works in a research hospital doing cell assays.
- She learned a bit of R in an undergrad biostatistics course and has been through the Carpentries lesson on the Unix shell.
- Rachel is thinking about becoming a data scientist and would like to understand how data is stored and managed.
Data Scientists, back in the day, were largely people with both a fairly strong quantitative background and a strong software engineering background. The kind of people who could build a demo LSTM in an afternoon. Usually there was a bit of a trade-off between the quant/software aspects (really mathly people might be worse coders, really strong coders might need to freshen up on a few areas of mathematics), but generally they were fairly strong in each area.
In many orgs it's been reduced to "over paid data analysts" but I wouldn't even hire "Rachel" for a role like that.
Again, things have apparently changed.
https://en.m.wikipedia.org/wiki/Kullback%E2%80%93Leibler_div...
a measure of how one probability distribution P is different from a second,
ie. literally it's a separation measure for distributions .. just as I recalled from my first encounter with the notion ~ 1984 (ish).If you're sincere you should either add those points back or, preferably, expand upon your theory of how my snap take is incorrect.
( I'm aware it's not a metric due to triangle inequality, etc. )
The wikipedia page implies the opposite of that argument.
Perhaps that’s changed since 1984, but the proposition was about current practices.
As a fully anglicized US citizen born in Brooklyn, New York I don't think there's ever been any vowel confusion over the spelling of the name:
https://en.m.wikipedia.org/wiki/Solomon_Kullback
Admittedly I did check as it's not uncommon for mathematicians to have alternate spellings for their names.
Ditto Leibler, born Chicago, Illinois in 1914, no dropped L
You must protect the corporate overlords.
All of the information in the knowledge of Leetcode + category.
(Does it really matter WHICH question?? They are different but all the same. That is the point.)
you still find these kinds of people and roles at smaller companies but at largecorps, what's the point? the interesting modelbuilding you shunt off to your army of phd-holding research scientists. deploying models and managing infra goes to MLE. what's left is the data analyst stuff, which you repackage as "data science" because cmon, "analytics"? are we dinosaurs? this is modern tech, we have an image to uphold!
there's not really a need for, or supply of, people who can do everything (edit: _at largecorps_, obviously)
Oh sure, if you have teams of research scientists and machine learning engineers to shunt the work to. That's, like, what? 5% of companies out there? Less?
No need, indeed.
anyway that 5% hires a disproportionately larger # of "data scientists"
The term has always gone in a half-dozen directions at once, and ranged anything from
* an idiot making PPT decks for business presentations based on sales data; to
* a statistician with very sophisticated mathematical background but minimal programming skills doing things in R or State; to
* a person with a random degree making random dashboard in Tableau; to
* a person with sophisticate background in software engineering, data engineering, and related fields who can kind of do math
* an expert in machine learning (of various calibers)
* a physicist using their quantitative skills to munge data
... and so on. That's been confusing people since the title came out. It depends on the industry, and there's a dozen overlapping titles too, some with well-defined meanings and some varying from company to company (business analyst, data engineering, etc.).
For data cleaning we do tend to write the same sort of things over and over. And that’s where I think things could improve. Though what makes a data engineer special in my mind is that they get to know the nuances of data in detail. They get familiar with the columns and their meanings to the business and the expected volume and all sorts of things. And when you get that deeply involved with the data you clearly see where things are jarringly and almost like a vet to a sick animal you write data cleaning things because you care about the data that much.
(I've had a design in the works for years, and finally should have time and budget to implement it. Probably not helpful for legacy systems, though.)
There’s no email or other such thing in your bio. :(
I find AI has revolutionized anything one-off, and data stuff has a lot of one-off. 80% of the time, I can ask the LLM and get a solution which would take 1-2 hours to code which works.
* Verification of correctness is unnecessary or nominal, since it only needs to work in one case. If it doesn't handle complex corner cases as come up in software systems, there aren't any. And in most cases, the code is simple enough you can verify at a glance.
* Code quality doesn't matter since it's throw-away code.
It's something along the lines of:
"I have:
[cut-and-paste some XML with a hairy nested JSON structure embedded]
I want:
[write three columns with the data format I want, e.g. 3 columns of CSV with the only the data I need]"
Can you make a Python script to do that?
[Cut-and-paste script, and see if it works]
If it does, I'm done. If it doesn't, I can ask again, break it into simpler steps, ask it to debug, or do it by hand. Almost no time lost up to this point, though, and 80% of the time, I just saved two hours.
In practice, this means I can do a lot more prototyping and preliminary analysis, so I get to better results. Deadlines, commitments, and working time has not changed, so the net result is much higher quality output, holistically.
The bit about one-offs is not my experience. The idea being that writing connector code or extract stuff or even data cleaning changes based on the source and is usually put in production.
Ideal would be an endpoint to send data to like your example with sample data and then have it return after a prompt with the code needed or bypass the code just give me the subset of data that I request.
---
Step 1:
- I do a lot of exploratory and one-off analysis, some of which leads to internal memos and similar and some of which goes nowhere. I do a lot of prototyping to.
- I do a lot of whiteboarding with stakeholders. This is also open-ended and exploratory. I might have a hundred mock-ups before I build something which would go into prod (which isn't a lot of time; a mock-up might be 5 minutes, so a hundred represents a few days' time).
This helps make sure: (1) I have enough flexibility in my architecture to guide likely use-cases, and I don't overengineer for things which will never happen (2) I pick the right set of things.
---
Step 2:
I build high-fidelity versions of the above. These, I can review e.g. with focus groups, in 1:1s, and in meetings.
---
Step 3:
I build production-ready deployable code. Probably about a third of the thing in step 2 reach step 3.
---
LLMs do relatively little for step 3. If I have time, I'll have GPT do a code review. It's sometimes helpful. It sounds like you spend most of your time here, so you might get less benefit than I do.
For step 2, they can often build my high-fidelity mockup for me, which is nice. What they can't do yet is do so in a way which is consistent with the rest of my codebase (front-end theming, code style, tools used, etc.). I'll get something working end-to-end quickly, but not necessarily something I can leverage directly for step 3.
However, in step 1, they've had a transformational impact. Exploratory work is 99% throw-away code (even the stuff which eventually makes it to prod; by that point, it has a clean rewrite).
One more change is that in step 1, I can try different libraries and tools too. LLMs are at the level of a very junior programmer, which is a lot better than me in a tool I've never used. Evaluating e.g. a library might be a couple of days of learning with the equivalent of 5 minutes - 1 day of building (usually, to figure out it's useless for my use-case). With an LLM, I have a feasible lousy first version in minutes. This means I can try a half-dozen libraries in an hour. That didn't fit into my timelines pre-LLM, and definitely does now. I end up using better libraries in my code, which leads to better architecture.
So YMMV.
I'm posting since I like reading stories like the above myself. Contexts vary, and it's helpful to see how things are done in contexts others than my own. If others have them, please feel free to share too.
Which LLM are you using? ChatGPT enterprise? Something offline data / sql centric?
API (rather than web) is more convenient and avoids a lot of privacy / data security issues. I wouldn't use it for highly secure things, but most of what I do is open-source, or just isn't that special.
I have analogous scripts to run various local LLMs, but with my setup, the init / cooldown time is long enough that it's easier to use a web API. Plus my GPU is often otherwise occupied. Most of what I use my GPU for are text (not code) tasks, and I find the open source models are good enough. I've heard worse things about them for code, but I haven't experimented enough to see if they'd be adequate. Some of that is getting used to how the system works, good / bad prompts, etc.
ollama + a second GPU + a running chat process would likely solve the problem for around ≈$2k, so about the equivalent of a bit over a half-century of calls to the OpenAI API. If I were dealing with something secure, that'd probably make sense. What I'm doing now, it doesn't.
Data Scientist - a statistics major living in San Francisco
Strong coder who can implement an LSTM = ML Engineer
Decent coder who can implement a recent paper with scaffolding code = Applied Scientist
Acceptable coder who is good enough at math to innovate and publish = Research Scientist
Strong coder who cares about data = Data Engineer
Acceptable coder who has lots of domain knowledge = Business analyst, Data Scientist.
If you're just a Data scientist without any domain knowledge...... then you're in a precarious career position.
Job positions still want the latter, though. If I ever left my job I'm not confident I could get another job with the Data Scientist title, nor could I get a "ML Engineer" job since those focus more on deployment than development.
My R is embarrassingly rusty nowadays and I miss making pretty charts with ggplot2.
Jokes apart there used to be two categories of data scientists, those that came from a science/phd background where they duct taped their mathematical understanding to code which might work in production, and those those that come from a CS background that duct taped their mathematical/medium tutorial knowledge to an extravaganza of grid search and micro-services that made unscientific predictions in a scalable way.
So now we have the ml engineer (engineer) and the data scientist (science) with clear roles and expectations. Both are full time jobs, most people cannot to both.
but more seriously, unless someone's explicitly doing ML research for most applications using something off-the-shelf-ish[0] and tinkering with it works best. and this mostly requires direct experience[1] with the stack.
and sure, of course, if said project/team/org/corp has so much money they even can train their own model, sure, they can then afford to have these separate roles with "more dedicated" domain experts.
[0] from YOLO to LLaMa to whatever's now on HuggingFace
[1] the more direct the better. you have used LLMs before? great. pyTorch? great. you can deploy stuff on k8s and played with ChatGPT? well, okay, that's ... also great. you know how to get stuff from Snowflake/Databricks/SQL to some training job? take my money!
http://i.stack.imgur.com/eLrhI.png
vs
http://image.slidesharecdn.com/daml-150908205332-lva1-app689...
As a field of "science" perhaps.
In real life (when it became hot) data scientists mostly meant "devs doing analytics" and a lot of it involved R and Python, or the term "big data" thrown around for 10GB logs, and things like Cassandra, with or without some background in math or statistics.
What it never has been, in practice, was a combination of strong math/statistics AND strong software engineering background. 99.9999% of the time it's one or the other.
They have the courses and certifications to prove it, too. It's magic!
| domain knowledge | quantitative knowledge | technical knowledge |
--------------------------------------------------------------------------------------data analyst | high | mid | low |
data engineer | low | mid | high |
data scientist | mid | high | mid |
In my experience this intersection is a null set. And not just that it's an extremely rare feat to pull off IMO, the mental bandwidth and time needed to be good at one of those two alone would consume one person fully. This is why quant/stat specialists were paired with ETL/data-pipeline specialists to build end to end solution.
One reason Data Science became such a hot role back in the day was that it was amorphously defined; because no one knew what exactly it entailed folks across a broad range of skill sets (stats, data engineers, NoSQL folks, visualisation and so on) jumped into the fray. But now companies have burnt their hands, they have learnt to call out exactly what's needed; even when they advertise for DS role they specify what's required of them. For example, this page on Coursera[1] is clear about emphasis on Quant, which is a welcome development IMO.
[1] https://www.coursera.org/articles/what-is-a-data-scientist
edit: title has been updated: https://github.com/gvwilson/sql-tutorial/commit/14d1e57b94a8...
It's a great service when someone takes the time to document knowledge on a single page with quality examples, and trust the reader to follow along. Reminds me of the Rudin analysis book.
[1] https://third-bit.com/sdxpy/ (python version) [2] https://third-bit.com/sdxjs/ (js version) [3] https://aosabook.org/ [4] http://teachtogether.tech/
Edit: He wrote about this project here: https://third-bit.com/2024/02/03/sql-tutorial/
- Not single page _per se_ but I have plenty of Jupyter Notebook based tutorials here: https://github.com/DataForScience/
Self contained with slide decks and notebooks.
Also cool 'Zig Zen': https://ziglang.org/documentation/master/#toc-Zen
- Ruby: https://github.com/stevecondylios/ruby-learning-resources/bl...
- Rails: https://github.com/stevecondylios/ruby-learning-resources/bl...
But this vim cheatsheet was great:
A failed attempt was to load (very) many (e.g. about 100) pages of javascript lessons from w3schools before the plane took off, but for some reason the pages tried to refresh during the flight and I lost them all, so that was a massive waste of time (opening them all before the flight took about 20 minutes).
from the sudoku solver http://norvig.com/sudoku.html to things like "NPL in python" https://colab.research.google.com/github/norvig/pytudes/blob...
...
https://cryptopals.com/ (a remake of the Matasano crypto challenges) understand crypto by actually building and then subsequently breaking it (it's not strictly single-page, but wget can mirror it nicely)
Just run `rustup docs --book` after installing rustup
Edit: also an inaccuracy that's minor but can bite you if you're not careful - they mention temporary tables are in memory not on disk - that's not true in almost all sql databases, they are just connection specific eg they don't persist after you disconnect.
Some databases are optimized for a temp table to be a throwaway, but that can be a good or bad thing depending on the use case.
(gives the penguins.db file necessary for the examples)
Full outer joins and cross joins are different types of joins. A cross join returns the Cartesian product of both tables, while a full outer join is like a combination of a left and right join.
Better explanation here: https://stackoverflow.com/questions/3228871/sql-server-what-...
> A join that is guaranteed to keep all rows from the first (left) table. Columns from the right table are filled with actual values if available or with null otherwise.
This wording only works for identity equality join condition. It creates misleading mental model of left joins, and unfortunately is very common.
That model obviously doesn't work because if there's more than one match as the matching left row is duplicated for each match. However I don't understand their point of this being a problem when you don't have a "identity equality join condition", since this can also occur for equality joins as long as you're not joining on a unique key.
What really distinguishes an SQL master is working with queries hundreds of lines long, and query optimization. For example, you can often make queries faster by taking out joins and replacing them with window functions. It's hard to practice these techniques outside of a legit enterprise dataset with billions of rows (maybe a good startup idea).
HAVING is one of the standard clauses, I use it on mysql all the time and a quick search shows it exists for the others.
select
sex,
round(
avg(body_mass_g) filter (where body_mass_g < 4000.0),
1
) as average_mass_g
from penguins
group by sex;* Explain the difference between a database and a database manager.
* Write SQL to select, filter, sort, group, and aggregate data.
* Define tables and insert, update, and delete records.
* Describe different types of join and write queries that use them to combine data.
* Use windowing functions to operate on adjacent rows.
* Explain what transactions are and write queries that roll back when constraints are violated.
* Explain what triggers are and write SQL to create them.
* Manipulate JSON data using SQL.
* Interact with a database using Python directly, from a Jupyter notebook, and via an ORM.
I'm a non software type of engineer in my world a lot of tables are structured as timeseries data (such as readings from a device or instrument) which uses timestamp as a key.
Then we have other tables which log event or batch data (such as an alarm start and end time, or Machine start/machine stop etc).
So a lot of queries end up being of the form
Select A.AlarmId, B.Reading, B.Timestamp from Alarms A, Readings B where A.StartTime >= B.Timestamp and A.EndTime < B.Timestamp
A lot of people seem to have problems grasping these kinds of joins.
- https://clickhouse.com/blog/clickhouse-fully-supports-joins-...
- https://clickhouse.com/blog/clickhouse-fully-supports-joins-...
- https://clickhouse.com/blog/clickhouse-fully-supports-joins-...
- https://clickhouse.com/blog/clickhouse-fully-supports-joins-...
- https://clickhouse.com/blog/clickhouse-fully-supports-joins-...
https://stackoverflow.com/questions/784900/why-does-no-datab...
https://www.postgresql.org/docs/current/features.html
Clickhouse is simply a joke in comparison. No basic cursor support, no transactions, incomplete comparison operators, no single-row SELECT with GROUP BY and HAVING clauses grouped views, no procedures, no anti-joins or WHERE EXISTS, for that matter. The list goes on... it's basically impossible to write SQL to any degree of sophistication in Clickhouse.
Does exist.
> single-row SELECT with GROUP BY and HAVING clauses grouped views
If it's about grouping sets they do exist.
> no procedures
parametrized views/UDF/executable UDF (UDTF) exist.
> WHERE EXISTS,
Exists, but without Correlated Sub query part, which is honestly a joke because of how subpair performance it usually have compared to other alternatives.
Can you remind, does SQL:2023 standard finally allow you to use DISTINCT keyword in WINDOW functions?
Or people still forced to do horrible hacks with correlated subqueries or joins to do extremely simple thing like count Distinct in running window of X days?
> it's basically impossible to write SQL to any degree of sophistication in Clickhouse.
It's says more about engineer not DBMS.
I remember seeing it once and I can never find it now.
People, do both! Worth every cent!
It opens up with analyzing death row inmates, so significantly more real than classifying flowers.
sqlite> delete from work where person = "tae";
Parse error: no such column: tae
delete from work where person = "tae";
error here ---^
sqlite> delete from work where person = 'tae';
sqlite>*laughs in PTSD*
Badly then?
Personally I want my SQL queries to be written like a database professional.
Please suggest this entry level thing.
SQL is enduring because it is logical and understandable. But there is still an initial vertical learning curve.
I am trying to teach a friend of mine SQL but I’m not sure how to construct a lesson plan.
Is there a canonical SQL 101?
> [what this is] notes and working examples that instructors can use to perform a lesson
So use the resource to teach your friend.
Obviously there's a lot more to learn about many of these areas to really make the most of them, but this is a really good launchpad.
But im so used to ORM these days anything more complex then a sql join is already going over my head if i didn't do a sql refresher. As far as i have skimmed the article it seems like a very good refresher for even a SWE. I will definitely put this tutorial on my todo list.
I am a grumpy old man, fed up with newspeak
I am a grumpy old man, fed up with all this newfangled nonsense.
Little SQLer ("Little Squealer")