Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sqlite Query for multiple values in one column

Tags:

android

sqlite

I wanted to do query in table for field id with some vales like 1,5,4,11 which will come from previous screen according to selection.

cursor = database.query(tablename,
                    new String[] { "TopName" }, "id =?", new String[]{"2,3"}, null, null, null);

When I do like this, I am getting cursor count 0, with new String[]{"2"} I am getting value I want for all ids with values in string array like OR which have value in that column.

like image 629
ud_an Avatar asked Dec 01 '11 15:12

ud_an


People also ask

How can I get multiple values from a single column in SQL?

Using an OR condition enables you to specify several alternative values to search for in a column. This option expands the scope of the search and can return more rows than searching for a single value. You can often use the IN operator instead to search for multiple values in the same data column.

How do I select multiple values in a selected query?

To select multiple values, you can use where clause with OR and IN operator.

How does group by work in SQLite?

SQLite GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into groups. GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the ORDER BY clause.

How do I merge two columns in SQLite?

SQLite uses double-pipes ( || ) - more formally known as the concatenation operator - to combine strings. You can combine both literal strings (in quotation marks) and column values using this operator.


2 Answers

You can use the IN operator like this,

cursor = database.query(tablename, new String[] {"TopName"}, "id IN(?,?)", 
                                        new String[]{"2","3"}, null, null, null);
like image 112
Lalit Poptani Avatar answered Oct 01 '22 05:10

Lalit Poptani


The correct syntax for using the IN operator in Android's ContentProvider is as follows:

cursor = database.query(contentUri, projection, "columname IN(?,?)", new String[]{"value1" , "value2"}, sortOrder);

Alternatively, we can also use,

cursor = database.query(contentUri, projection, "columnName IN(?)", new String[] {" 'value1' , 'value2' "}, sortOrder);

Note that we need single quotes around each comma-separated value in the arguments for second case, otherwise the whole string will be treated as one value for the column. The SQL will treat it as

SELECT * FROM table WHERE columnName IN ('value1,value2')

instead of the correct syntax

SELECT * FROM table WHERE columnName IN ('value1' , 'value2')

like image 35
ps2010 Avatar answered Oct 01 '22 05:10

ps2010