And or priority in SQL

Source: Internet
Author: User

The SQL statement is as follows:

Select * from LOAN_BACK_LIBRARY where LIBRARY_ID = 1 or LIB_ID = 1 and STATUS = 3

The conditions for my desired results are:1. LIBRARY_ID = 1 or LIB_ID = 1

2. STATUS = 3

But this is not the case. STATUS is displayed! But it matches LIBRARY_ID = 1 or LIB_ID = 1.

Why?

The original execution of this SQL statement is as follows:

Select * from LOAN_BACK_LIBRARY whereLIBRARY_ID = 1OrLIB_ID = 1 and STATUS = 3

To:

Select * from LOAN_BACK_LIBRARY whereSTATUS = 3 and LIBRARY_ID = 1OrLIB_ID = 1 Still incorrect

Haha, I found the problem:

If the where clause has the and or clause, the or clause automatically separates the Left and Right query conditions, that is, the and clause is executed first, and then the or clause is executed. The reason is: and has the highest execution priority!

Relational operators with a high priority: not and or

The solution is:

Use () to change the execution sequence !!!!

The preceding SQL statement is as follows:

Select * from LOAN_BACK_LIBRARY whereSTATUS = 3 and (LIBRARY_ID = 1OrLIB_ID = 1)

This is the perfect answer !!!!

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.