Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select TOP 1 from the result set

Tags:

sql

mysql

I would like to retrieve the top 1 value of result set of query which is connected using Union

SELECT TOP 1 * FROM
(
    SELECT paused_time as end_time
        FROM production_time
        WHERE created_time = curdate()
    UNION 
    SELECT resumed_time as end_time
        FROM pause_timer
        WHERE created_time = curdate()
    UNION
    SELECT end_time as end_time
        FROM timer_idle
        WHERE created_time = curdate()
) as end_time
ORDER BY end_time DESC 

But could not get the expected result.

like image 265
user1894647 Avatar asked Jul 23 '15 09:07

user1894647


People also ask

What does select top 1 do in SQL?

The SQL SELECT TOP Clause The SELECT TOP clause is used to specify the number of records to return. The SELECT TOP clause is useful on large tables with thousands of records. Returning a large number of records can impact performance.

What does select 1 from mean?

The statement 'select 1' from any table name means that it returns only 1. For example, If any table has 4 records then it will return 1 four times.

How do I select the top 1 row in MySQL?

Here's the syntax to select top N rows in MySQL. In the above statement, we list the columns column1, column2, … that you want to select in your query. Also, you need to specify LIMIT n after the table name, where n is the number of rows you want to select. The above query will select top n records in your table.


1 Answers

There is no TOP keyword in MySQL as far as I am aware. What you require is Limit:

SELECT * FROM
(
    SELECT paused_time as end_time FROM production_time WHERE created_time = curdate()
    UNION 
    SELECT resumed_time as end_time FROM  pause_timer WHERE created_time = curdate()
    UNION
    SELECT end_time as end_time FROM  timer_idle WHERE created_time = curdate()
) as end_time
ORDER BY end_time DESC 
LIMIT 1
like image 56
Wibbler Avatar answered Oct 15 '22 23:10

Wibbler