Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does selecting specific values from an SQL statement improve efficiency compared to doing a "SELECT *"

Tags:

sql

mysql

This question has just came in to my mind, and I'm not in a position to answer it.

Let's say you are developing a news page for a website. In your table you would have the following fields:

ID, Title, Subject, Content, Time, Author, Keywords

On the actual page that the user will see, you may only want to display the following:

Title, Content, Keywords

Now, when you go to write the SQL statement, would it be better to write it as this:

SELECT Title, Content, Keywords FROM newstable;

Or as this:

SELECT * FROM newstable;

I always thought that using the former example would be far more efficient and quicker to use. However, I'm now thinking it might be quicker and easier to just use the select all statement.

Is either way right, or does it really matter how they are written?

like image 824
mickburkejnr Avatar asked Sep 13 '11 13:09

mickburkejnr


People also ask

What is the difference between SELECT and SELECT * in SQL?

SELECT column returns only the value of that column. SELECT * returns the value of every column in the table.

Should I use SELECT * in SQL?

That's all about why you should not use SELECT * in the SQL query anymore. It's always better to use the explicit column list in the SELECT query than a * wildcard. It not only improves the performance but also makes your code more explicit.

Is SELECT * faster than selecting columns?

Selecting distinct and less than all columns will always be faster than selecting *.


1 Answers

Yes, it matters for performance and other reasons.

  • When you select only the columns you need, less data must be returned. This means less time pulling it off the hard drive and sending it over the wire.
  • It is possible that the columns you select may be completely satisfied using a covering index, which can make the query many times faster
  • By specifying the column names, you are documenting what data you are using in your code. This is very helpful when you come back to do maintenance.
  • By not using *, you do not run the chance of your code breaking when columns are renamed, added or removed. If you are explicit with column names, you will get a query execution-time error, rather than the new result being blindly passed along to your code, where who-knows-what will happen.
like image 183
D'Arcy Rittich Avatar answered Oct 27 '22 14:10

D'Arcy Rittich