24

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
  • 306
  • 4
  • 11
TheBounder
  • 397
  • 2
  • 3
  • 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

51
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;
Tim Cooper
  • 151,519
  • 37
  • 317
  • 271
SubniC
  • 8,987
  • 2
  • 25
  • 32
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,642
  • 13
  • 60
  • 96
1

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
  • 451,927
  • 24
  • 239
  • 318
0

It worked for me:

    select * from customer where id in ((select min(id) from customer),(select max(id) 
from customer));
Shiwangini
  • 840
  • 14
  • 25
-4

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