ChatGPT解决这个技术问题 Extra ChatGPT

How to get the top 10 values in postgresql?

I have simple question:

I have a postgresql table: Scores(score integer).

How would I get the highest 10 scores the fastest?

UPDATE:

I will be doing this query multiple times and am aiming for the fastest solution.

-1: what have you done so far? Why is that not good enough? What's the Postgres version? Where is explain analyze?

O
Olaf Dietsche

For this you can use limit

select *
from scores
order by score desc
limit 10

If performance is important (when is it not ;-) look for an index on score.

Starting with version 8.4, you can also use the standard (SQL:2008) fetch first

select *
from scores
order by score desc
fetch first 10 rows only

As @Raphvanns pointed out, this will give you the first 10 rows literally. To remove duplicate values, you have to select distinct rows, e.g.

select distinct *
from scores
order by score desc
fetch first 10 rows only

SQL Fiddle


fetch first X rows only is the answer I was looking for -- thank you from the far future!
G
Grzegorz Gierlik

Seems you are looking for ORDER BY in DESCending order with LIMIT clause:

SELECT
 *
FROM
  scores
ORDER BY score DESC
LIMIT 10

Of course SELECT * could seriously affect performance, so use it with caution.


R
Raphvanns

Note that if there are ties in top 10 values, you will only get the top 10 rows, not the top 10 values with the answers provided. Ex: if the top 5 values are 10, 11, 12, 13, 14, 15 but your data contains 10, 10, 11, 12, 13, 14, 15 you will only get 10, 10, 11, 12, 13, 14 as your top 5 with a LIMIT

Here is a solution which will return more than 10 rows if there are ties but you will get all the rows where some_value_column is technically in the top 10.

select
  *
from
  (select
     *,
     rank() over (order by some_value_column desc) as my_rank
  from mytable) subquery
where my_rank <= 10

From his question there is only one column in the table. So why not "select distinct score from Scores order by score desc limit 10"?
@Derek, good point. Though that would probably not be the case in a real world app where we are usually looking to identify the top N of "somethings".
True. Just focusing on his exact question. Also, I've had good luck using limit in a subquery like yours, e.g. "select * from table where value in (select distinct value from table order by value desc limit 10)" I think that's equivalent to yours. I'm not sure which of our queries would perform better, it would probably depend on the table structure and indexing.
There is a missing keyword OVER after rank()
S
Syed Kashif
(SELECT <some columns>
FROM mytable
<maybe some joins here>
WHERE <various conditions>
ORDER BY date DESC
LIMIT 10)

UNION ALL

(SELECT <some columns>
FROM mytable
<maybe some joins here>
WHERE <various conditions>
ORDER BY date ASC    
LIMIT 10)