sqlsql-serverrdbms

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?

Thanks

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