Some general tips when writing an SQL statement

One: only “tune” SQL after code is confirmed as working correctly

Two: code the query as simply as possible i.e. no unnecessary columns are selected, no unnecessary GROUP BY or ORDER BY.

Three: it is the same or faster to SELECT by actual column name(s). The larger the table the more likely the savings.
Use:
SELECT customer_id, last_name, first_name, street, city FROM customer;

Rather than:
SELECT * FROM customer;

Four: do not perform operations on DB objects referenced in the WHERE clause:

It is the same or faster to SELECT by actual column name(s). The larger the table the more likely the savings.
Use:
SELECT customer_id, last_name, first_name, street, city FROM customer;

Rather than:
SELECT * FROM customer;

Five: Avoid a HAVING clause in SELECT statements - it only filters selected rows after all the rows have been returned. Use HAVING only when summary operations applied to columns will be restricted by the clause. A WHERE clause may be more efficient.
Use:
SELECT city FROM country WHERE city!= ‘Vancouver’ AND city!= ‘Toronto’; GROUP BY city;
Rather than:
SELECT city FROM country GROUP BY city HAVING city!= ‘Vancouver’ AND city!= ‘Toronto’;

Six: When doing multiple table joins consider the benefits/costs for each of EXISTS, IN, and table joins. Depending on your data one or another may be faster.
Note: IN is usually the slowest.
Note: when most of the filter criteria are in the sub-query IN may be more efficient; when most of the filter criteria are in the parent-query EXISTS may be more efficient.

Seven: where possible use EXISTS rather than DISTINCT.

Eight: where possible use a non-column expression (putting the column on one side of the operator and all the other values on the other). Non-column expressions are often processed earlier thereby speeding the query.
Use:
WHERE SALES < 1000/(1 + n);
Rather than:

WHERE SALES + (n * SALES) < 1000;

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • E-mail this story to a friend!
  • MySpace
  • StumbleUpon

Comments

Leave a Reply




  • About

    HD Techblog is a collection of knowledge about Information Technology from HD Expertise. We, HD engineers, contribute many different topics from small technical things like programming tips to broad view such as technology trends, business review. Our aim is to help you to find useful knowledge for your work from our expertise.