Search code examples
mysqlsqlselectquery-optimizationunion

Alternate way to get last and first record from database table


SELECT * FROM
    (SELECT * FROM customer ORDER BY customer_id ASC  LIMIT 1 )DUMMY_ALIAS1
UNION ALL 
SELECT * FROM
    ( SELECT * FROM customer  ORDER BY customer_id DESC LIMIT 1)DUMMY_ALIAS11

what is other alternative way to get the last and first record , i think my query is not optimized


Solution

  • Try this:

    SELECT c.* 
    FROM customer c
    INNER JOIN ( SELECT MIN(customer_id) AS minCustomerId, 
                        MAX(customer_id) AS maxCustomerId 
                 FROM customer
               ) AS b ON c.customer_id IN (minCustomerId, maxCustomerId);