Pages

Sunday, March 9, 2008

Introduction To Queries

This is the Database Programmer blog, for anybody who wants practical advice on database use.

There are links to other essays at the bottom of this post.

This blog has two tables of contents, the Topical Table of Contents and the list of Database Skills.

Today we are going to look at performance, direct SQL coding, and then begin with the basics of the SQL SELECT command.

Disk Activity Determines Performance

Before we even look at the SQL SELECT command, we must know what motivates the experienced database programmer to pick certain kinds of queries and avoid others. The first motivator is of course performance. We all want our programs to go fast. If you want a fast database program, then you have to think about the hard disk.

The slowest device in a computer is the disk drive. The price of disk reads is so much higher than in-memory operations that there is nothing to gain by optimizing code unless disk reads are optimized first. I often tell my programmers to consider in-memory operations to be "free" when coding, and to concentrate all optimization efforts on reducing disk reads. This approach may gloss over some important truths, but it is an excellent starting point for database beginners.

Optimizing disk reads comes down to writing efficient queries on top of well-designed tables. With that being said, we have one more short note to cover before going into the syntax of the queries.

A Quick Note on Inline SQL

Many authors and framework programmers discourage the use of SQL SELECT statements directly in application code. This essay contains no opinions on that question.

However, it is important to know that the SELECT statement must be coded somehow and sent to the server, whether you code it manually or some framework tool generates it for you. This essay is all about how to code (or generate) that SELECT statement. Knowing how it all works is a requirement if you code your own framework or if you suspect your chosen framework may not be your friend in all cases.

Introducing SQL Select

The simplest query is four words (or symbols) long. If your database has a table of countries then here is a very simple query that will work:

SELECT * FROM COUNTRIES

This query will return all rows and columns from a table. Depending on what language you code in, these may come back in an associative array, an array of generic objects (or similar), or some other special-purpose object like a ResultSet.

You have probably been told not to use the "*" in a SELECT, for performance reasons. This is usually good advice. In the simplest case, you save bandwidth by only retrieving the columns that are of interest to you. If your table contains long varchar or text (aka clob) columns there are even more reasons to avoid "SELECT *". When you have long varchar and text columns, they may be stored outside of the main storage for the table, causing the server to look in two places to retrieve each row. Therefore, avoiding "SELECT *" and always specifying just the columns you need reduces disk reads on the server and reduces bandwidth delivering the results.

But as this is an introductory essay it is important to know how to retrieve a complete table, so I have used the "SELECT *" here.

Filtering Results with WHERE

The WHERE clause limits which rows from the base table will go into the query results. You specify a WHERE clause as one or more boolean conditional expressions. Multiple expressions can be separated by AND and OR, using parentheses to group expressions. You can review your product's documentation to see all of the comparisons and functions that are available. A moderate WHERE clause might look like this:

SELECT country,name
  FROM COUNTRIES
 WHERE country like 'A%'
   AND (   name like 'D%'
        OR name like 'E%'
       )
   AND continent = 'Africa'

Filtering and Performance

The primary purpose of a WHERE clause is to obtain the correct result. However, it is also a very important performance tool. Here is why.

If you are completely and totally new to database programming, you may get the idea that you will skip the WHERE clause and do your filtering in the application. This may seem like a good idea because you save the trouble of learning two languages. Instead of learning SQL plus your application language, you can concentrate on just your application language. And so you make a reasonable decision to use as little SQL as possible and just do everything in application code.

The drawback to this perfectly reasonable suggestion is that it violates our first performance concept, it creates a huge disk read burden. If you need five rows out of 50,000, then filtering in the application requires the database server to read all 50,000 rows off the disk. On top of that, these have to be delivered to your application for processing.

Making use of the WHERE clause means that only 5 rows are read off the disk (this assumes the presence of an index which will be explained in a later essay). In this particular example, using a WHERE clause will perform 1000 times faster than not using it. Of course this is only a single very vague example, but since a database application is composed largely of queries, it is definitely a good idea to have all of these queries start out on solid ground.

Foreign Keys and JOIN

Next week we are going to look at JOINs in much detail, but I want to mention them here briefly. The JOIN clause lets you return results from more than one table, and the JOIN determines how the rows from multiple tables will be matched to each other.

For this week I will say only that good queries will almost always use foreign keys as the basis of their JOINs. We have seen in these essays more than once that the foreign key is the fundamental and only way to connect information in separate tables. Naturally, therefore, the foreign key will loom large in our discussion of JOIN, since JOIN controls the combined retrieval of information from separate tables.

Sorting Query Results

You can sort query results by including an ORDER BY clause in the query. Simply name the columns:

SELECT customer,order,date 
  FROM ORDERS
 WHERE date >= '2008-03-01'
 ORDER BY date,customer

Some database servers let you put an ASC or DESC in front of individual columns, while other servers can only apply a DESC or ASC term to the entire sort operation.

Overall application performance comes into play with ORDER BY clauses. It is almost universally true that you can sort faster on the database server than you can in your code. You want to make sure that your manual queries contain ORDER BY clauses, and that your framework is generating them. You do not want to be sorting in application code in most cases.

Order of Terms Matters

You have to put the various clauses into the right order or they will not work. The order is:

SELECT ....
  FROM ....
  JOIN .... ON ....
 WHERE ....
 ORDER BY...

Conclusions

This week we began to examine queries, by looking at the very basics of the SQL SELECT query syntax. Not surprisingly, performance issues came up for every single part of the query, from the column list to the ORDER BY.

For performance, we looked at the basic idea that disk reads determine performance, which we will see more of in later weeks. I also mentioned that table design determines query efficiency, but we have not gotten very deep into that yet.

Related Essays

This blog has two tables of contents, the Topical Table of Contents and the list of Database Skills.

Other essays relating to SQL SELECT are:

95 comments:

  1. I hope I'm not spamming the comments today :)

    I didn0t understand "However, there are other cases, especially when using varchar or text (aka clob) columns, when there are fewer disk reads when you avoid the columns you have no use for." How come you avoid columns with *?

    ReplyDelete
  2. Bruno, I rephrased the statement in question to make it clearer. The problem with long varchar and text columns is that they are stored outside of the main table storage area, forcing the server to go to two separate spots on disk. If you habitually do SELECT * you will force the reading of lots of data you probably don't need, on top clogging the pipe to deliver it to you.

    ReplyDelete
  3. awesome guidelines... THANK'S..

    ReplyDelete
  4. This is ansuperior writing service point that doesn't always sink in within the context of the classroom. In the first superior writing service paragraph you either hook the reader's interest or lose it. Of course your teacher, who's getting paid to teach you how to write an good essay, 
    online Python certification course | python training in OMR | Python training course in Chennai

    ReplyDelete
  5. Some us know all relating to the compelling medium you present powerful steps on this blog and therefore strongly encourage contribution from other ones on this subject while our own child is truly discovering a great deal. Have fun with the remaining portion of the year.

    Java training in Annanagar | Java training in Chennai

    Java training in Chennai | Java training in Electronic city

    ReplyDelete
  6. After reading your post I understood that last week was with full of surprises and happiness for you. Congratz! Even though the website is work related, you can update small events in your life and share your happiness with us too.

    Data Science course in kalyan nagar | Data Science course in OMR

    Data Science course in chennai | Data science course in velachery

    Data science course in jaya nagar | Data science training in tambaram

    ReplyDelete
  7. DevOps is currently a popular model currently organizations all over the world moving towards to it. Your post gave a clear idea about knowing the DevOps model and its importance.

    Good to learn about DevOps at this time.


    devops training in chennai | devops training in chennai with placement | devops training in chennai omr | devops training in velachery | devops training in chennai tambaram | devops institutes in chennai | devops certification in chennai | trending technologies list 2018

    ReplyDelete
  8. In the beginning, I would like to thank you much about this great post. Its very useful and helpful for anyone looking for tips. I like your writing style and I hope you will keep doing this good working.
    Angularjs Institute in Bangalore
    Best Angularjs Training in Bangalore
    Best Institute For ccna Course in Bangalore
    Best ccna Training Institute in Bangalore

    ReplyDelete
  9. Very nice post here thanks for it .I always like and such a super contents of these post.Excellent and very cool idea and great content of different kinds of the valuable information's.
    machine learning course in Chennai
    machine learning training center in Chennai
    machine learning certification in Chennai
    Android training in chennai
    PMP training in chennai

    ReplyDelete
  10. Such an exceptionally valuable article. Extremely intriguing to peruse this article. I might want to thank you for the endeavors you had made for
    composing this amazing article.


    WordPress Bundle,
    WordPress Bundle Pack,
    WordPress Starter Pack,
    WP Starter Pack,
    WP Bundle Pack,
    Giant Brand Solutions,
    Premium WordPress Themes and Plugins,
    WordPress Themes,
    WordPress Plugins,

    ReplyDelete
  11. Hi..
    Nice Blog. You have shared as possible information related to quarries as anyone can share. SQL is trending in all aspects. You have explained very well how we can use quarry language for framework and in our programming.

    ReplyDelete
  12. I am inspired with your post writing style & how continuously you describe this topic. azure course After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic.

    ReplyDelete
  13. I am very happy when read this blog post because blog post written in good manner and write on good topic. Thanks for sharing valuable information.

    Java training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery

    ReplyDelete
  14. Your post is just outstanding! thanks for such a post,its really going great and great work.You have provided great knowledge about thr web design development and search engine optimization
    Java training in Chennai

    Java Online training in Chennai

    Java Course in Chennai

    Best JAVA Training Institutes in Chennai

    Java training in Bangalore

    Java training in Hyderabad

    Java Training in Coimbatore

    Java Training

    Java Online Training

    ReplyDelete
  15. Wonderful blog...! This information is very helpful for enhancing my knowledge and Thank you...! oracle training in chennai

    ReplyDelete

  16. I recently came across your article and have been reading along. I want to express my admiration of your writing skill and ability to make readers read from the beginning to the end. I would like to read newer posts and to share my thoughts with you.Your post is just outstanding! thanks for such a post,its really going great and great work.You have provided great knowledge

    Azure Training in Chennai

    Azure Training in Bangalore

    Azure Training in Hyderabad

    Azure Training in Pune

    Azure Training | microsoft azure certification | Azure Online Training Course

    Azure Online Training

    ReplyDelete
  17. Thanks for giving great kind of information. So useful and practical for me. Thanks for your excellent blog, nice work keep it up thanks for sharing the knowledge.IELTS Coaching in chennai

    German Classes in Chennai

    GRE Coaching Classes in Chennai

    TOEFL Coaching in Chennai

    spoken english classes in chennai | Communication training


    ReplyDelete
  18. This comment has been removed by the author.

    ReplyDelete
  19. Really impressed! Everything is very open and very clear clarification of issues. It contains truly facts. Your website is very valuable. Thanks for sharing.
    data science course in Hyderabad

    ReplyDelete
  20. Best place to design your digital visiting card & Mini website in Rs 100
    Miniwebsite

    ReplyDelete
  21. Your content is nothing short of brilliant in many ways. I think this is engaging and eye-opening material. Thank you so much for caring about your content and your readers. I suggest everyone takes the One Funnel Away Challenge 2021, giant brand solutions, One Funnel Away Challenge, 1 Funnel Away Challenge, https://giantbrandsolutions.com/, resurge reviews, resurge, seo for small business

    ReplyDelete
  22. What’s up to everyone, because I am really keen on reading this web site’s post to be updated on a regular basis. It consists of nice information.
    data scientist training in hyderabad

    ReplyDelete
  23. These are in fact fantastic ideas in about blogging. You have touched some nice things here. Any way keep up writing.
    data scientist training in hyderabad

    ReplyDelete
  24. This is a very nice one and gives in-depth information. I am really happy with the quality and presentation of the article. I’d really like to appreciate the efforts you get with writing this post. Thanks for sharing.
    Artificial intelligence Classes in pune

    ReplyDelete
  25. This is a very nice one and gives in-depth information. I am really happy with the quality and presentation of the article. I’d really like to appreciate the efforts you get with writing this post. Thanks for sharing.
    UiPath course in pune

    ReplyDelete
  26. Just now I read your blog, it is very helpful and looking very nice and useful information.
    Data Science Training in Hyderabad
    Data Science Course in Hyderabad

    ReplyDelete
  27. Infycle Technologies, the No.1 software training institute in Chennai offers the No.1 Big Data course in Chennai for tech professionals and students at the best offers. In addition to the Big Data course, other in-demand courses such as Python, Selenium, Oracle, Java, Python, Power BI, Digital Marketing also will be trained with 100% practical classes. After the completion of training, the trainees will be sent for placement interviews in the top MNC's. Call 7504633633 to get more info and a free demo.No.1 Big Data Course in Chennai | Infycle Technologies

    ReplyDelete
  28. Expected to create you a tiny word to thank you once more in regards to the pleasant ideas you've contributed here…

    Data Science Training in Hyderabad

    ReplyDelete
  29. Nice blog and informative blog. Thanks for sharing this blog with us.
    Python Course in Hyderabad

    ReplyDelete
  30. Thankful for Sharing This Article. It is incredibly such a ton of huge substance. I trust these Commenting records will serve to my site…

    Data Science Training in Hyderabad

    ReplyDelete
  31. wow... what a great blog, this writter who wrote this article is realy a great blogger, this article so good , would help a lot who are in to programming and also students .
    Thank you!

    data science course in tambaram

    ReplyDelete
  32. wow... what a great blog, this writter who wrote this article is realy a great blogger, this article so good , would help a lot who are in to programming and also students .
    Thank you!

    data science training in tambaram

    ReplyDelete
  33. Excellent post on Programming . It is what i was searching for.I would like to suggest you that please keep sharing such type of info.Thanks

    ReplyDelete
  34. I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. Feel free to visit my website; 일본야동
    일본야동
    국산야동
    일본야동
    한국야동


    ReplyDelete
  35. I have read your excellent post. This is a great job. I have enjoyed reading your post first time. I want to say thanks for this post. Thank you… Feel free to visit my website; 일본야동
    일본야동
    국산야동
    일본야동
    한국야동

    ReplyDelete
  36. wow, its a incredible information. thanks for sharing. i think this article would be nice if you put some image to help describing the topic. Feel free to visit my website; 일본야동
    일본야동
    국산야동
    일본야동
    한국야동

    ReplyDelete
  37. Incredible post I should say and a debt of gratitude is in order for the data. Schooling is certainly a tacky subject. Be that as it may, is still among the main subjects within recent memory. I appreciate your post and anticipate more. You have made some valid statements there. I looked on the web to study the issue and discovered a great many people will oblige your perspectives on this site...
    how to make a paper airplane eagle
    science behind paper airplanes | how to make a paper airplane that flies far and straight step by step | classic dart paper airplane

    ReplyDelete
  38. Really an awesome blog and informative content. Keep sharing more blogs with us. If you want to learn a data science course, follow the below link.
    Data Science Course in Hyderabad

    ReplyDelete
  39. Thank you for sharing the information.The article is very useful for us.If you want to know more :

    Azure Training in Chennai

    ReplyDelete
  40. When activated, it will change your current home page, search page, and a new tab without any authorization or understanding. If infected by this malware, you may be confronted with problems such as the slowness and inability to respond to your PC, the appearance of fake notifications and alerts, redirection of web searches, and more. rts dsrlte

    ReplyDelete
  41. Thanks for sharing informative article. This a good and great content.Keep sharing with us.
    website designing course in rishikesh

    ReplyDelete
  42. Thanks for posting such an informative article
    This article is very useful for us
    For more: https://www.cmsforca.in/cma/

    ReplyDelete
  43. Nice Article Thanks for Sharing it was really helpful for me

    B.Com Computers Colleges in Hyderabad

    ReplyDelete
  44. This was a nice blog. I am very impressed with your post because this post is very helpful to me, Thanks for sharing this post.

    CMA Coaching Centres in Hyderabad

    ReplyDelete
  45. Passionate about sharing valuable insights and helpful information. Grateful to connect with you on this digital platform. Feel free to explore and discover a wealth of knowledge that can enhance your life. Let's embark on this journey together!

    Digital Marketing Training in Hyderabad

    ReplyDelete
  46. Thank you for sharing the information. The article is very useful for us .If you want to know more .

    AI Training in Hyderabad

    ReplyDelete
  47. Thank you for this excellent post. I always appreciate such superb content. The ideas are excellent, and the content provides valuable information of various kinds.

    ISO 22301 Lead Auditor Training

    ReplyDelete
  48. Hi, Thanks for sharing wonderful articles...

    For More:

    Retail Counters in Scotland

    ReplyDelete