Python Practice › SQLite Programs › Program 17

Top N rows

EasySQLite Programs · 17 of 20

Write a Python program to get the top 3 scores.

Advertisement
Output
[('Gill', 90), ('Virat', 82), ('Rahul', 61)]

Approach

  1. ORDER BY ... DESC LIMIT 3.

Solution

Python
import sqlite3 conn = sqlite3.connect(":memory:")conn.execute("CREATE TABLE scores (player TEXT, runs INTEGER)")conn.executemany("INSERT INTO scores VALUES (?, ?)", [("Virat", 82), ("Rohit", 45), ("Gill", 90), ("Rahul", 61)])print(conn.execute("SELECT player, runs FROM scores ORDER BY runs DESC LIMIT 3").fetchall())
Output
[('Gill', 90), ('Virat', 82), ('Rahul', 61)]

Learn the concept

New to this topic? Read the lesson, then come back.

More sqlite programs

← All 20 SQLite Programs

Leave a Comment