Search code examples
sqlmariadbmax

How to get the biggest id of database in SQL?


How can I get the greatest id between all my database tables?

Intuitively something like this, but doesn't work:

SELECT 
    MAX(n.id_order, s.id_order, pr.id_order, pu.id_order) 
FROM 
    neworders AS n, salesorders AS s, proposalspurchase AS pr, purchaseorders AS pu

I need help with this id_order, is possible get each id easily and compare them to get the max. But is possible do it with just one query?


Solution

  • I need help with this id_order, is possible get each id easily and compare them to get the max. But is possible do it with just one query

    Yes, We can get all ids and compare them to get the max using union or union all.

    select MAX(id_order) as greatest_id
    from (
        select MAX(id_order) as id_order from neworders
        union all
        select MAX(id_order) as id_order from salesorders
        union all
        select MAX(id_order) as id_order from proposalspurchase
        union all
        select MAX(id_order) as id_order from purchaseorders
    ) as orders;