243 points · by todsacerdoti · 3y ago · 170 comments
I recently learned this is also what Amazon recommends when querying Spectrum. [1]
[1] https://aws.amazon.com/blogs/big-data/10-best-practices-for-...
The example in this article can manage to do without a join because it's only using the other tables to filter the customer table. The proposed solution breaks down as soon as a column needs to be brought in from the other tables (for example, "the total number of products purchased from the Beauty category"). A notion as simple as "I want to return a list of customers with additional properties" does not map to any dedicated SQL construct ! You can JOIN then GROUP BY, but making sure that the result only has exactly one value per customer is not something you can explicitly say in your SQL, it's a consequence of how you set up your JOIN and GROUP BY keys, and it's both easy to make a mistake and hard to understand the intent.
You can, you say it by grouping on only columns from the customers table, and those columns including a candidate key. Necessarily and equivalently, this means everything not from the customers table must be only referenced in an aggregate expression, but that's trivially what “I want a single row per customer, with some data not from the customers table” is asking.
> it's a consequence of how you set up your JOIN and GROUP BY keys,
Well, its a consequence of the GROUP BY. which is literally “what do you want one row for each of”, so... it's kind of weird to complain that it should be something else. GROUP BY is the dedicated construct in SQL that soecifies the thing you are looking for.
SELECT Customer.Name, sum(Sales.Quantity)
FROM Customer
INNER JOIN Sales ON Customer.A = Sales.A
GROUP BY Customer.B
Can you tell whether this will return exactly one line for each customer ? If INNER JOIN + GROUP BY was the dedicated construct to do so, then the answer would be "yes", because by definition it is the dedicated construct to do so. That's what a dedicated construct does: it is dedicated to doing that thing.But both INNER JOIN and GROUP BY are much more versatile than that. In order to return exactly one line per customer, the following must be true: 1. column Customers.B must be a unique key of the Customers table (otherwise you'll get duplicate lines), and 2. each value of column Customer.A must also appear in column Sales.A (otherwise you'll have missing lines). Neither of these properties can be ascertained by looking at the query alone.
A dedicated construct would be something like (imaginary syntax):
SELECT Customer.Name, sum(Sales.Quantity)
FROM Customer
INNER JOIN Sales ON Customer.A = Sales.A
GROUP INTO CustomerI can tell it will return one row for each Customer.B.
If Customer.B is a candidate key of Customer, that will also be one eow per Customer.
> If INNER JOIN + GROUP BY was the dedicated construct to do so
The dedicated construct to say what you want one row per is GROUP BY. Yes, it operates by columns, not tables, so what it means in table terms is schema-dependent.
> each value of column Customer.A must also appear in column Sales
Well, yes, that’s what INNER JOIN means. The dedicated construct to assure that every row from the first source but not the second source table is included in the result set before filtering by WHERE is LEFT [OUTER] JOIN.
If you can't define what a "customer" is via the information in your database alone, then you can't query based on "a customer". And if the answer is "each row in Customer with a unique B", then that's part of the definition and reasonable to use as knowledge in getting "one row per customer".
I didn't explain that well, I think... but that's the general thought that was running through my head as I read your writing.
For number 2, that's exactly what inner join means otherwise use a left join. The first question someone should ask themselves is if they want all customers or only ones that have had sales.
I think the problem is fundamentally that if you take a record, and split it across 2 tables, then there's no easy operation to merge them and guarantee distinctness.
Separately, even though there are some %-breakdowns in the article, I don't think the `DISTINCT` sort is so much of a problem in most cases. Usually the actually joining is the problem for any truly large dataset, so while I trust the diagrams shown, I think those %'s change dramatically based on the underlying data.
I train people new to SQL at work, and I can tell you with complete certainty that you only get this impression because people learn very quickly to never use `distinct`.
It's by far the most common cause of performance problems for people new to SQL.
Even if you scale down on customers by two orders of magnitude, the intermediate table starts growing rapidly.
Also, the good news is the planners are increasingly better at converting your desired end state into queries utilizing features like this, without you explicitly telling them to.
a temp table with unique/primary key on custumer really helps if uniqueness is a requirement.
When you write `SELECT DISCTINCT a, b` you are asking for every unique pair (a, b) in the result. Specifically, the same value of `a` could appear multiple times in the result paired with different values of `b`.
The only way to implement that "generally" is to visit all of the rows in the result-set, and skip over duplicates using a hash table of "already seen" pairs, or by sorting the result. The problem is that this intermediate result-set is much bigger than we really want.
As a human, we look at this and think "Oh, but `a` is the primary key (in this case CustomerID) and `b` is a column in the same table (CustomerName) so we only need to be distinct over `a`, which means the query optimizer should be able to "push down" the DISTINCT clause into the scan of the joined tables". The problem is that the query optimizer has not been endowed with this kind of knowledge about the specific relationship between `a` and `b`, and so cannot do this optimization. In principle, a query optimizer could implement this kind of optimization though.
At this level you really start getting into the nitty gritty of what optimizations a particular database has implemented though: the solution presented in the article may be the best way to write this for SQL Server, but this "correlated subquery" form could be catastrophically slow in other database engines...
This isn't quite right; there are two general ways. One is a hash table as you say, the other one is sorting. The second is quite relevant once you have a reasonable framework for interesting orders (e.g., scanning along an index, or doing sortahead on a smaller table with a foreign key that guarantees uniqueness).
> The problem is that the query optimizer has not been endowed with this kind of knowledge about the specific relationship between `a` and `b`, and so cannot do this optimization. In principle, a query optimizer could implement this kind of optimization though.
There are absolutely query optimizers that know this (try such a query in MySQL, for instance).
And this solves almost all of the problematic cases of this on practice. If the thing you are querying isn't a key, you will naturally think a bit further and not write the distinct.
I guess that kind of optimization just goes counter to the philosophy of SQL optimizers. I know that I would be deeply surprised if I found a database doing it, and not in a good way.
> I know that I would be deeply surprised if I found a database doing it, and not in a good way.
SQL engines do way more surprising optimizations than this. SQL is a "4th gen" language after all, meaning it's absolutely within the spirit that the database engine does whatever it wants to get the result.
A top level distinct to a query like this is a huge red flag. Even in a sub select or a join clause id rather have a group by than a distinct.
Exactly. People post a lot of things about SQL optimisation without knowing anything about it. Frankly, I'm getting really fed up with it on HN.
If your query processor is even marginally competent, ANY & EXISTS are indeed optimized exactly the same way.
A slightly smarter QP will perform as well for the equivalent IN condition, too.
We should write our code to be readable, but it is reasonable to expect that the reader knows the language.
User:
Explain Max/MSP's use of bang.
ChatGPT:
Max/MSP, often simply referred to as "Max", is a visual programming language for music and multimedia. In Max, the fundamental building blocks are "objects" that are connected with "patch cords". These objects can process, generate, or manipulate various types of data, including audio, MIDI, and other control messages.
One of the most basic and essential objects in Max is the "bang". Visually, a bang is represented by a small button in the Max patcher window. Conceptually, a bang is an event trigger. When a bang is received by an object, it tells that object to do something, often to execute its primary function.
Here's a breakdown of how the bang is used in Max:
Triggering Actions: Many objects in Max perform an action when they receive a bang. For example, the metro object (a metronome) sends out bangs at regular intervals. When connected to other objects, these bangs can trigger various actions in a patch.
Flow Control: Bangs can be used to control the order of operations in a patch. The trigger object, often abbreviated as t, is particularly useful for this. It can output a sequence of bangs (and other data types) in a specific order.
User Interaction: The bang object can also be used as an interactive button in a user interface. When you click on it, it sends out a bang.
Feedback: Bangs can be used to provide visual feedback. For instance, when a certain condition is met in your patch, you might use a bang to flash, indicating that the event has occurred.
Conversion: Sometimes, you might receive data, but you only want to know when the data has arrived and not necessarily what the data is. In such cases, you can convert any incoming data into a bang. For example, if you connect a MIDI note input to a bang, the bang will flash every time a note is played, regardless of the note's pitch or velocity.
In essence, the bang is a fundamental concept in Max/MSP, representing an event or a moment in time. It's a way to initiate actions, control the flow of operations, interact with the user, and more.
User:
How about a special value "dang" for propogating mistakes?
The concept of a special value like "dang" to propagate mistakes is an interesting and humorous idea. Let's explore this hypothetical scenario:
Purpose: "Dang" could be used in a system to indicate that a mistake or an error has occurred and has been propagated. Instead of failing silently or producing unpredictable results, the system would clearly mark the affected data or process with "dang".
Usage:
In a programming context, "dang" could be a special return value indicating that a function has encountered an error that wasn't caught but isn't catastrophic enough to halt execution.
In a database, "dang" could indicate corrupted or suspicious data that resulted from a known error but hasn't been cleaned or addressed.
Advantages:
Transparency: Instead of silent failures or cryptic error messages, "dang" provides a clear and human-readable indication of a problem.
Debugging: It could make debugging easier, as developers can quickly identify and trace back the source of "dang" values.
User Experience: For end-users, seeing a "dang" value could be a more friendly or humorous way of being informed that something went wrong, as opposed to a generic error message.
Challenges:
Overuse: If used too liberally, "dang" could become a catch-all for various issues, making it harder to pinpoint specific problems.
Misunderstanding: Without proper documentation or understanding, developers or users might be confused about what "dang" actually represents.
Standardization: For "dang" to be widely adopted, it would need to be standardized across platforms and tools, which is a significant challenge.
In essence, while "dang" as a concept introduces a fun and novel way to handle and propagate errors, its practical implementation would require careful consideration to ensure it adds value to the development and user experience.
Mind you, most of what I write are ad hoc SQL queries where I might write 100-200 queries in a single day. So that sort of thing really adds up. And it's in a strange place where performance isn't dire, since I can work on other stuff while queries chug.
PostgreSQL allows a zero-column `SELECT`.
If for ten years you always indented the code this way
Void F()
{ Foo();
Bar();
Baz();}
Then following snippet will seem hard to parse mentally: Void F()
{
Foo();
Bar();
Baz();
}
And vice versaIn that case, PostgreSQL has a feature where you can do this:
select distinct on (customer_id) customer_id, order_id
from orders
order by customer_id, created_date desc
And get all customer IDs with their latest order ID. select customer_id, max(order_id)
from orders
group by customer_id
order by customer_idalthough it would seem to be so by design, however design is only as robust as the thousands of individuals building on the system :)
It only seems so if you assume auto-increment is used to populate the order_id and that it always increases with time. That latter assumption is quite unsafe:
* Systems could have been merged with a bulk import of old orders into this one from elsewhere (assuming order_id is a surrogate key and there is a separate order code or such that is used to identify the orders externally).
* In fact, a simple insert of several records in the same statement will not necessarily get auto-increment values in the order you expect (in practise they usually do - but the DB engines do not guarantee this, it is an accident of other factors in their design rather than a defined behaviour).
* Because of optimisations for concurrency in the way auto-increment is handled, it is possible that long-running transactions could cause ordering discrepancies. In theory at least, in practise unless you've explicitly opted out of ACID-preserving locking semantics for those transactions I suspect these protections will stop this un-ordering happening by blocking the concurrency. This sort of issue is why you occasionally see unexpected gaps in auto-increment values.
* I have seen an example where an incrementing signed-int ID was getting too close to MAXINT for comfort, and as a temporary measure ahead of changing that ID to be a longer type the increment was reset to restart at MININT and head back towards 0 from there! This was with a 16-bit integer (I'm old enough to have been around when it was common to use them to save space, where we generally default to 32-bit these days) but the same could happen to larger types.
https://docs.snowflake.com/en/sql-reference/functions/min_by
Anyway I’ll happily fix these in my code on Monday.
The one book I’ve found and really enjoyed was “SQL Performance Explained”.
The relationships between them should be represented by bridge tables. Really there's only one relationship here which is product orders.
Why have the expense of a join in your select queries when you can just associate them properly during the insert in the first place?
Then you can simply select limit 1 from the bridge table and only have one scan on the customer table for the whole query.
> The relationships between them should be represented by bridge tables. Really there's only one relationship here which is product orders.
What?
There appears to be a mistake in the Products table, which only allows a product to belong to one category.
But the many-to-many relationship between orders and products is already represented in a bridge table, OrderDetails, and the one-to-many relationship between customers and orders is correct. Why would you have a bridge table between customers and orders instead of recording the same information in a column of the Orders table?
And... how is your bridge table going to operate without having columns for the PKs of multiple other tables? That's what OrderDetails is doing. What would you change?
Because as you said the relationship is one customer to many orders.
> the many-to-many relationship between orders and products is already represented in a bridge table, OrderDetails
The relationship between Orders and Products is one-to-many, not many-to-many. Also, OrderDetails is not a bridge table because it has the quantity of Products. Bridge tables should only have the IDs and it's not going to have one row per order nor per customer. It's going to have n rows where n is the number of categories a product in an order belongs to multiplied by the number of products in an order multiplied the number of orders made by a customer multiplied by the number of customers who have made orders. It's a lot of rows, but compresses very well and makes the queries simpler by flattening all these relationships into one. The only relationship that matters for this query is customers and product category, but you can query for any relationship without joins in this bridge table I'm proposing.
> That's what OrderDetails is doing. What would you change?
OrderDetails is messed up in other ways too. What is "LineItemID"? LineItem should have the quantity and price? That table isn't even defined in the example. OrderDetails is a bad table that needs to go. Your interpretation of what I'm saying is correct. I would add an actual bridge table (not OrderDetails) that relates the customers to the orders.
You're correct that OrderDetails, as written, does need to relate an order to all its products, but my point was that you don't need to join to query for all the customers who have made at least one order of a given category. You just need to select where the category ID matches.
> OrderDetails is messed up in other ways too. What is "LineItemID"? LineItem should have the quantity and price? That table isn't even defined in the example.
You could have answered these questions by just reading the example schema. LineItemId is part of the two-column primary key defined for the OrderDetails table. It's not a reference to anything; presumably its purpose is to define the order in which line items appear in an Order.
> OrderDetails is a bad table that needs to go.
I hope you don't do a lot of code review. Or much coding, for that matter.
The OrderDetails table already records how many strawberries were included in Bob's order of July 3rd.
Unless you mean something very different in which case some concrete examples would be nice.
If you can guarantee you’ll only store ASCII, you can safely use 255.
This is also probably a premature optimization for practically anyone to be fair. Even at 1 billion rows, you’ve only added 1 GiB of overhead, and at that scale that’s a small percentage of the overall size.
I remember that the ancient Pascal dialect I used in college had max array sizes of 255 because they used a single byte for the size.
Why does Lucene and derivatives (ES,Solr,etc..) not have the concept of a join? Always found it to be a major downside of them.
There, fixed it for you. /s
The only reason the product is specifically mentioned in that last part is because it mentions an optimisation that is possibly specific to SQL Server's query planner.
If you have such an allergy to the product that you can't process general advice from someone who uses it, there are clues you could have triggered your anaphylaxis earlier and saved you time: t-sql is mentioned in the site's side-bars, as is “Learn SQL Server” for that matter.
But I assumed that was dependent on the query planner; Oracle SQL, as I recall, has/had specific constructs for giving hints to the query planner.
Problems that can be “fixed” with DISTINCT but really shouldn't, an accidental cross-join being one I've seen many times, be are common to many (all?) SQL implementations and I don't think they are treat much better by any of them (they are generally mistakes, so prioritising optimising for them is not a good use of the query planner engineering team's time).
> Oracle SQL, as I recall, has/had specific constructs for giving hints to the query planner.
SQL Server has index hints much like Oracles, along with locking hints (which I think Oracle has similarly), and so forth, which can tweak the query planners behaviour. They are best avoided if other options are available because:
• they often only work well for a given data pattern, so you are just pushing the problem into the future when your data size has grown noticeably (in this context they are valuable as a temporary workaround, just make sure you treat them as such and work to remove the need)
• they potentially block optimisations that future versions of the query planner/engine can perform by forcing it a different way around
• sometimes they make explicit reference to objects (indexes usually), tightly coupling their names to things that others may not expect making accidental breaking changes more likely
Postgres doesn't have the same sort of index hints IIRC, but does have options that constrain the query planner in similarly to try make it prefer a particular path and/or avoid another.
(Not mine, and I don’t know the source)
What's the argument for avoiding distinct? Is it performance? I've often wondered if the (sometimes redundant) distincts slow things down. Perhaps it does, but just not enough that I noticed.
Primary reason: distinct on every select shows either lack of knowledge of schema, in particular which columns make rows unique, or unfortunate schema design. (Apart from niche cases, schema should be somewhat normal. I.e. column parent_name belongs in the table parent, not in the table student)
Select a from x where myuniquekey=1; —- guaranted to return 1 or zero rows, if myuiniquekey is actually unique.
Select a from x join y on x.parent_id = y.y_id —- guaranteed to return same amount of rows as exist in y, never more, never duplicates y rows. (N-to-1 relation)
If distinct is used in any of above, then question “why?” naturally arises.
In more severe case, leads to bugs:
Select distinct student.student_name, parent.parent_name from student join parent on student.parent_id = parent.parent_id —- silently discards rows, where by accident student/parent name combo matches several times.
Technically sql allows comparing unrelated columns (colour=last_name), but for vast majority of cases, when joining, one of the side should be joined using it’s unique key, and other side should be using it’s foreign key, which ensures that duplicates don’t appear randomly, and thus distinct is not needed.
Not if distinct is the default.
> Select distinct student.student_name, parent.parent_name from student join parent on student.parent_id = parent.parent_id —- silently discards rows, where by accident student/parent name combo matches several times.
Either with or without distinct can be a bug depending on what you are doing it for.
There are actually 4 variations on what you might want, and you can get all of them with distinct:
select distinct student.student_id, student.student_name, parent.parent_id, parent.parent_name from ...
select distinct student.student_name, parent.parent_id parent.parent_name from ...
select distinct student.student_id, student.student_name, parent.parent_name from ...
select distinct student.student_name, parent.parent_name from ...