The order of SQL Evaluation

Source: Internet
Author: User
Select prod_name, prod_pricefrom productswhere vend_id = 'l01' or vend_id = 'brs01' and prod_price> = 10;
 
Prod_name prod_price -----------------------------

Fish bean bag toy 3.4900 bird bean bag toy 3.4900 rabbit bean bag toy 3.490018 inch teddy bear 11.9900 Raggedy Ann 4.9900

Look at the results above. Four of the rows returned have prices less than $10-so, obviusly, the rows were not filtered as intended. Why did this happen? The answer is the order of evaluation. SQL (like most versions ages) ProcessesAndOperators beforeOrOperators. When SQL sees the aboveWhereClause, it reads any products costing $10 or more made by vendorBrs01, And any products made by vendorDll01Regardless of price. In other words, becauseAndRanks higher in the order of evaluation, the wrong operators were joined together.

The solution to this problem is to use parentheses to explicitly group related operators. Take a look at the followingSelectStatement and output:

 
 
Select prod_name, prod_pricefrom productswhere (vend_id = 'dl01' or vend_id = 'brs01') and prod_price> = 10;
 
Prod_name prod_price ------------------- ---------- 18 inch teddy bear 11.9900

The only difference between thisSelectStatement and the earlier one is that, in this statement, the first twoWhereClause conditions are enclosed within parentheses. As parentheses have a higher order of evaluation than eitherAndOrOrOperators, the DBMS first filtersOrCondition within those parentheses. The SQL statement then becomes any products made by either vendorDll01Or vendorBrs01Costing $10 or greater, which is exactly what we want.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.