Amir
Amir

Reputation: 1061

Ionic Sqlite SELECT IN statement doesn't return correct results

I have ionic mobile application where I use Sqlite plugin. I try to run following query:

this.db.executeSql('SELECT * FROM foo_table WHERE id IN (?)', [[1, 3]])
    .then(data => {
        console.log(data.rows.item(0));
        console.log(data.rows.item(1));
        // Do something here
    });

I have on purpose left showing the database initialization code because it is unnecessary because it works properly with other methods in the same file. In database I have two entities in table_foo which contain some specific data and each entity have id.

When I run above statement it doesn't return those two entities which ids are 1 and 3. Instead it return undefined. I run exact same statement in sqlite console that is SELECT * FROM table_a WHERE id IN (1,3); and this works. It shows correctly the two entities. My question is why Sqlite SELECT IN query above doesn't work properly and how I should properly add many values in params (where is located array of values 1 and 3)? Am I using it (SELECT IN query) wrong?

When I run above query with params as:

Upvotes: 0

Views: 522

Answers (1)

Amir
Amir

Reputation: 1061

I found two workarounds for this:

  1. Concatenating array values as strings (not good solution):
const ids = [1, 3];
this.db.executeSql('SELECT * FROM foo_table WHERE id IN (' + ids.toString()')', [])
    .then(data => {
        console.log(data.rows.item(0));
        console.log(data.rows.item(1));
        // Do something here
    });
  1. Using sql SELECT in SELECT IN query (good solution if you can fetch those values from database table):
this.db.executeSql('SELECT * FROM foo_table_a WHERE id IN (SELECT id FROM foo_table_b)', [])
    .then(data => {
        console.log(data.rows.item(0));
        console.log(data.rows.item(1));
        // Do something here
    });

Upvotes: 0

Related Questions