117 points · by FedericoRazzoli · 4y ago · 132 comments
I swear to god whenever I search for something in the python standard library I have to scroll past a bunch of sites like this before i find the actual docs.
> It is important to understand the interaction between aggregates and SQL's WHERE and HAVING clauses. The fundamental difference between WHERE and HAVING is this: WHERE selects input rows before groups and aggregates are computed (thus, it controls which rows go into the aggregate computation), whereas HAVING selects group rows after groups and aggregates are computed. Thus, the WHERE clause must not contain aggregate functions; it makes no sense to try to use an aggregate to determine which rows will be inputs to the aggregates. On the other hand, the HAVING clause always contains aggregate functions. (Strictly speaking, you are allowed to write a HAVING clause that doesn't use aggregates, but it's seldom useful. The same condition could be used more efficiently at the WHERE stage.)
Thank you for linking this, it's very concise and actually helpful.
https://wikidiff.com/spam/spam
https://www.codegrepper.com/code-examples/python/frameworks/...
EDIT2: replaced statement of fact about WHERE/HAVING with this message.
It may be time to admit that general purpose search engines are fundamentally broken and that the only useful way forward is subject-specific search that allows users to be in control of their results.
I've been saying that since I first heard someone pitching SEO while eating lunch. Once you start gaming an index for visibility, Tragedy of the Commons goes into full swing, and the Yellow Pages ironically become a truer representation of actual local state. To this day, the memory of that...individual just going on and on casually talking pitching about what is no less than intentional pollution of the search structure of the collective knowledge of human still causes a hot nugget of incandescent rage and disgust deep within my soul. Before now, the thought of forgiving them has never entered my mind before now, and in this minute is quickly dismissed. I didn't know the person, they were themselves probably just trying to get by best they knew how. But I just can't seem to let it go. Poisoning the well like that... It either requires the most appalling sense of shallow callousness, profound ignorance, or a complete disregard for the integrity of our species' collective informational output. It's the burning of the Library of Alexandria by way of Salesman vying for attention. As time goes on the disgust only becomes becomes more pointed as the practice is normalized and refined to the point the way information is organized and made accessible on the Internet makes a bigger statement on what society really values than the indexed content itself does.
I'd normally say live and let live, but I'm getting increasingly bothered by the suffering and extra cognitive load foisted on the world by ads, marketing, etc..., and the lack of societal wherewithal to push back and say enough is enough.
Anyway, this rant brought to you by Libraries! Support your local branch today! Strike a blow for open access!
The bloggers themselves initiate the issue, and I don't see how subject-specific engines could completely solve that. Why would they be able to distinguish this article from a well written entry on a SQL topic that is not just a restatement of fairly basic knowledge? Docs don't cover everything, there's space for articles like this that follow the same basic structure but with more useful information, a and once people can infer a little bit about the search engine's algorithm from how it shows results then we're back to the SEO arms race.
But I wouldn't go as far as to say that the person who writes the website is not the problem. The content in these sites is usually borderline spam.
The thing is, documentation is (usually) written very dense, with a lot of assumptions about knowledge. The PostgreSQL documentation on WHERE vs HAVING is decent (https://www.postgresql.org/docs/8.1/tutorial-agg.html), but the MySQL documentation (https://dev.mysql.com/doc/refman/8.0/en/select.html) is ... a lot to read and not very explanatory for someone who only rarely deals in SQL.
Documentation writing is an art and most projects don't have the resources to have actually working documentation, much less understandable documentation - which is part of the reason why w3schools, stackoverflow, quora and random SEO "blogs" get so much traffic.
I think your problem is with search engines and not the writers of these articles, who probably don't consider you to be the target audience.
(This is not a comparison between the languages, just an oddity about the docs)
I created special "search engines" on my browser, so I start typing ":p" and whatever I write next it automatically searches using the site:python.org filter.
The standard library docs have their own search. Plus there is always help()
Preferably, SQL would look more like:
FROM Foo f
WHERE f.value < 10
JOIN Bar b on b.id = f.bar_id
WHERE b.other_value > 20
SELECT f.group, f.value
GROUP BY f.group the_group AGGREGATING SUM(f.value) the_sum
WHERE the_sum > 100
ORDER BY the_group
And so on. FROM introduces a source of data which flows into the next line. SELECT does a projection, GROUP BY applies aggregation operators on groups and also does a projection. WHERE could be inserted pretty much anywhere.It also cross-compiles to SQL and can thus be used to build queries, although the result is not necessarily the most efficient. Someday I hope someone with expertise in compilation and query optimization will take a look at dplyr and figure out how to get it to generate optimally efficient SQL.
If we did that, and also ported dplyr to some other languages, programmers might never have to hand-write SQL again. (LINQ might be a good way too, but I know much less about it)
[1] https://scholar.google.com/citations?user=YA43PbsAAAAJ&hl=en...
Dplyr was already great in its first version, but Hadley and company have worked incredibly hard to make it much, much better. It's hard to think of another system that has improved so much from such an already high starting point.
It was a fine language for its time. So was Pascal, and FORTRAN. We don't use those anymore generally for a variety of good reasons.
SQL ANSI nulls alone are a good-enough reason to toss it. Any language where "x = x" commonly returns an object that is treated as falsey is broken.
edit: I'm getting "You're posting too fast" so I can't continue this conversation, but no being able to express "unknown" is not worth throwing out the reflexive property of equality. That is a bad trade-off and I will die on this hill.
Nah. One of the most common uses of null is to communicate missing values in the sense of "this entity has this attribute but we don't know what its value is". This is a fundamental feature needed in data management.
So say you've got data on two balls A and B. You don't know what the color of either ball is. Is color(A) = color(B)? What's the best answer to this question?
Obviously it's "we don't know", and the value we use to communicate "we don't know" is null.
SQL nulls aren't broken. They're just a third option outside of True/False that needs its own handling, because reality is complicated.
PS: Contrary to popular opinion in certain coding circles, floating point arithmetic isn't broken either. It's a beautiful, delicate tool that works the way it does because it must in order to support its use cases (e.g. numerical linear algebra and representing continuous physical quantities). If it doesn't work exactly the way you want, you may need a couple guardrails or a different system like fixed point arithmetic.
The correct way to represent this, which has been widely used for several decades now, is sum types. If your value might be unknown, you need to explicitly represent this in the type of your value (e.g. Optional<Foo>) instead of relying on a hack that allows subverting the type system.
And even if it were a good idea, leaving the user with no built-in operators, not even a simple COALESCE(bool) to properly manage the null complexity? That's unacceptable.
Given a SQL boolean expression `f(b)` that can return true, false, or null, how do I test if `f(b)` has returned NULL? How do I handle that NULL case?
ANSI SQL gives users a strange new paradigm for boolean algebra and then says "GLHF" and gives you zero tools to handle the situation, not even linguistic features that would let you roll your own boolean-based functions, since you can't write SVFs that take boolean parameters.
I mean this trashboat of a language doesn't even let you bind boolean to a variable! You have to deal with the PITA of converting from Booleans to bits because those are totally different things.
I rarely use nulls like that. And then only for things outside of SQL databases like lazy loading or caching. And even then I still prefer null == null to be true.
If nulls are for what you have written then why we are calling them "null" - no value? Why not calling them "unknown". Even then what is benefit in introducing non boolean logic to a relational query language? I have never seen anyone using any of three-valued logic benefits when writing SQL. Every time I get unknown logical value it means I have made a mistake in my query, which would be better handled by rising an error.
For example, AVG(col) and COUNT(col) treat it as a missing value (NULLs do not alter the average or the count), but 1 + NULL treats it as an unknown value (the result is unknown). The complete list of NULL-related inconsistencies would be long.
It would have been better to use different words for different semantics, or not implementing NULL at all. Also, in some cases it can lead to poor query performance.
Every time someone tries to replace it, it eventually comes back again. Just look at the recent NoSQL and Big Data craze, and then how we're today with a miriad of SQL engines.
However, I would add that SQL is a very strong local optimum: a "good" language that keeps the good parts would be insufficiently different from actual SQL to convince anybody to switch.
Also people forget that querying is only half of the equation, there's DDL too.
Seems like an attempt to throw the baby out. 3-valued logic anyone?
So, any language using IEEE 754 floats is broken?
From(foo) |>
Where(Get.value .< 10) |>
Join(From(bar) |> As(:bar), on = Get.bar.id .== Get.bar_id) |>
Where(Get.bar.other_value .> 20) |>
Select(Get.group, Get.value) |>
Group(Get.group) |>
Where(Agg.sum(Get.value) .> 100) |>
Order(Get.group)
There is no HAVING and the you can use any tabular operators in any order. Aggregates are also separated from grouping and can be used in any context after Group is applied. JOIN Bar b
if you've defined the foreign keys before.The need to spell them out again and again is one of my personal SQL pet peeves.
GROUP BY is totally the opposite of what you expect. It NOT "group by"!,
This is group by:
1:
A
B
2:
A
C
If where like this (as in the RM) then you can bet other hacks like graph-ql where not necessary (and will make database more friendly to OO langs)I learned this (and most of my understanding of SQL) from https://blog.jooq.org/10-easy-steps-to-a-complete-understand... (point 2.), which was recommended by Hadley Wickham (of R tidyverse/dplyr fame).
SQL is not a great language. Serviceable, but not great.
test=# create table event (who text not null,
test(# what text not null,
test(# at timestamptz not null default now());
CREATE TABLE
test=# insert into event (who, what)
test-# values ('Bob', 'sent a message'),
test-# ('Alice', 'received a message'),
test-# ('Alice', 'sent a message receipt'),
test-# ('Bob', 'received the message receipt'),
test-# ('Bob', 'waited patiently for a response'),
test-# ('Bob', 'worried whether his message had been well-received'),
test-# ('Bob', 'paced'),
test-# ('Alice', 'forgot to reply for two weeks'),
test-# ('Bob', 'began to panic'),
test-# ('Bob', 'fled the country for Moldova in a fit of panic'),
test-# ('Alice', 'finally remembered to reply'),
test-# ('Bob', 'never got it');
INSERT 0 12
test=# select who as "The poor sod",
test-# count(what) as "Events"
test-# from event
test-# group by "The poor sod"
test-# order by "Events" desc;
The poor sod | Events
--------------+--------
Bob | 8
Alice | 4
(2 rows)Snowflake supports it - https://docs.snowflake.com/en/sql-reference/constructs/havin...
Redshift doesn’t: https://docs.aws.amazon.com/redshift/latest/dg/r_HAVING_clau...
Databricks doesn’t: https://docs.databricks.com/sql/language-manual/sql-ref-synt...
All of them do also support teradata’s QUALIFY clause which is like another layer over WHERE and HAVING that filters windowed data.
In theory¹ a DB that supports skip-scanning could use feedback from some HAVING clauses to short-circuit such a scan significantly, for instance if HAVING COUNT(*)<4 is present and a fourth row for that grouping comes up it can discard the row and skip to the next value. This would likely only be useful for indexes containing large numbers of the same few values though.
[1] I'm not aware of any engine that does this. It might be that the time cost of assessing if the optimisation is worthwhile² far outways the sum benefit over time of the saving when it is actually found to be worthwhile.
[2] Similarly, writing+testing+maintaining the code to do so might not be good use of dev time compared to other improvements
I will post the link later, if necessary in a comment.
SELECT x ... HAVING y => SELECT * FROM (x ...) t WHERE yThis phrase returns departments where the number of female employees is <10 right, rather than listing female employees from departments that have <10 employees in total?
SELECT department_id, count(*) AS employees_no FROM employee WHERE gender = 'F' GROUP BY department_id HAVING count(*) < 10;
The logical order in which the DB processes the query is: FROM Employee
WHERE gender = 'F'
GROUP BY department_id
HAVING count(*) < 10
SELECT department_id, count(*) as employees_no
so you apply count(*) < 10 after you filtered by gender and after you grouped by department_idExcept some databases allow for that syntax. The one we use, SQLAnywhere, does.
select category, sum(amount) as total
from mytable
group by category
HAVING total > 100
is equal to (and potentially more performant than) select category, total
from (
select category, sum(amount) as total
from mytable
group by category
) as mysubquery
WHERE total > 100I usually find CTEs to be a relatively tolerable middle ground of readability and performance (although I don't run from HAVING, either):
with category_totals as (select category,
sum(amount) as total
from mytable
group by category)
select category,
total
from category_totals
where total > 100;
Either way, subqueries are a code smell for me.Subqueries are indeed a performance red flag when the query is returning more than a few rows AND the subquery references fields outside of the subquery. Or put more simply, a subquery that will need to be executed an unreasonable number of times per run.
But so long as you aren't doing anything like that, and your database engine has a competent query planner, there should be zero difference in performance. For this reason I don't consider subqueries to be a code smell. For me a query is "smelly" when it does things which aren't obvious to a human parsing the query with their brain.
I've managed software teams and data engineering teams, and both teams get tripped up with even moderate SQL queries. To simplify, we encouraged teams to use a clearer subset of SQL. Most HAVING can be replaced with a WHERE inside a more readable and explicit subquery. Similarly, we got rid of most RIGHT JOINS.
[0] https://jvns.ca/blog/2019/10/03/sql-queries-don-t-start-with...
But seriously, this concept doesn't seem to require as much attention as this post gives it.
/thread
With no other language I have faced so many gotchas with implicit conversions and unexpected behaviors.
Cornell has a good explanation: https://www.cs.cornell.edu/projects/btr/bioinformaticsschool...
If you want to take a peek at an older revision: http://web.cecs.pdx.edu/~len/sql1999.pdf (I'm guessing this will be another case of be careful what you wish for).