John John - 1 month ago 14
SQL Question

combine 2 basic queries to return one result

Using PostgreSQL I have two queries. I want to combine the two queries to return two integer values separated by commas.

SELECT * from newlayerya_1 ORDER BY id DESC LIMIT 1

SELECT * from newlayerya_1 ORDER BY id ASC LIMIT 1


-- should return for example 141,23

Iv tried some examples I found online but having no joy with it.

CREATE FUNCTION test_ret(a integer, b integer) RETURNS RECORD AS $$
DECLARE
ret RECORD;
BEGIN
-- Arbitrary expression to change the first parameter
--IF LENGTH(a) < LENGTH(b) THEN
-- SELECT TRUE, a || b, 'a shorter than b' INTO ret;
SELECT * from newlayerya_1 ORDER BY id DESC LIMIT 1 INTO ret;
-- ELSE
-- SELECT FALSE, b || a INTO ret;
SELECT * from newlayerya_1 ORDER BY id ASC LIMIT 1 INTO ret;
--END IF;
RETURN ret;
END;$$ LANGUAGE plpgsql;

Answer
SELECT
    (SELECT id from newlayerya_1 ORDER BY id DESC LIMIT 1),
    (SELECT id from newlayerya_1 ORDER BY id  ASC LIMIT 1)

Should avoid any anti-patterns, such as casting integers as strings.

Or, even simpler...

SELECT
    MAX(ID), MIN(ID)
FROM
    newlayera_1
Comments