SQLite query doesn't work as expected - android

I have a problem with an SQLite Query and can't figure it out. These are my table:
CREATE TABLE Exercise
(
e_id int auto_increment primary key,
name varchar(20)
);
CREATE TABLE PersonalList
(
p_id int auto_increment primary key,
name varchar(20)
);
CREATE TABLE Exercise_Personal_List
(
e_id_m int auto_increment primary key,
p_id_m int
);
INSERT INTO Exercise
(e_id, name)
VALUES
('1', 'exercise1'),
('2', 'exercise2'),
('3', 'exercise3'),
('4', 'exercise4'),
('5', 'exercise5'),
('6', 'exercise6');
INSERT INTO PersonalList
(p_id, name)
VALUES
('1', 'list1'),
('2', 'list2'),
('3', 'list3');
INSERT INTO Exercise_Personal_List
(e_id_m, p_id_m)
VALUES
('2', '1'),
('4', '1'),
('6', '1'),
('1', '2');
Exercise table: a collection of exercises
PersonalList table: a collection of list
Exercise_Personal_List: a reference to which Exercise is part of which Exercise_Personal_List
I'm trying to get a list of Exercises that are not yet added to a specific list. E.g. the ones that are not added to List 1. My query:
select * from Exercise
where e_id not in (
select e_id from Exercise_Personal_List
where p_id_m like '1'
)
The result is empty. I don't see the error in the query. The correct result should be 1, 3, 5.
Btw, I'm using http://sqlfiddle.com to evaluate this stuff. It's faster for testing :)
Thanks for your help!

I think you mean to be doing the following query where the second instance of e_id has been changed to e_id_m:
select * from Exercise
where e_id not in (
select e_id_m from Exercise_Personal_List
where p_id_m like '1'
)

There is a little mess up in the creation - you shouldn't use auto_increment in the joining table:
CREATE TABLE Exercise_Personal_List
(
e_id_m int,
p_id_m int
);
And the selection should be:
select * from Exercise
where e_id not in (
select e_id_m as e_id from Exercise_Personal_List
where p_id_m like '1'
)

Related

Android - Change a column type in SQLite database dynamically at runtime

I have an application, where I am detecting the type of a particular column at run-time, on page load. Please refer the below code:
public String fncCheckColumnType(String strColumnName){
db = this.getWritableDatabase();
String strColumnType = "";
Cursor typeCursor = db.rawQuery("SELECT typeof (" + strColumnName +") from tblUsers, null);
typeCursor.moveToFirst();
strColumnType = typeCursor.getString(0);
return strColumnType;
}
The above method simply detects the type of column with column Name 'strColumnName'. I am getting the type of column in this case.
Now, I want to change the column type to TEXT if I am receiving INTEGER as the column type. For this, I tried the below code:
public String fncChangeColumnType(String strColumnName){
db = this.getWritableDatabase();
String newType = "";
Cursor changeCursor = db.rawQuery("ALTER TABLE tblUsers MODIFY COLUMN " + strColumnName + " TEXT", null);
if (changeCursor != null && changeCursor.moveToFirst()){
newType = changeCursor.getString(0);
}
return newType;
}
But while executing the 'fncChangeColumnType' method, I am getting this error, android.database.sqlite.SQLiteException: near "MODIFY": syntax error (code 1): , while compiling: ALTER TABLE tblUsers MODIFY COLUMN UserID TEXT
NOTE: I also replaced 'MODIFY' with 'ALTER', but still getting the same error.
Please check if this is the right method to change the type dynamically.
Please respond back if someone has a solution to this.
Thanks in advance.
In brief, the solution could be :-
Do nothing (i.e. take advantage of SQLite's flexibility)
you could utilise CAST e.g. CAST(mycolumn AS TEXT) (as used below)
Create a new table to replace the old table.
Explanations.
With SQLite there are limitations on what can be altered. In short you cannot change a column. Alter only allows you to either rename a table or to add a column. As per :-
SQL As Understood By SQLite - ALTER TABLE
However, with the exception of a column that is an alias of the rowid column
one defined with ?? INTEGER PRIMARY KEY or ?? INTEGER PRIMARY KEY AUTOINCREMENT or ?? INTEGER ... PRIMARY KEY(??) (where ?? represents a valid column name)
you can store any type of value in any type of column. e.g. consider the following (which stores an INTEGER, a REAL, a TEXT, a date that ends up being TEXT and a BLOB) :-
CREATE TABLE IF NOT EXISTS example1_table (col1 BLOB);
INSERT INTO example1_table VALUES (1),(5.678),('fred'),(date('now')),(x'ffeeddccbbaa998877665544332211');
SELECT *, typeof(col1) FROM example1_table;
The result is :-
As such is there a need to change the column type at all?
If the above is insufficient then your only option is to create a new table with the new column definitions, populate it if required from the original table, and to then replace the original table with the new table ( a) drop original and b)rename new or a) rename original, b) rename new and c) drop original)
e.g. :-
DROP TABLE IF EXISTS original;
CREATE TABLE IF NOT EXISTS original (mycolumn INTEGER);
INSERT INTO original VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9),(0);
-- The original table now exists and is populated
CREATE TABLE IF NOT EXISTS newtable (mycolumn TEXT);
INSERT INTO newtable SELECT CAST(mycolumn AS TEXT) FROM original;
ALTER TABLE original RENAME TO old_original;
ALTER TABLE newtable RENAME TO original;
DROP TABLE IF EXISTS old_original;
SELECT *,typeof(mycolumn) FROM original;
The result being :-
i think the sql query statement is wrong ,try
ALTER TABLE tblUsers MODIFY COLUMN id TYPE integer USING (id::integer);
instead of id use column name....
hope this helps....
EDIT:
"ALTER TABLE tblUsers MODIFY COLUMN "+strColumnName+" TYPE integer USING ("+strColumnName+"::integer);"

Android SQLite Performance: Multiple selects in single query Vs single select in multiple queries?

Performance wise, which one is better (for a single table) ?:
Multiple select in single query or
Single select in multiple queries?
Example:
/*table schema*/
create table ACTIVITY_TABLE (
ID integer primary key autoincrement,
INTERVAL_ID integer not null,
ACTIVITY_TYPE text ,
WIFI_LIST text,
COUNT integer not null );
/*Multipe selects in single query*/
select * from
(select sum(COUNT)/60 as Physical from ACTIVITY_TABLE where INTERVAL_ID >=1 and INTERVAL_ID <=3 and (ACTIVITY_TYPE="Still" or ACTIVITY_TYPE = "Walking" or ACTIVITY_TYPE = "Running" ) ),
(select sum(COUNT)/60 as vehicular from ACTIVITY_TABLE where INTERVAL_ID >=1 and INTERVAL_ID <=3 and (ACTIVITY_TYPE="InVehicle" ) );
For your example, you can modify the query in the following way which will be much more efficient, I didn't tested the query.
select
sum(case when activitytype='walking' or activitytype='still' or activitytype='running' then COUNT else 0 end )/60 as physical,
sum(case when activitytype='InVehicle' then COUNT else 0 end)/60 as vehicular
from
activity_table
where interval_id>=1 and interval_id<=3

SQLite on Android: Different result set at Runtime vs. SQLite Administrator

I am building an Android app with an internal SQLite DB.
Here is the schema:
CREATE TABLE IF NOT EXISTS [tblImageVideoLink] (
[LinkID] INTEGER NOT NULL PRIMARY KEY,
[ImageID] INTEGER UNIQUE NOT NULL,
[VideoID] INTEGER NULL
);
CREATE TABLE IF NOT EXISTS [tblImages] (
[ID] INTEGER PRIMARY KEY NOT NULL,
[ImageName] VARCHAR(50) NOT NULL,
[ImageDescription] VARCHAR(100) NULL,
[Page] INTEGER NULL
);
CREATE TABLE IF NOT EXISTS [tblPages] (
[ID] INTEGER NOT NULL PRIMARY KEY,
[PageName] VARCHAR(30) NULL
);
CREATE TABLE IF NOT EXISTS [tblVideos] (
[ID] INTEGER NOT NULL PRIMARY KEY,
[VideoName] VARCHAR(150) NOT NULL,
[VideoDescription] VARCHAR(100) NULL,
[VideoType] VARCHAR(10) NULL
);
CREATE INDEX IF NOT EXISTS [IDX_TBLIMAGEVIDEOLINK_IMAGEID] ON [tblImageVideoLink](
[ImageID] DESC,
[VideoID] DESC
);
CREATE INDEX IF NOT EXISTS [IDX_TBLIMAGES_PAGE] ON [tblImages](
[Page] DESC
);
Here's the relevant data I have in the tables:
INSERT INTO tblImages (ID, ImageName, Page) VALUES (1, 'Beach.jpg', 1);
INSERT INTO tblImages (ID, ImageName, Page) VALUES (2, 'Bowling.jpg', 1);
INSERT INTO tblImages (ID, ImageName, Page) VALUES (3, 'Car.jpg', 1);
INSERT INTO tblVideos (ID, VideoName) VALUES (2, 'Bowling.3gp');
INSERT INTO tblVideos (ID, VideoName) VALUES (3, 'Car.3gp');
INSERT INTO tblImageVideoLink (LinkID, ImageID, VideoID) VALUES (1, 2, 2);
INSERT INTO tblImageVideoLink (LinkID, ImageID, VideoID) VALUES (2, 3, 3);
INSERT INTO tblPages (ID, PageName) VALUES (1, 'Misc');
I am trying to run this query to get all the images with a certain page, and their related videos:
SELECT DISTINCT I.ID AS 'Image ID', I.ImageName, V.ID AS 'Video ID', V.VideoName
FROM tblImages I
LEFT JOIN tblImageVideoLink L ON L.VideoID=V.ID
LEFT JOIN tblVideos V ON L.ImageID=I.ID
WHERE I.Page=1;
When I test it in SQLite Administrator, I am getting the desired result set, which is:
When I test it in the App (or in SQLiteSpy) I am getting a different result set:
I have tried everything I know, including GROUP BY, removing the DISTINCT, different JOIN types, etc.
BTW, SQLiteSpy writes at the bottom: SQLite 3.7.8 while SQLite Administrator writes SQLite 3.5.1. I don't know if it matters.
Please help, and also kindly explain why there's a difference between two SQLite tools...
What you see in SQLLite Admin is (considering your output) same as
SELECT DISTINCT(I.ImageName), V.VideoName
What you actual seeing in app is (considering your output) same as
SELECT DISTINCT(I.ImageName, V.VideoName)
Try brackets
My dear friend and DBA helped me spot my issue. Here's the working query to JOIN the two tables and get the data set I wanted:
SELECT DISTINCT I.ID AS 'Image ID', I.ImageName, V.ID AS 'Video ID', V.VideoName
FROM tblImages I
LEFT JOIN tblImageVideoLink L ON L.ImageID=I.ID
LEFT JOIN tblVideos V ON L.VideoID=V.ID
WHERE I.Page=1;
Thank you all for trying to help.

SQLite and Android Insert/Updates on SQLiteDatabase -CompiledStatements-

Pretend I have a table with 2 columns. _id and name. _id is the primary key and I do not want to set this value manually. I want to perform an insert of name="john," and let the program create my own _id. I am unclear what "index" to use when inserting and how many question marks to use. Does this code do the job? Should the index for john be 1 or 2?
String TABLENAME = "table";
SQLiteStatement statement = db.compileStatement("INSERT INTO "+TABLENAME+" VALUES(?);");
statement.bindString(1,"john");
statement.executeInsert();
Next, say I want to manually set my own _id value. Would I change the code to:
String TABLENAME = "table";
SQLiteStatement statement = db.compileStatement("INSERT INTO "+TABLENAME+" VALUES(?,?);");
statement.bindLong(1,666); //Manual _id.
statement.bindString(2,"john");
statement.executeInsert();
Your first example where you provide only the name will not work:
sqlite> create table test (i integer primary key autoincrement, j text);
sqlite> insert into test values ('asd');
Error: table test has 2 columns but 1 values were supplied
sqlite> insert into test values (null, 'asd');
sqlite> select * from test;
1|asd
sqlite> insert into test (j) values ('asd');
sqlite> select * from test;
1|asd
2|asd
so you need to identify the name column as the destination of the sole value this way, (or as you mentioned in your comment pass null):
SQLiteStatement statement = db.compileStatement("INSERT INTO "+TABLENAME+" (name) VALUES(?);");
Your second example should work fine.
This would apply to some table created this way:
create table SomeTable (_id integer primary key autoincrement, name text)
Then
SQLiteStatement statement = db.compileStatement("INSERT INTO "+TABLENAME+" VALUES(null,?);");
statement.bindString(1,"john");
Should also work.

SQLite script vars

I need to mass populate my SQLite database — ideally using a script rather than code.
I would like to do this (MySQL syntax) but for SQLite but I'm not sure it you can have variables defined in scripts:
INSERT INTO `parent` (id, name) values(NULL, "some name!");
SET #parentId= last_insert_rowid();
INSERT INTO `child` (id, parentId, name, ) values (NULL, #parentId, 'some name!);
SQLite throws errors when I try to declare variables in my SQLite script. Can this be done in SQLite?
You can use the function last_insert_rowid() without a script var for this case:
insert into parent (id, name) values (NULL, 'some name!');
then:
insert into child (id, parentId, name) values (NULL, last_insert_rowid(), 'child name!');
transcript:
SQLite version 3.7.6.3
sqlite> create table parent (id integer primary key, name);
sqlite> create table child (id integer primary key, parentId integer, name);
sqlite> insert into parent (id, name) values (NULL, 'some name!');
sqlite> insert into child (id, parentId, name) values (NULL, last_insert_rowid(), 'child name!');
sqlite> select * from parent;
1|some name!
sqlite> select * from child;
1|1|child name!
sqlite>
If you need to keep the value around for a while (through multiple inserts for example) use a temporary table:
sqlite> create temp table stash (id integer primary key, parentId integer);
sqlite> insert into parent (id, name) values (NULL, 'another name!');
sqlite> replace into stash values (1, last_insert_rowid());
sqlite> insert into child (id, parentId, name) values (NULL, (select parentID from stash where id = 1), 'also a name!');
sqlite> select * from parent;
1|some name!
2|another name!
sqlite> select * from child;
1|1|child name!
2|2|also a name!
sqlite>
Unfortunately you can't declare such variable in SQLite script. Moreover AFAIK all statements will not be executed except the first one. Also look HERE

Categories

Resources