Explain Codes LogoExplain Codes Logo

Sqlite - SELECT TOP syntax error

sql
limit-clause
database-pagination
sql-queries
Anton ShumikhinbyAnton Shumikhin·Sep 26, 2024
TLDR

In SQLite, the query syntax does not include SELECT TOP. Instead, the correct syntax leverages the LIMIT clause. To fetch the first 10 rows from a table, use the following:

SELECT * FROM table_name LIMIT 10;

This command is SQLite's equivalent to SQL Server's SELECT TOP 10.

Employing the LIMIT clause

SQLite's LIMIT clause shines when used in various scenarios that require fetching a specific set of data.

Retrieving a solitary entry

To fetch a single entry, you'd employ LIMIT 1. Here's how:

SELECT * FROM employees WHERE retired = 0 ORDER BY hire_date LIMIT 1;

This fetches the longest-serving current employee. Quite the workhorse, aren't they? 🐎

Implementing pagination

It's easy peasy to execute database pagination with LIMIT and OFFSET:

SELECT * FROM posts LIMIT 10 OFFSET 20;

This skips the first 20 posts and returns the next 10. Voila, third page of your blog is served! 🎉

Dynamically setting the LIMIT

For a dynamic LIMIT, set it with a subquery:

SELECT * FROM sales LIMIT (SELECT COUNT(*) FROM promotions WHERE active = 1);

Here, we match the number of sales returned to the number of active promotions. Everyone loves sales, right?

Advanced usage of the LIMIT clause

Broadening your understanding of SQLite's LIMIT clause and its flexible deployment is key to becoming a proficient SQLite user.

The Importance of Order

When you combine LIMIT and ORDER BY, remember to place ORDER BY before LIMIT to ensure your data selection makes sense:

-- Fetch the newest recruit SELECT * FROM employees ORDER BY hire_date DESC LIMIT 1;

Who's the new kid on the block, ey?

How to tackle ties when ordering results? Here's the trick:

-- Fetch top scorer(s), **tie inclusive** SELECT * FROM players WHERE score = (SELECT MAX(score) FROM players);

No one likes a tie, but oh well 🤷‍♀️

Using LIMIT with Joins

You can extract precisely the data you need from multiple tables by combining LIMIT with JOIN:

SELECT employees.name, departments.name FROM employees JOIN departments ON employees.dept_id = departments.id LIMIT 5;

This returns just five rows for a snappier query result - the fewer dishes to wash, the better, right?