Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql to take maximum number from both the tables?

I need to query the maximum ID from two tables and I need to take the ID of whichever is larger. i am using sqlserver.

Queries:

SELECT MAX(a.ID)
FROM   tableA a

SELECT MAX(b.ID)
FROM   tableB b

If tableA's maximum ID is 20 and tableB's maximum ID is 30 then the UNION of both the tables query should return only 30.

Is it possible to combine both the queries into a single query to return maximum ID?

like image 378
user1016403 Avatar asked Jan 22 '13 15:01

user1016403


People also ask

How do I find the maximum value of two tables in SQL?

select id from T1 where price in( select max(price) from( select max(price) as price from T1 union select max(price) as price from T2 union select max(price) as price from T3 ) temp ) union select id from T2 where price in( select max(price) from( select max(price) as price from T1 union select max(price) as price from ...

Can you do max count together in SQL?

No, we can't use a MAX(COUNT(*) and we can not layer aggregate functions on top of one another in the same SELECT clause.

Can I SELECT from two tables SQL?

In SQL we can retrieve data from multiple tables also by using SELECT with multiple tables which actually results in CROSS JOIN of all the tables. The resulting table occurring from CROSS JOIN of two contains all the row combinations of the 2nd table which is a Cartesian product of tables.

How do I SELECT 3 max values in SQL?

To get the maximum value from three different columns, use the GREATEST() function. Insert some records in the table using insert command. Display all records from the table using select statement.


2 Answers

This is based on what you said, UNION both tables and get the maximum value.

SELECT max(ID)
FROM
(
    select max(ID) ID from tableA
    UNION
    select max(ID) ID from tableB
) s

or

SELECT max(ID)
FROM
(
    select ID from tableA
    UNION
    select ID from tableB
) s
like image 144
John Woo Avatar answered Sep 18 '22 18:09

John Woo


SELECT MAX(id)
FROM (SELECT ID FROM tableA
      UNION
      SELECT ID FROM tableB) AS D
like image 24
Lamak Avatar answered Sep 22 '22 18:09

Lamak