25

I need to be able to select two records from a table based on ID.

I need the first one, and the last one (so min, and max)

Example:

Customer
        ID   NAME
        1     Bob
        50    Bob

Any ideas? Thanks.

Natasha Kurian
  • 407
  • 5
  • 11
TheBounder
  • 407
  • 2
  • 5
  • 9
  • 3
    The art of looking at manuals is lost: http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_max –  Apr 01 '16 at 21:27

5 Answers5

53
SELECT MIN(id), MAX(id) FROM tabla

EDIT: If you need to retrive the values of the row you can do this:

SELECT *
FROM   TABLA AS a, (SELECT MIN(id) AS mini,
                            MAX(id) AS maxi
                     FROM   TABLA) AS m
WHERE  m.maxi = a.id
       OR m.mini = a.id;
SubniC
  • 9,807
  • 4
  • 26
  • 33
3

Is this what you are looking for?

select id, name from customers where id = ( select max(id) from customers )
union all
select id, name from customers where id = ( select min(id) from customers )

Now I have tested this type of query on a MySQL database I have access, and it works. My query:

SELECT nome, livello
FROM personaggi
WHERE livello = (
SELECT max( livello )
FROM personaggi ) 
Albireo
  • 10,977
  • 13
  • 62
  • 96
2

If ties for first and/or last place are not a concern, then consider the following query:

(SELECT id, name FROM customers ORDER BY id DESC LIMIT 1)
UNION ALL
(SELECT id, name FROM customers ORDER BY id LIMIT 1);
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

It worked for me:

    select * from customer where id in ((select min(id) from customer),(select max(id) 
from customer));
Channa
  • 742
  • 17
  • 28
-4

SELECT MIN(value), MAX(value) FROM table