⊗pyPmDBQL 113 of 128 menu

Limiting the Number of Records in SQL in Python

To limit the number of lines output, use the LIMIT command.

Example

Let's select the first two users:

query = "SELECT * FROM users LIMIT 2"

Example

Let's select all users with a salary of 500, and then use LIMIT to take only the first two of those selected:

query = "SELECT * FROM users WHERE salary=500 LIMIT 2"

The result of the executed code:

{'id': 1, 'name': 'user1', 'age': 23, 'salary': 400} {'id': 2, 'name': 'user2', 'age': 25, 'salary': 500}

Example

With LIMIT you can select multiple rows from the middle of the result. In the example below, we will select from the second row (row numbering starts from zero), 4 pieces:

query = "SELECT * FROM users LIMIT 1,4"

The result of the executed code:

{'id': 2, 'name': 'user2', 'age': 25, 'salary': 500} {'id': 3, 'name': 'user3', 'age': 23, 'salary': 500} {'id': 4, 'name': 'user4', 'age': 30, 'salary': 900} {'id': 5, 'name': 'user5', 'age': 27, 'salary': 500}

Practical tasks

Get the first 4 users.

Get users from the second, 3 pieces.

enru