I’ve always preached to my developers that SELECT * is evil and should be avoided like the plague.
Are there any cases where it can be justified?
I’m not talking about COUNT(*) – which most optimizers can figure out.
Edit
I’m talking about production code.
And one great example I saw of this bad practice was a legacy asp application that used select * in a stored procedure, and used ADO to loop through the returned records, but got the columns by index. You can imagine what happened when a new field was added somewhere other than the end of the field list.
I’m quite happy using
*in audit triggers.In that case it can actually prove a benefit because it will ensure that if additional columns are added to the base table it will raise an error so it cannot be forgotten to deal with this in the audit trigger and/or audit table structure.
(Like dotjoe) I am also happy using it in derived tables and column table expressions. Though I habitually do it the other way round.
I’m mostly familiar with SQL Server and there at least the optimiser has no problem recognising that only columns
a,b,cwill be required and the use of*in the inner table expression does not cause any unnecessary overhead retrieving and discarding unneeded columns.In principle
SELECT *ought to be fine in a view as well as it is the finalSELECTfrom the view where it ought to be avoided however in SQL Server this can cause problems as it stores column metadata for views which is not automatically updated when the underlying tables change and the use of*can lead to confusing and incorrect results unlesssp_refreshviewis run to update this metadata.