Why SELECT * is bad for SQL performance (2020)
tanelpoder.com
tanelpoder.com
Title is a bit click-bait-ish; I was expecting some deep insight of why this:
SELECT A,B,C FROM TBL;
was superior to this: SELECT * FROM TBL;
when the table had three columns. Instead we get a wildcards are bad argument; especially when that wildcard fetches data that you don't need etc; which I guess everyone agrees with.Select * is better from cte/temp table because you then only need to make changes in one place.
I'm not sure how much deeper it's possible to go.
If I had to choose (which usually isn't necessary) I'd say wildcards are the lesser evil.
Sure, but depending on number of records and/or implementation of the name lookup, it can add up over a large resultset, or have a slightly cost over many smaller queries.
Mind you, I think -most- implementations are smart enough to only need to do the lookup once for a returned datareader, but the cost is still there.
While I agree, there are some languages + db drivers where this is your only choice unless you roll your own. Go's sql package relies on order in the Scan method, for example.
Sometimes 'we' ask * instead of "gimme everything that starts with a number" because we may need to check that the column "ID" which is supposed to be a 10-digit number, may have an entry "A1234567890". And this has not raised any alarms. And this means that this human is not paying taxes, because his/her tax-ID is not 'run' when the gov runs the tax calculations, because the script pulls 10-digit numbers, and my ID has a letter. So some DBA got paid $50k, changed my field, run the thing, change back my field. If you think this is not happening, it is.
Consider other scenarios on obligations like that.
I once did a KYC audit for a bank. When I asked * , I laughed and cried with the results.
Soooooooooo.. yes, very click bait-y title. Each SELECT should fit the purpose it serves for the report reader. When doing KYC and you have to review 5mil clients, you want *, otherwise you will miss the: Surname: 123Smith!!!, DoB: 30/2/1980, and other duplicates, nasty surprises, people over 150yo, etc.
ie having `SELECT id, firstname, surname FROM people` would still catch 'A1234567890' and '123Smith!!!'
Where as `SELECT * from people WHERE id REGEXP '^[0-9]+$'` would exclude them despite being a wildcard SELECT.
Beyond that, when you are looking for anomalous conditions you don't say "get me all records," because how you going to pick out something that doesn't look right out of five million items? When you are looking for anomalous conditions you say "get me all records that are NOT in the form I am expecting." Then you add constraints, foreign keys, etc so it doesn't happen again.
> Instead we get a wildcards are bad argument; especially when that wildcard fetches data that you don't need etc; which I guess everyone agrees with.
#2 comment:
> Nevertheless in reality most of the stated reasons have almost no real practicability... So in most cases fetching to many columns would be no problem
This happens surprisingly frequently in a lot of tech discussions. The most popular comment accuses the author of saying something so obviously correct, that it's a waste of time to even bring it up. And the second most popular comment is someone telling the author that he's wrong.
When you constantly apply this "only things bigger than X matter" reasoning you still end up with slow, shitty software but you just died by a thousand cuts instead of 1.
This feels like a strawman. I have yet to see an instance of this in my 10 years. The much, much, much more common case is people justifying half-assed shoddy work with YAGNI.
I do end up shipping working software much sooner than if I optimized every statement everywhere.
Perhaps I do; but my main "accusation" here is that the title is pure click bait, if it was replaced by this:
SQL - Don't fetch data you don't need!
Would anyone here bothered reading it?For instance. “Select *” can be good for ad-hoc exploration (as long as you include a limit to the rows returned). It’s bad practice for shipped code because it can lead to binding issues, in code, when you modify or add columns.
“Select *” will almost certainly be optimized away by the execution plan but if you have blob data, could introduce a lot of unnecessary disk i/o.
Is “select *” bad? It depends.
What do you mean? Ask for all the columns, you're gonna get all the columns in a resultset. Only in a subquery could the planner know what is unused.
'select ' is _perhaps_ tolerable for creating a view--under the conditions that the database transforms the query into the unambiguous named columns at view creation time--and that's about it.
What I mean is: like all other things, it depends. And with assumptions like this, it is generally better to measure.
This is very common IME, and it is a very bad code smell. It tends to break things very low in the architecture, so even capturing the error makes the application essentially not work in a fundamental way.
Cheers
https://slatestarcodex.com/2018/10/30/sort-by-controversial/
You would be surprised how many don't even think a second about it, not to say realize any of the points made by the author.
It might have changed but in ActiveRecord it was fairly common to do.
models = Model.where(column_name: column_val)
and then further down the fetch, just use two three columns from the whole fetch. This used to issue a `SELECT *` to the table if no select clause went along, and most people don't realise the harm with fetching all columns. Even if it is a single row, storage engines like InnoDB store blobs in an indirected way, which can lead to more read IO ops than required.Even without the optimisation bit, personally I prefer when code is explicit about what it is doing, like the data it is operating on/with. While omitting select makes the code succinct, having it there gives an idea at a glance about what it is operating with.
In all probability (we did say Oracle, which means enterprise), this application code is going to live forever, and never receive dev attention once it reaches functional status (unless something breaks).
Consequently, encoding something like "SELECT *" on the app side means that will never be updated, or even noticed, which is the same as saying it will be impossible to subsequently optimize.
Because you can't optimize specifics (these columns) from the DB side, when the only information an application gives you is generic (requests all columns).
Multiple this by 100 apps hitting the same core databases, and you start to see why it's a big deal, from an organization-lifecycle perspective (over 20 years+).
This is classic premature optimization. You don't know that overselecting will have any significant performance impact, and barring a few obvious cases (LOBs) it's quite unlikely to matter. There's a material cost in complexity to add situation-specific SQL vs the aforementioned:
models = Model.where(column_name: column_val)
Most databases make it pretty easy to find out what queries are consuming resources. Spend your time optimizing those.For starters, any software developed in any company with the ability to deliver updates in a timely manner.
When someone does something stupid and puts a whole bunch of unexpected data into that database, the latter query will cripple the entire show, whereas in theory the former will still just ask for the original intended data.
I've worked on a lot of databases and I've never seen the number of columns grow to the extent that it would impact performance in a large way. It might go from 8 to 11 columns, but I've never experienced anything like 5 to 55.
For a variety of reasons, if there's a whole new set of data (like customer survey responses to be associated with the customers table), or large data (like product thumbnails to be associated with the products table), to be associated with primary keys, it's added to an entirely new table that you can perform a JOIN on only when required.
Not to mention that while any application client can often add new rows to a database, they can't generally add new columns -- whoever administers the database often keeps those privileges for themselves for general security reasons.
It may just be one json column added to your Postgres table, but who knows how much space one row could take in production.
Another reason—if you have multiple databases (or just non-synchronous replicas) and do online schema changes, it’s possible to end up with different schemas visible on the same table. If you are confident that every engineer in your employ is an experienced SQL author and/or your ORM is perfect and would never access a column by index number rather than text name, you should be OK. Everybody else should query explicit column names.
It's infrequent because crappy development practises mean that when you try and change the schema a pile of people scream abuse at you because their crappy wildcard queries break, because the crappy code written around those wildcard queries shits the bed if the columns change in any way, shape, or form.
"Crappy wildcard queries" would seem to be the least of it, ha. Most of the time, a wildcard query that returns additional columns at the end won't cause any problems at all -- client software will just ignore them. Unless you're making each row 100x larger in size and you get a performance hit, but that's the point I was making -- that's not something that usually happens in reality anyways.
It's still not a great practice to use SELECT *, but at least this gives you a way to add columns without breaking existing applications. It's also useful when you plan to remove a column, to test in advance whether anything using SELECT * would break without that column there.
This is even more so when joins or views are involved, because the columns returned may change over time; joins particularly. Or, for that matter, migrations; while a CREATE plus ALTER may have resulting in a particular column ordering in 2002-2017, the new DB using the CREATE that rolls up all those changes in 2018 may result in a different column ordering, with subsequent broken code (which will be blamed on the DB by the thoughtless programmer, of course).
For API Stability:
- querying only the columns you really need makes it less likely that a column you don't really need happens to somehow brake your code if changed (e.g. because some ORM mapping not working). (This btw. is one of the major drawbacks of many REST APIs, i.e. they default to the rest equivalent of ).
- deciding the order in which you want columns to be returned explicitly is less bug prone to a variety of bugs, relying on column order of `` is brittle but some ORM do so and some other code might do so by accident in some way or another. Explicitly defining the order makes it easier to avoid such bugs.
- SQL queries doesn't need to be updated if you add columns (to explicitly not query the for the query unnecessary new column)
They re correct in an "academic view" but most applications are CRUD and based on an ORM and there are not many columns fetched too much which will make any difference. There are some rare cases where these statements are correct, especially the lob fetching but in these cases most often the queries are switched to manually specifying the columns just for these tables.
What is really needed would be something like SELECT * EXCEPT verylargecolumn FROM mytable ... So in most cases fetching to many columns would be no problem, but if there is really a column which is probelamtic you could easily request to ignore it.
COUNT(column) means in reality COUNT(column is NOT NULL), so if the column can have nulls the values need to be checked. But in most databases there is no difference in performance because the query optimized is intelligent enough to check whether the column can have null by definition and switches to COUNT(*) if there can't be nulls. In some databases COUNT(primarykey) is even faster, but these are all optimizations most often not needed, so micro optimizations as the query optimizer is intelligent enough to choose the best logic ;)
EDIT: PostgreSQL might be able to optimize that with LLVM but for short running queries it won't.
I suspect that stems from the fact it doesn't have the pregenerated statistics that other databases have, and therefore there isn't much scope to make a smart query optimizer.
There are improvements to decrease data scanned, for example, good sort orders and partitioning. BQ supports predicate pushdown for both of these.
Do you actually believe that most CRUD apps use an ORM?
I wouldn't say the ORM is "for prototypes/pocs", but rather it should be the default and raw SQL is "complicated stuff only".
When fetching from views, selecting unneeded columns can trigger unneeded JOINs.
Assuming no JOINed column is mentioned in the select list (either explicitly or through *), the query optimizer can eliminate the OUTER JOIN, or INNER JOIN when it is known that the referenced row exists (because there is a FOREIGN KEY).
This is mentioned in the article as "Oracle’s join elimination transformation", but (most?) other databases can do it too.
Let's say we have the following two tables and a view that joins them:
CREATE TABLE PARENT (
PARENT_ID int PRIMARY KEY,
PARENT_NAME varchar(255)
);
CREATE TABLE CHILD (
CHILD_ID int PRIMARY KEY REFERENCES PARENT,
CHILD_NAME varchar(255)
);
CREATE VIEW PARENT_CHILD
AS
SELECT
*
FROM
PARENT
JOIN CHILD
ON PARENT_ID = CHILD_ID;
Now if you select any fields from PARENT, the query plan will physically access both PARENT and CHILD. For example: SELECT
*
FROM
PARENT_CHILD;
SELECT
PARENT_ID,
PARENT_NAME
FROM
PARENT_CHILD;
But the following would physically access only CHILD (because it knows that for any existing CHILD row, the corresponding PARENT row must also exist): SELECT
CHILD_ID,
CHILD_NAME
FROM
PARENT_CHILD; SELECT
PARENT_ID
FROM
PARENT_CHILD;Application reliability for me is the main reason. Better performance is just a plus.
A lot of best practices from 20 years ago are no longer valid. Like the excessive normalisation. These days data storage isn't always the major limiting factor anymore, in many cases it's better to have less tables with more data.
Like using name=result_row("name") instead of name=result_row(1)
The former works even with SELECT * irrespective of the order of the columns. The latter won't.
Also, selecting all the columns at once has an ergonomics effect of making it simpler to take advantage of caching when writing multiple components which might query the same data within the same execution.
That being said, I do think selecting less columns is better than more, an even when using an ORM I find myself writing projects and helper objects to reduce how many columns I need in my queries, but I view that as more of an optimization, a secondary concern that I can take care of after the main logic is implemented, rather than a primary concern that should shape the initial implementation of the logic.
Of course, the performance concerns I have had might be vastly different than the original poster's, so take my comment with a grain of salt.
SELECT * seems like a strawman to me. I don't often see it in the wild anymore. But pulling more columns than you need is extremely common; it happens in every codebase I've ever seen. I habitually do it myself. More-or-less every time I choose to re-use a single function for retrieving data in several places. Because then the function needs to get the union of all the columns that all the callers need.
Which may be a reasonable trade-off. There's almost always a need to strike a balance between maintainability and performance. But it's also nice to have occasional reminders to re-assess what you've been doing. This particular practice tends to have a particularly high cost, and one that, depending on how you configure your environments, may be much larger in production than it is in development or CI.
var user = repository.GetUserById(userId);
return user.IsDisabled;
That's not even a facetious example, I have seen it multiple times. In some cases that query is pulling multiple columns, and a few joins.. just to pull a single bit value.For example, there's nothing about the code example you give that strictly implies the use of an ORM, just the use of some sort of layered design.
In that scenario, this can be strictly more efficient than doing a specialized query here, and a more general fetch of the user later, because it becomes just one sql command instead of two.
Obviously though there are ORMs that don't offer such caching, or cases where the value will not be used again elsewhere in the request, and in those cases this is clearly undesirable. It is generally quicker and easier to do this than adding a new custom method to the repository to get exactly the desired data which is why it remains common even in those scenarios.
For example, R's dbplyr library lets you write queries that select all columns that start_with("something_"). This is revolutionary, because now a person can use the semantics of column names in their selection!
Granted, dbplyr ultimately generates a query that explicitly names the columns, so it's not a within-SQL solution, but I've been surprised at how useful the behavior is!
Break that monster into smaller, more manageable tables and architect your database such that you can obtain exactly the data you need with well indexed joins, cached lookups, etc.
(to be clear, I still enjoyed reading this.)
However, those things have always been exotic, and with the advent of SQLite have become even less common.
SELECT * EXCLUDE g, m, p, x FROM table
There's use for the wild card, for instance if you need ad hoc query of data during development or testing.
If your table is not properly indexed however, will cause unnecessary select all query even if you didn't intend to.
Junior developer is bad for SQL performance but hey, everyone starts there, so there's nothing to be embarrassed about. Just code on!
"SELECT *" should be just as performant as "SELECT A, B, C" when your object only has A, B and C as columns.
The arguments presented in the article may or may not be applicable to your particular application, but I think it's a solid principle that you shouldn't assume your database will retain its schema indefinitely. If you're relying on "SELECT *" to mean "SELECT A, B, C", you're in for a bad time.
this is not a hard thing to anticipate and yet my coworkers thought otherwise...
However, it still stands true in a test of time when you will end up with a lot more columns.
But I didn’t say it’s a good idea to do SELECT * (I never use it outside manual queries), just that it has no performance implication just by virtue of using it.
Select “a” from “b” where “c” = 1;
With a composite index on c and a allows you to fetch everything you need without even looking at the table.
In some cases on big databases, adding covering index is the way to make your apication perform well, by eliminating those table lookups.
If wire-level payload size IS your big concern you should probably be looking at an entire myriad of things beyond your projection, like the actual query, or your protocol or caching or if you should even be using a RDBMS.
Yes, you should be more explicit in your queries, in which case
SELECT A,B,C FROM TBL;
should likely become
SELECT t.[A] ,t.[B] ,t.[C] FROM TBL t;
YMMV
Probably the most common code run in my Datagrip instance. I run it so frequently that I created a parameterized version with a shortcut.
In theory, this makes sense, but 800 column is already another problem for your application/system. What if you need to select 196 of those columns, what are you going to do? What kind of SQL or Java/Python/NAME_HERE_OTHER_LANG code are you going to write to select those fields?
Plus, despite everything, the optimizer is not perfect and some extra columns might change your query plan (Sybase had so much fun with this stuff).
plus, if you do LIKE* the performance will go nuts
“The real problem is that programmers have spent far too much time worrying about efficiency in the wrong places and at the wrong times; premature optimization is the root of all evil (or at least most of it) in programming.”
~Knuth (or maybe Hoare)
If you have indexes on column A but not B selecting * (a+b) will also need to fetch the row, otherwise it can fetch only the index.
The end.
To be fair, I've been using sql and optimizing it for a decade. The number of times "select *" was the offender was a minority. Typically N+1 is the biggest performance issue in modern frameworks and newer developers. Following that is complex logic that can be simplified to a more efficient sql.
select (star) is so far down the causes of slowdowns it is hardly worth mentioning 95% of the time.
0% of the time was db->server bandwidth the issue. Otherwise you're probably fetching a gig of data instead of filtering it in sql or paging.
But that’s the point of ORMs. Disregard anything that makes your database different than any other, and any of its optimizations, so that you can pretend raw data fits an OO-paradigm and feel safe because you can go `customer.name = “dork”; customer.save();` and make anything more complicated than that Somebody Else’s Problem.
So in some cases its better to select the whole object by primary key because some other method would do that later anyhow and now its in the cache and will skip an extra db call.
.NET ORMs don't do this (at least Entity Framework Core)
`db.Users.Select(x => new { x.Name, x.Age }).ToListAsync()`
will perform something like `SELECT Name, Age FROM db.Users`
but ofc if you tell it to load everything `db.Users.ToListAsync()`
then it will perform
`SELECT Name, Age, Salary, ... FROM db.Users`
but not *
People tend to say that: EF Core for saving data in db (because it detects changes and shortens code really hard)
and Dapper for reads - writting manually good queries
If you're suggesting ORMs are bad because they make developer lives easier, I don't understand how one relates to the other.
Raw database queries aren’t difficult except in extreme edge cases that most ORMs aren’t smart enough to handle either. ORMs do make things slightly “easier”, but that comes at a cost. Whether that cost is in terms of performance or complexity or developers losing understanding/knowledge of how to build code that leans into the benefits of whichever database you choose comes down to whichever ORM you’re using, but that trade off will always be there.
And either way, 99% of people using any random ORM have no idea whether a `select *` is being used or not. That’s the whole point. You put blind faith into whatever ORM believing it will do the “right”/“most optimized” thing.
Another thing that speaks for raw SQL is that it's a lot easier to debug queries, just copy/paste the query into your SQL editor and start figuring out what's wrong, you can't just do that with an ORM.
yea, that's the point where things start getting exciting when you have logic in queries that you actually have to debug.
I too love 200 LoC (tiny, in fact) procedures that inside build ""dynamic SQL"" aka string concat and EXEC with many OUTPUT parameters
10/10 experience, would recommend it to everyone.
No, I don't want to debug my queries because it means that I'm probably doing too much on the database.
I treat database more like a fancy data storage with outdated language, not as a business logic layer.
A lot of times, the technically 'optimal' solution isn't necessarily optimal.
No, the point of ORMs is to map between relational databases and object-orientated programming environments, both of which are things which exist for good reasons.
Your analysis is shallow and ill-informed – particularly given that many ORMs will very carefully select the columns which are selected in any particular query.
If you’re using an ORM this whole article is moot to you. You don’t decide whether `SELECT *` is the being used or not (let alone more complex optimizations), and if you do actually delve this deep into your ORM you are in the vast minority of coders
if you’re using an ORM it’s an architectural decision that was mandated early on in whatever project, so even if you did find out a naive `select *` is being used by your third-party ORM, the whole point would be moot because we can’t just switch out ORMs for this project.
So for most people using an ORM, this is useless information because either you don’t know/care or your organization won’t let you know/care because they’re already doing it that way organization-wide.
I'd argue that using an ORM as default and handcrafting optimized queries for specific edge cases should be the way to go.
All ORM's are not equal. It is a broad class of frameworks designed for different purposes and with different trade-offs. My favorite is EF Core which allow you to select exactly the fields you want or do the equivalent to "select *". I'm sure there other ORM's which support the same.
This so many times. I also think before people talk about an ORM they need to define ORM as they can range from something like Hibernate to a simple object mapper. Is something like jOOQ and ORM where I can write typed SQL and it maps results to objects?
I prefer writing SQL, but also prefer using a library that can do the tedious object mapping for me.