Using the LIMIT statement in a SQLite query

AndroidSqlite

Android Problem Overview


I have a query that selects rows in a ListView without having a limit. But now that I have implemented a SharedPreferences that the user can select how much rows will be displayed in the ListView, my SQLite query doesn't work. I'm passing the argument this way:

return wDb.query(TABELANOME, new String[] {IDTIT, TAREFATIT, SUMARIOTIT}, CONCLUIDOTIT + "=1", null, null, null, null, "LIMIT='" + limite + "'");

Android Solutions


Solution 1 - Android

The equals (=) operator is not used with the LIMIT clause. Remove it.

Here's an example LIMIT query:

SELECT column FROM table ORDER BY somethingelse LIMIT 5, 10

Or:

SELECT column FROM table ORDER BY somethingelse LIMIT 10

In your case, the correct statement would be:

return wDb.query(TABELANOME, new String[] {IDTIT, TAREFATIT, SUMARIOTIT}, CONCLUIDOTIT + "=1", null, null, null, null, String.valueOf(limite));

Take a look here at the SQLite select syntax: http://www.sqlite.org/syntaxdiagrams.html#select-stmt">http://www.sqlite.org/syntaxdiagrams.html#select-stmt</A>

This image is rather useful: http://www.sqlite.org/images/syntax/select-stmt.gif">http://www.sqlite.org/images/syntax/select-stmt.gif</a>

Solution 2 - Android

For anyone stumbling across this answer looking for a way to use a LIMIT clause with an OFFSET, I found out from this bug that Android uses the following regex to parse the limit clause of a query:

From <framework/base/core/java/android/database/sqlite/SQLiteQueryBuilder.java>

> LIMIT clause is checked with following sLimitPattern.

private static final Pattern sLimitPattern = Pattern.compile("\\s*\\d+\\s*(,\\s*\\d+\\s*)?");

Note that the regex does accept the format offsetNumber,limitNumber even though it doesn't accept the OFFSET statement directly.

Solution 3 - Android

Due to this bug which also doesn't allow for negative limits

> 8,-1

I had to use this workaround

SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
builder.setTables(table);
String query = builder.buildQuery(projection, selection, null, null, null, sortOrder, null);
query+=" LIMIT 8,-1";

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2443607View Question on Stackoverflow
Solution 1 - AndroidMike CialowiczView Answer on Stackoverflow
Solution 2 - AndroidJon OView Answer on Stackoverflow
Solution 3 - AndroidPepijnView Answer on Stackoverflow