What are the potential pitfalls of using ORDER BY in a MySQL query when trying to display top results for each category?

When using ORDER BY in a MySQL query to display top results for each category, the main pitfall is that it will only return the top overall results, rather than the top results for each category. To solve this issue, you can use a subquery to group the results by category and then order them within each group.

$sql = "SELECT * FROM (
    SELECT *, ROW_NUMBER() OVER(PARTITION BY category ORDER BY score DESC) as rn
    FROM your_table_name
) t
WHERE t.rn = 1";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        // Output the top result for each category
        echo "Category: " . $row['category'] . " - Top Result: " . $row['score'] . "<br>";
    }
} else {
    echo "No results found.";
}