r/SQLServer • u/Arkiteck • Oct 15 '19
Blog How to Think Like the SQL Server Engine: The Perils of SELECT *
https://www.brentozar.com/archive/2019/10/how-to-think-like-the-sql-server-engine-the-perils-of-select/2
Oct 15 '19
Can anyone confirm that select * is optimized for EXISTS and NOT EXISTS?
→ More replies (1)2
u/ComicOzzy Oct 16 '19 edited Oct 16 '19
It is. I've always written SELECT NULL instead, mostly as a signal to others less familiar with how SQL works that we aren't returning anything. (edit: TBH, it only helps by causing them to go ask or search to find out what is happening, and if it helps them learn, mission accomplished, I guess.)
2
u/Lothy_ Oct 27 '19
If you take the lazy path - select * - you invariably force SQL Server to defer to the clustered index.
This undermines the utility of other non-clustered indexes that may exist, and may contain all of the data that actually need for your particular query. But because of the *, they're regarded as incapable of satisfying the query.
11
Oct 15 '19
[removed] — view removed comment
5
u/Dragasss Oct 15 '19
Technically, the star is an additional ping to result set to look up all the available columns after performing all the joins, extensions and what ever the mess that you have done via your query. Explicitly listing out the columns just saves a single lookup to the result set and IS better because you are explicit about what you want from the query instead of leaving it up to the planner to do what ever.
5
Oct 15 '19
But select * can break your app when columns are added, removed, or changed. That’s the main problem.
3
Oct 15 '19
[removed] — view removed comment
3
u/angrathias Oct 16 '19
Have 2 tables joined to one another where they’ve both have a column with the same name and see what happens
4
u/ps_for_fun_and_lazy Oct 15 '19
It really didn't rocket surgery that select * is bad. I wish all SQL examples and training materials only taught select * as a bad practice to avoid.
2
u/Oddball_bfi Oct 15 '19
Here's one for you which I'd like a view on:
I use
SELECT *in views when I don't want to project, on filter, join or augment data in other tables.I don't write out all the column names because the views are payload agnostic and only care that the columns they need are there. Everything else should be passed on for the next query to deal with.
An example would be a view
CurrentProcessOrder- time slice of theProcessOrdertable.My questions: In this instance, is * still bad? Would writing out all the columns be better or worse? Am I missing a trick to do these operations in a more effective way?