SQLite : ORDER BY a joined column - java

I have this simple request :
SELECT *
FROM categories
LEFT OUTER JOIN items ON categories.id = items.category_id
ORDER BY items.category_id, items.name;
The problem is that the results are ordered following items.id, instead of the two specified columns.
If I replace with :
ORDER BY categories.id, items.name;
It works great, but it doesn't use my index:
CREATE INDEX items_index ON items(category_id, name);
How can I resolve that properly? Thank You.
Edit : Here is how I created the 2 tables :
// Categories
db.execSQL("CREATE TABLE categories (" +
"id INTEGER PRIMARY KEY, " +
"parent_id INTEGER , " +
"resource_name TEXT, " +
"FOREIGN KEY(parent_id) REFERENCES categories(id) ON UPDATE CASCADE ON DELETE CASCADE);");
db.execSQL("CREATE INDEX categories_index ON categories(parent_id);");
// Items
db.execSQL("CREATE TABLE items (" +
"id INTEGER PRIMARY KEY, " +
"category_id INTEGER , " +
"name TEXT, " +
"price REAL, " +
"FOREIGN KEY(category_id) REFERENCES categories(id) ON UPDATE CASCADE ON DELETE CASCADE);");
db.execSQL("CREATE INDEX items_index ON items(category_id, name);");
How I insert the categories :
ContentValues values = new ContentValues();
values.put("id", category.getId());
values.put("parent_id", category.getParentId());
values.put("resource_name", category.getResourceName());
db.insert("categories", null, values);
And the items :
ContentValues values = new ContentValues();
values.put("category_id", item.getCategoryId());
values.put("name", item.getName());
values.put("price", item.getPrice());
long id = db.insert("items", null, values);

Related

SQLite Delete Cascade not working: FOREIGN KEY constraint failed

I have two table:
Child Table
public static final String SQL_CREATE_TAB_COMMENT = "CREATE TABLE " +TABLE_COMMENT+ "( " + KEY_COMMENT + " INTEGER PRIMARY KEY AUTOINCREMENT , " + COLUMN_EMMET + " TEXT NOT NULL , " +COMMENT+ " TEXT , "+IMAGCOM+" TEXT , "+FORMAT+" TEXT NOT NULL , "+DATECMTCREATION+" TEXT , "+TAGSTATUTCMT+" TEXT , "+ COLUMN_COMMENT_KEY_POST +" INT NOT NULL , "+EMETPOST_PHONE+ " TEXT, " +DEST_PHONE+ " TEXT, " + IDCMTEMET + " TEXT,"+VISITEDCMT+" TEXT, "+TAB_IMAGES + " TEXT, "+IS_DOWNLOADED + " TEXT,"+FILEDOC+" TEXT, FOREIGN KEY(" + COLUMN_COMMENT_KEY_POST + ") REFERENCES " + TABLE_POST_NEW + "(_id) ON DELETE CASCADE )";
Parent Table
public static final String SQL_CREATE_TAB_POST_NEW = "CREATE TABLE " +TABLE_POST_NEW+ "( " +KEY_POST+ " INTEGER PRIMARY KEY AUTOINCREMENT ," +EMMET+ " TEXT NOT NULL , " +TEXT+ " TEXT NOT NULL , "+ IMAG +" TEXT ,"+TYPE+ " TEXT ," +DEST+ " TEXT ," +IDPOSTEMET+ " TEXT NOT NULL, " +CMT_NON_LU+ " TEXT, " +DATELASTEVENT+" TEXT, " +DATECREATION+ " TEXT, " +TAGSTATUT+ " TEXT,"+COUNTER_DEST+" TEXT,"+VISITED+" TEXT,"+ NAME_GROUP+ " TEXT,"+ IDGROUP + " TEXT, "+TAB_IMAGES + " TEXT, "+IS_DOWNLOADED +" TEXT, "+COLUMN_POST_KEY_CONTACT+ " INT NOT NULL DEFAULT 0, "+LABEL_IMAGES+" TEXT,"+TAB_FILE+" TEXT)";
Now If I am deleting parent row I have this error:
FOREIGN KEY constraint failed Error Code : 787 (SQLITE_CONSTRAINT_FOEIGNKEY)
Caused By : Abort due to constraint violatio
public PosteManager openForWrite(){
db = dbHelper.getWritableDatabase();
//db.execSQL("PRAGMA foreign_keys=ON");
db.setForeignKeyConstraintsEnabled(true);
return this;
}
public int deletePoste(int posteId){
openForWrite();
int delete = db.delete(DbHelper.TABLE_POST_NEW, DbHelper.KEY_POST + "=" + posteId, null);
close();
return delete;
}
KEY_POST = _id; and I test COLUMN_COMMENT_KEY_POST = _id and COLUMN_COMMENT_KEY_POST = post_id
I have the same error
I test your code and I have this in Log.d("TABLESQL","The creation SQL for table " :
D/TABLESQL: The creation SQL for table comment_tbl_new is
CREATE TABLE comment_tbl_new( _commentid INTEGER PRIMARY KEY AUTOINCREMENT , Emetteur TEXT NOT NULL , comment TEXT , imageCom TEXT , format TEXT NOT NULL , Datecmtcreation TEXT , Tagstatutcmt TEXT , post_id INT NOT NULL , emetPost_phone TEXT, Dest_phone TEXT, idcmtemet TEXT,visited TEXT, tab_image TEXT, idownloaded TEXT,filedoc TEXT, FOREIGN KEY(post_id) REFERENCES post_tbl_new(_id) )
06-14 00:11:06.845 18468-18468/com. D/TABLESQL: The creation SQL for table comment_tbl is
CREATE TABLE comment_tbl( _commentid INTEGER PRIMARY KEY AUTOINCREMENT , Emetteur TEXT NOT NULL , comment TEXT , imageCom TEXT , format TEXT NOT NULL , Datecmtcreation TEXT , Tagstatutcmt TEXT , _id INT NOT NULL , emetPost_phone TEXT, Dest_phone TEXT, idcmtemet TEXT,visited TEXT, tab_image TEXT, idownloaded TEXT,filedoc TEXT, FOREIGN KEY(_id) REFERENCES post_tbl_new(_id) ON DELETE CASCADE )
From API 16+, you should enable foreign key constraint like this in SQLITEOpenHelper class:
#Override
public void onConfigure(SQLiteDatabase db){
db.setForeignKeyConstraintsEnabled(true);
}
As the foreign key constraint is enabled, You can check if another table is not referring child table and it's foreign key is not cascade. Also ") REFERENCES " + TABLE_POST_NEW + "(_id) have you defined _id column in your TABLE_POST_NEW ?

Android : Calculate sum and group by month (SQLite)

Is there are any option to select amount, group them by month and calculate sum. I tried to get total sum of each month and pass it to ArrayList.
Example of data:
Amount Date
230 04/03/19
500 05/03/19
400 04/04/19
600 06/04/19
100 04/03/19
... ...
My code structure
private String CREATE_BILLS_TABLE = "CREATE TABLE " + TABLE_BILLS + "("
+ COLUMN_BILL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_BILL_USER_ID + " INTEGER,"
+ COLUMN_DESCRIPTION + " TEXT,"
+ COLUMN_AMOUNT + " INTEGER,"
+ COLUMN_DATE_STRING + " TEXT,"
+ COLUMN_COMPANY_NAME + " TEXT,"
+ COLUMN_CATEGORY + " TEXT,"
+ " FOREIGN KEY ("+COLUMN_BILL_USER_ID+") REFERENCES "+TABLE_USER+"("+COLUMN_USER_ID+"));";
public ArrayList<Bills> getDateByUserID(int userID){
SQLiteDatabase db = this.getReadableDatabase();
// sorting orders
ArrayList<Bills> listBillsDates = new ArrayList<Bills>();
Cursor cursor = db.query(TABLE_BILLS, new String[] { COLUMN_BILL_ID,
COLUMN_BILL_USER_ID, COLUMN_DESCRIPTION, COLUMN_AMOUNT, COLUMN_DATE_STRING, COLUMN_COMPANY_NAME, COLUMN_CATEGORY}, COLUMN_BILL_USER_ID + "=?",
new String[] { String.valueOf(userID) }, COLUMN_DATE_STRING, null, null, null);
if (cursor.moveToFirst()) {
do {
Bills bills = new Bills();
bills.setAmount(cursor.getInt(cursor.getColumnIndex(COLUMN_AMOUNT)));
bills.setDateString(cursor.getString(cursor.getColumnIndex(COLUMN_DATE_STRING)));
// Adding record to list
listBillsDates.add(bills);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
// return category list
return listBillsDates;
}
I believe that a query based upon :-
SELECT sum(COLUMN_AMOUNT) AS Monthly_Total,substr(COLUMN_DATE_STRING,4) AS Month_and_Year
FROM TABLE_BILLS
WHERE COLUMN_BILL_USER_ID = 1
GROUP BY substr(COLUMN_DATE_STRING,4)
ORDER BY substr(COLUMN_DATE_STRING,7,2)||substr(COLUMN_DATE_STRING,4,2)
;
Note that other columns values would be arbritary results and as such cannot really be relied upon (fine if the data is always the same). Hence they have not been included.
Will produce the results that you want :-
e.g.
Using the following, to test the SQL :-
DROP TABLE IF EXISTS TABLE_BILLS;
CREATE TABLE IF NOT EXISTS TABLE_BILLS (
COLUMN_BILL_ID INTEGER PRIMARY KEY AUTOINCREMENT,
COLUMN_BILL_USER_ID INTEGER,
COLUMN_DESCRIPTION TEXT,
COLUMN_AMOUNT INTEGER,
COLUMN_DATE_STRING TEXT,
COLUMN_COMPANY_NAME TEXT,
COLUMN_CATEGORY TEXT)
;
-- Add the Testing data
INSERT INTO TABLE_BILLS (
COLUMN_BILL_USER_ID, COLUMN_DESCRIPTION, COLUMN_AMOUNT, COLUMN_DATE_STRING, COLUMN_COMPANY_NAME,COLUMN_CATEGORY)
VALUES
(1,'blah',230,'04/03/19','cmpny','category')
,(1,'blah',500,'05/03/19','cmpny','category')
,(1,'blah',400,'04/04/19','cmpny','category')
,(1,'blah',600,'06/04/19','cmpny','category')
,(1,'blah',100,'04/03/19','cmpny','category')
-- Extra data for another id to check exclusion
,(2,'blah',230,'04/03/19','cmpny','category')
,(2,'blah',500,'05/03/19','cmpny','category')
,(2,'blah',400,'04/04/19','cmpny','category')
,(2,'blah',600,'06/04/19','cmpny','category')
,(2,'blah',100,'04/03/19','cmpny','category')
;
SELECT sum(COLUMN_AMOUNT) AS Monthly_Total,substr(COLUMN_DATE_STRING,4) AS Month_and_Year
FROM TABLE_BILLS
WHERE COLUMN_BILL_USER_ID = 1
GROUP BY substr(COLUMN_DATE_STRING,4)
ORDER BY substr(COLUMN_DATE_STRING,7,2)||substr(COLUMN_DATE_STRING,4,2)
;
Results id :-
The above can then be converted for use by the SQLiteDatabase query method. So your method could be something like :-
public ArrayList<Bills> getDateByUserID(int userID) {
SQLiteDatabase db = this.getReadableDatabase();
String tmpcol_monthly_total = "Monthly_Total";
String tmpcol_month_year = "Month_and_Year";
String[] columns = new String[]{
"sum(" + COLUMN_AMOUNT + ") AS " + tmpcol_monthly_total,
"substr(" + COLUMN_DATE_STRING + ",4) AS " + tmpcol_month_year
};
String whereclause = COLUMN_BILL_USER_ID + "=?";
String[] whereargs = new String[]{String.valueOf(userID)};
String groupbyclause = "substr(" + COLUMN_DATE_STRING + ",4)";
String orderbyclause = "substr(" + COLUMN_DATE_STRING + ",7,2)||substr(" + COLUMN_DATE_STRING + ",4,2)";
ArrayList<Bills> listBillsDates = new ArrayList<Bills>();
Cursor cursor = db.query(TABLE_BILLS, columns, whereclause,
whereargs, groupbyclause, null, orderbyclause, null);
if (cursor.moveToFirst()) {
do {
Bills bills = new Bills();
bills.setAmount(cursor.getInt(cursor.getColumnIndex(tmpcol_monthly_total)));
bills.setDateString(cursor.getString(cursor.getColumnIndex(tmpcol_month_year))); //<<<<<<<<<< NOTE data is MM/YY (otherwise which date to use? considering result will be arbrirtaryy)
// Adding record to list
listBillsDates.add(bills);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
// return category list
return listBillsDates;
}
The above has been tested and run and using the following code :-
ArrayList<Bills> myMonthlyTotals = mDBHelper.getDateByUserID(1);
Log.d("BILLSCOUNT","The number of bills extracted was " + String.valueOf(myMonthlyTotals.size()));
for (Bills b: myMonthlyTotals) {
Log.d("MONTHYLTOTAL","Monthly total for " + b.getDateString() + " was " + String.valueOf(b.getAmount()));
}
In an activity, resulted in the following in the log
:-
04-14 11:58:25.876 16653-16653/? D/BILLSCOUNT: The number of bills extracted was 2
04-14 11:58:25.877 16653-16653/? D/MONTHYLTOTAL: Monthly total for 03/19 was 830
04-14 11:58:25.877 16653-16653/? D/MONTHYLTOTAL: Monthly total for 04/19 was 1000
Please consider the comments in regard to values from non-aggreagted columns be arbitrary values. As per :-
Each non-aggregate expression in the result-set is evaluated once for an arbitrarily selected row of the dataset. The same arbitrarily selected row is used for each non-aggregate expression. Or, if the dataset contains zero rows, then each non-aggregate expression is evaluated against a row consisting entirely of NULL values. SELECT - 3. Generation of the set of result rows.
As per the comments, using recognised date formats can make the underlying SQL simpler and likely more efficient.

SQLite Delete Query Error: no such column: ID (code 1)

I'm trying to delete a row in my SQLite db in my app. It keeps on crashing with
no such column: ID (code 1)
I've tried
db.delete(TABLE_NAME, "ID=?", new String[]{Integer.toString(numID)});
but I still end up with the same
DB Structure:
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME +
" (ITEM_ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
"NAME TEXT, " +
"PRICE INTEGER, " +
"DATE TEXT);");
}
Deletion query:
SQLiteDatabase db = this.getWritableDatabase();
String query = "DELETE FROM " + TABLE_NAME + " WHERE " + ITEM_ID + " = '" + Integer.toString(numID ) + "'";
db.execSQL(query);
My other select queries work perfectly fine so any help would be appreciated
You are trying to delete by ID, but your table uses ITEM_ID
change
db.delete(TABLE_NAME, "ID=?", new String[]{Integer.toString(numID)});
to
db.delete(TABLE_NAME, "ITEM_ID=?", new String[]{Integer.toString(numID)});
Wouldn't ITEM_ID need to be within the "", rather than a variable??
String query = "DELETE FROM " + TABLE_NAME + " WHERE ITEM_ID='" + Integer.toString(numID) + "'";

Android SQLITE DB update table not working

contactid = 123;
SYNC_SUCCESS = 1;
db.updateSyncStatus(contactid, SYNC_SUCCESS);
I have tried the 3 possible ways to update the table in SQLite DB. But its not working. INSERT and DELETE process are working good. Only I am facing problem in the UPDATE. Did I missed anything?
public void updateSyncStatus(String contactid, int syncSuccess) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues CV = new ContentValues();
CV.put(CONTACTS_SYNC_STATUS, syncSuccess);
try {
// db.update(TABLE_CONTACTS, CV, CONTACTS_CONTACTID + "='" + contactid + "'", null); // Tried, Not working
// db.update(TABLE_CONTACTS, CV, CONTACTS_CONTACTID +" = ?", new String[] {contactid}); // Tried, Not Working
db.update(TABLE_CONTACTS, CV, CONTACTS_CONTACTID + " = ?", new String[]{contactid});
}
catch (Exception e){
String error = e.getMessage().toString();
Log.e(TAG, "UpdateError: " + error);
}
db.close();
}
Table Structure:
String CREATE_CONTACTS_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_CONTACTS + "("
+ CONTACTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
+ CONTACTS_NUMBER + " VARCHAR,"
+ CONTACTS_CONTACTID + " VARCHAR,"
+ CONTACTS_SYNC_STATUS + " TINYINT DEFAULT 0" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
Actually the problem is not with the update query. The problem is , before executing the updateSyncStatus method, next statement ran and I am getting the output before updating the rows. So I have used the Handler to wait for 10 seconds before showing the output.

Why is sqlite auto_increment not incrementing?

I've got a database set up to store notes. I want to auto increment the first column. I've tried this, but when I read from the database every result in that column is 'null'.This is the code for creating the DB.
private static final String NOTES_TABLE_CREATE =
"CREATE TABLE " + NOTES_TABLE_NAME + " (" +
COLUMN_NAMES[0] + " INTEGER AUTO_INCREMENT, " +
COLUMN_NAMES[1] + " TEXT, " +
COLUMN_NAMES[2] + " TEXT, " +
COLUMN_NAMES[3] + " TEXT, " +
COLUMN_NAMES[4] + " TEXT, " +
COLUMN_NAMES[5] + " TEXT, " +
COLUMN_NAMES[6] + " TEXT);";
This is the code for getting the DB result.
SQLiteDatabase db = this.getReadableDatabase();
Cursor result = db.query(NOTES_TABLE_NAME, COLUMN_NAMES, null, null, null, null, null, null);
result.moveToFirst();
result.moveToNext();
System.out.println(result.getInt(0));
System.out.println(result.getString(1));
This is the output from logcat
04-09 17:56:17.981 22147-22147/com.example.a8460p.locationotes I/System.out: 0
04-09 17:56:17.981 22147-22147/com.example.a8460p.locationotes I/System.out: notetitle1234567890
AUTO_INCREMENT (as opposed to INTEGER PRIMARY KEY AUTOINCREMENT) is not supported in sqlite.
This is a little non-obvious, because sqlite silently ignores column constraints it does not recognize:
sqlite> CREATE TABLE test (
a INTEGER FABBELBABBEL NOT NULL
);
sqlite> .schema test
CREATE TABLE test (a INTEGER FABBELBABBEL NOT NULL);
sqlite> INSERT INTO test (a) VALUES (1);
sqlite> INSERT INTO test (a) VALUES (NULL);
Error: NOT NULL constraint failed: test.a
AUTOINCREMENT on the other hand, is supported for integer primary keys and only there, so the obvious workaround attempt is not supported, either:
sqlite> CREATE TABLE test (a INTEGER AUTOINCREMENT NOT NULL, b INTEGER);
Error: near "AUTOINCREMENT": syntax error
In short: Auto increment is only available for integer primary keys.

Categories