Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Data Slipping thru Query on SQL?

I do not understand how certain accounts can slip through the query as shown below; Am I doing something wrong? I am trying to make sure only Portfolios 1 – 3’s bonds and swaps feed thru.

SELECT DISTINCT portfolio
FROM holdings_table
WHERE as_of_date = '2022-01-01'
AND asset_class = 'bond' OR asset_class = 'swap'
AND portfolio = 'PORT1' OR portfolio = 'PORT2' OR portfolio = 'PORT3'

portfolio
PORT1
PORT2
PORT3
PORT4
PORT6

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In SQL, AND has precedence over OR. Therefore, what you wrote is interpreted as:

SELECT DISTINCT portfolio
FROM holdings_table
WHERE (as_of_date = '2022-01-01'
AND asset_class = 'bond') OR (asset_class = 'swap'
AND portfolio = 'PORT1' OR portfolio = 'PORT2' OR portfolio = 'PORT3')

What you probably wanted to write (but please double-check) can be achieved using parentheses:

SELECT DISTINCT portfolio
FROM holdings_table
WHERE as_of_date = '2022-01-01'
AND (asset_class = 'bond' OR asset_class = 'swap')
AND (portfolio = 'PORT1' OR portfolio = 'PORT2' OR portfolio = 'PORT3')

Pro tip: you can use asset_class IN ('bond', 'swap)` and similar for portfolio: this simplifies the query and helps you avoid this kind of mistakes.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading