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

How to identify a number is available in a range of numbers in 2 columns in SQL

I have a table with 2 columns a and b. I want to write a query to search a number is available in the column or the number falls between those 2 columns. I tried using >=,<= also with between but it is not returning any result.

Could someone help me with the query?

  • If the input parameter is 1, it should return true.
  • If the input parameter is 3, it should return true.
  • If the input parameter is 7, it should return true.
  • If the input parameter is 15, it should return false.

Thanks

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

Table with values and expected output:

Table with values and expected output

>Solution :

Say you have a couple of tables like the following:

CREATE TABLE number_ranges (
    A INT,
    B INT
);

INSERT INTO number_ranges (A, B) VALUES (1, 1), (2, 2), (3, 3), (5, 10), (20, 100);

CREATE TABLE search_inputs (
    `Search(Input)` INT
);

INSERT INTO search_inputs (`Search(Input)`) VALUES (1), (3), (7), (15);

You can use BETWEEN, CASE, and EXISTS to achieve your desired output:

SELECT 
    si.`Search(Input)`,
    CASE 
        WHEN EXISTS (
                 SELECT 1 
                 FROM number_ranges nr 
                 WHERE si.`Search(Input)` BETWEEN nr.A AND nr.B
             )
        THEN 'TRUE'
        ELSE 'FALSE'
    END AS Output
FROM search_inputs si;

Output:

Search(Input) Output
1 TRUE
3 TRUE
7 TRUE
15 FALSE
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