BiscuitCookie BiscuitCookie - 7 months ago 10
SQL Question

SQL- How to compare two numbers in the same row

I am creating a database in Oracle Apex and I basically need to compare two numbers in the same row so that I can find which is the biggest. Example table below;

enter image description here

Using the example above, how would I compare Number 1 and Number 2 on the same row e.g. Compare 6 against 7 for the first row then compare 3 against 1 for the second row.

MT0 MT0
Answer

If there is a minimum value for your numbers (i.e. they are all positive integers) then you can do:

Oracle Setup:

CREATE TABLE table_name ( ID, name, number1, number2, number3 ) AS
SELECT 1, 'Jane', 6, 7, 1 FROM DUAL UNION ALL
SELECT 2, 'John', 3, 1, NULL FROM DUAL UNION ALL
SELECT 3, 'Jake', NULL, NULL, 5 FROM DUAL;

Query:

SELECT ID,
       NAME,
       GREATEST( NVL( NUMBER1, 0 ), NVL( NUMBER2, 0 ), NVL( NUMBER3, 0 ) ) AS biggest
FROM   table_name;

Output:

        ID NAME    BIGGEST
---------- ---- ----------
         1 Jane          7 
         2 John          3 
         3 Jake          5 

If there is no minimum value then you can do:

Query 2:

SELECT ID,
       NAME,
       CASE WHEN NUMBER1 IS NULL AND NUMBER2 IS NULL AND NUMBER3 IS NULL
              THEN NULL
            WHEN NUMBER1 IS NULL AND NUMBER2 IS NULL THEN NUMBER3
            WHEN NUMBER1 IS NULL AND NUMBER3 IS NULL THEN NUMBER2
            WHEN NUMBER2 IS NULL AND NUMBER3 IS NULL THEN NUMBER1
            WHEN NUMBER1 IS NULL THEN GREATEST( NUMBER2, NUMBER3 )
            WHEN NUMBER2 IS NULL THEN GREATEST( NUMBER1, NUMBER3 )
            WHEN NUMBER3 IS NULL THEN GREATEST( NUMBER1, NUMBER2 )
            ELSE GREATEST( NUMBER1, NUMBER2, NUMBER3 )
            END AS biggest
FROM   table_name;
Comments