sqlgroup-byunioncoderunner

Cannot correctly get expected Union output for SQL


Troubles:

Did not Order By properly and have not laid out code/or used conventions as expected.

Question:

The Union operator needs to be used here and to that end, find vendor_id's specified in line three of the code used and a quantity of less than what is specified in the final line of code. The code will need to be sorted.

Code used:

SELECT job_id, po_id, 'Vendor ' || vendor_id as 'Reason'
FROM pos
WHERE vendor_id IS 'SOS'
UNION
SELECT job_id, po_id, 'Quantity < ' || quantity as 'Reason'
FROM pos
WHERE quantity < 10;

Meant to get:

job_id      po_id       Reason
----------  ----------  ------------
002         AAA         Quantiy < 10
004         CCC         Quantiy < 10
004         CCC         Vendor SOS
005         EEE         Vendor SOS
006         GGG         Quantiy < 10

Received (from CodeRunner):

Runtime error
Program does not use the expected ORDER BY clause or is badly laid out.

See database schema for more details (Primary Keys are in bold).

Unknown DBMS used. Behaves like PostgreSQL and not mysql.


Solution

  • To sort by job_id follow by po_id, just add ORDER BY clause at the end of query. By default the sort order ASC (ascending), you may add DESC if you want to sort in descending order.

    SELECT
        job_id, 
        po_id, 
        'Vendor ' || vendor_id as 'Reason'
    FROM pos
    WHERE vendor_id = 'SOS'
    
    UNION
    
    SELECT 
        job_id,
        po_id, 
        'Quantity < ' || quantity as 'Reason'
    FROM pos
    WHERE quantity < 10
    
    ORDER BY 
        job_id,
        po_id;