I have a SQLite table defined this way:
CREATE TABLE Points(value INTEGER, player INTEGER, match INTEGER)
In the execution, I may have several identical columns, and I want a call which only deletes one, not all of them nor keeping just one. Is there any SQL call to do that?
An example to explain myself clearer:
value player match
1 2 3
1 3 3
1 2 3
2 2 3
1 2 3
1 2 3
1 3 3
db.delete("Points", "value = 1, player = 2, match = 3", null); //pseudo-code for the deletion
db.delete("Points", "value = 1, player = 3, match = 3", null);
value player match
1 2 3
2 2 3
1 2 3
1 2 3
1 3 3
I think db.delete("Points", "value = 1, player = 3, match = 3", null); will delete ALL columns which match the where clauses, am I right?
The delete statement you wrote will indeed delete all matching rows.
Try to use the built-in column ROWID, read the first line, save the rowid, and then delete where ROWID= the value you selected.
Try this
String _val=""+1;
String _player=""+3;
String _match=""+3;
db.delete(TABLE_NAME,"value=? AND player=? AND match=?",new String[] {_val,_player,_match});
The usual way to do this is to assign every table a unique identifier for each row. Like this:
CREATE TABLE Points(Id INTEGER PRIMARY KEY, value INTEGER, player INTEGER, match INTEGER);
Then you can use a subquery to find the one row you want to delete:
DELETE FROM Points WHERE Id =(SELECT MIN(Id) FROM Points WHERE value=1 AND player=2 and match=3);
This example deletes the oldest record entered first (the oldest has the lowest unique key Id)
Related
I have an Android Sqlite database and I'm trying to select the top 1000 rows by RANK number, because RANK is always changing I sometimes get duplicate rows with the same RANK number, what I would like to do is only keep the duplicate row containing the newest RANK based on its CREATED_DATE, I will visually display this below:
id rank created_date
1 1 1/1/2014
2 2 1/1/2021
3 3 1/1/2021
4 1 1/1/2021
The output I want is:
id rank created_date
2 2 1/1/2021
3 3 1/1/2021
4 1 1/1/2021
My current code gets close but doesn't remove duplicate RANK based on CREATED_DATE instead it removes them based on ID which I don't want and I haven't been able to find a way to do it by CREATED_DATE
Cursor c = theDatabase.query(DATABASE_TABLE, columns, RANK + " BETWEEN 1 AND 1000", null,
RANK, null, ID + " ASC");
This code above is removing duplicates based on ID which I don't want and gives this output below:
id rank created_date
1 1 1/1/2014
2 2 1/1/2021
3 3 1/1/2021
Any help will go a long way thanks
you can use GROUP BY with max() function.
e.g. select * from table group by rank having max(created_date)
I have a table in my database which has 3 columns: id, name, category_id which has 1 million rows. the user selects a category_id in the app and then the database has to return 12 rows which have the selected category_id. then in the next api call, the database has to return the next 12 rows which have the selected category_id and so on.
My question is how I can return the rows randomly and avoid returning repeated rows in next api calls?
You are looking for a repeatable random sort. For this you can use RAND() with a seed. The idea is that each search should be assigned a constant seed (that you can persist in the user's session, for example).
Assuming that a user has seed 12345, you can fetch its first page like:
select * from mytable where category_id = ? order by rand(12345) limit 12
Then the second page is fetched as follows:
select * from mytable where category_id = ? order by rand(12345) limit 12, 12
Third page:
select * from mytable where category_id = ? order by rand(12345) limit 24, 12
And so on.
Assuming id is a key of the table and has positive values only, you can do:
select id, name, category_id
from my_table
where category_id = ? and id > ?
order by id
limit 12
The first time you call it, you can use:
category_id = 123
id = -1
The second time you get the max id from before (let's say 25) and use that one.
category_id = 123
id = 25
I have table with duplicate id record.I written a query to get all record with same id.Now i want to update record id such as follows
CREATE TABLE Student1
(`id` int,`status` int,`amount` int , `Name` varchar(10), `date` varchar(55))
;
INSERT INTO Student1
(`id`,`status`,`amount`, `Name`, `date`)
VALUES
(1,0,4500, 'ram', '04/02/2012'),
(2,0,2000, 'shyam', '05/09/2013'),
(2,0,6500, 'radhe', '11/11/2014'),
(2,0,8000, 'radheshyam', '15/11/2013'),
(4,0,1500, 'ghanshyam', '08/11/2014')
;
id status amount Name date
1 0 4500 ram 04/02/2012
2 0 2000 shyam 05/09/2013
2 0 6500 radhe 11/11/2014
2 0 8000 radheshyam 15/11/2013
4 0 1500 ghanshyam 08/11/2014
SqlQuery:
SELECT * FROM Student1
where id in (SELECT id FROM Student1 GROUP BY id HAVING count(*)>1)
Expected Result :
id status amount Name date
2 0 2000 shyam 05/09/2013
2 0 6500 radhe 11/11/2014
2 0 8000 radheshyam 15/11/2013
Now i want to update any two records id's to 21,211.So i am trying to get the cursor count which will return 3.After getting count i m moving to position 2 to change its id but how to write query to update current cursor position record.
I din't test it, but this will get you going.
cursor.moveToFirst();
while ( !cursor.isAfterLast()) {
// update whatever you want here
db.getWritableDatabase().update(
//TABLE_NAME,
//values,
//whereclause,
//args
);
cursor.moveToNext()
}
Get the values from the cursor on each position and make the updates. This operation should be done outside the main thread. You could use a asynctask.
But you shouldn't create DB records with ID duplication. Add a AUTOINCREMENT statement at you table creation.
No way to update the records in this way as there is no primary key field to use the where clause on. Always mark the id field as primary key to avoid such situations. The best you can do is find these entries, store the Date or name, which ever is unique, and then use that in the where clause to change the id.
do(cursor.moveToFirst()) {
//store the name or Date and call a method on the database
// to update the entry to set new id where name equals to this name.
} while(cursor.moveToNext());
Avoid such situations by marking the id field as primary key. SQLite auto-increments the primary key field even if it is not explicitly mentioned.
I have the below table in my DB
id name is_current
1 apple 0
2 banana 1
3 mango 0
4 grapes 1
5 pineapple 1
I want to execute an update query which will update the (fruit) table last column (is_current) single value and at the same time the whole column values as well. For example the first row has an apple with id=1 and I want to set this value to 1 and all other fruit values to zero so the table look like,
id name is_current
1 apple 1
2 banana 0
3 mango 0
4 grapes 0
5 pineapple 0
Currently I am using two different queries and to different methods to achieve this
1st: is to set all values of is_current column to 0
String sql = "UPDATE "+TABLE_NAME +" SET " + is_current + " = '"+ Zero +"';
2nd: is to set the apple values to 1 by using id
String sql = "UPDATE "+TABLE_NAME +" SET " + is_current + " = '"+ One +"' WHERE "+ id + " = "+rowId;
So how can I combine these two queries to a single one to achieve this?
If you want to do this stuff for a specific fruit/ID (e.g. every time you update apples) you can set a trigger such that when you update that fruit, then it will automatically set to zero all other rows.
However if you want to do this stuff in a more general way then you need to perform 2 queries (as told by #Der Golem)
how can I combine these two queries to a single one to achieve this?
You can't.
You have to execute at least 2 commands.
A command to update all the is_current values to 0.
And a command to update the specified record to 1.
Hello I have a table with that structure:
ID VALUE
1 3
2 5
3 12
if I query select id,value,value+5 from table. Thats the result
ID VALUE NEW_VALUE
1 3 8
2 5 10
3 12 17
And what I want to make a query indicating the id and the new value that return the whole table but with a 3rd column indicating the new values after inserting. for example for myQuery(id=2,value=8)
ID VALUE NEW_VALUE
1 3 3
2 5 8
3 12 12
Is posible to do that in the same query?
YOu can use the WHERE clause to select only the rows you want ("...if the student has the given id..."):
update T
set col3 = col2 + 5
where id = 2
Of course, col3 would have to exist before you can update it. So you will either have to issue an ALTER-TABLE statement (if your implementation supports it) or recreate the table with the desired columns, import the original data (INSERT INTO YOURNEWTABLE...SELECT ... from YOUROLDTABLE) and then update col3.
If you don't want to "persist" this third column but only need it to be displayed when you query:
select id, col2, col2 + 5 as myComputedValue
from T
where id = 2
Finally, if you want to display all rows but change the addend conditionally (add zero to col2 when the id is not one of the ones you desire but add 5 when it is) then you can use the CASE statement.