Rank on SQLite SubQuery - sqlite

I have a table Person with ID(Guid), FirstName(string), LastName(string) and 3000 entries. What I desperately need is the rank of a certain entry by ID in a sorted query by FirstName and LastName.
So for example: I search for any entries with FirstName or LastName containing the String 'mil' which returns 62 entries sorted. Since I know the ID of an entry somewhere in this result, I need the row_index of this entry.
I tried this with a Temp Table before, but since I'm working with sqlite-pcl for UWP I can't use 'CREATE TEMP TABLE' statements and so on, thus I need a solution in a single query.
PRAGMA temp_store = MEMORY;
DROP TABLE IF EXISTS TempQuery;
CREATE TEMP TABLE TempQuery AS SELECT ID FROM Person WHERE (Firstname LIKE '%mil%' OR LastName LIKE '%%');
SELECT rowid FROM TempQuery WHERE ID = '48a0231a-af41-450d-a291-5912d39119c9' LIMIT 1;

Related

Result of SELECT MAX(id) is null

On the database open, I inserted 5 records into the Expense table. Then I removed all 5 records one by one.
And before I insert new entry I check max inserted id. For some reason it's null. What's wrong?
var result = await db.rawQuery("SELECT MAX(id) as last_inserted_id FROM Expense");
final maxID = result.first["last_inserted_id"];
print('maxID:$maxID'); //maxID:null
If there are no rows in the table, there is no maximum defined. What you rather should do is look for the ID sequence number of the table to find out what the next ID will be. That information is usually stored in some meta table of the DB.
SELECT seq FROM SQLITE_SEQUENCE WHERE name='Expense';

sqlite shift rowid in multiple records

Hello i have an sqlite db with many records like 10540 record they are ordered by creation time , i want to shift like a record in the middle and like to do it automatically
for example :
select * from table1 where id >= 8521;
UPDATE Table1 SET id = id +1 ;
does not work i get Error: Result: UNIQUE constraint failed:
so i want to shift up all records from 8521 to the last record and get place in the 8520 place for example so i can insert my record in that place of table .
even the
id = select max(id)+1
does not work how can i increment the id from last record to the needed record so i can put a place in the records db
A simple update statement would fail, as it would try to create duplicate values in the primary key.
What you can do is this:
First update the column to the negatives of the values they should have:
update table1
set id = -(id + 1)
where id > 8520;
Now there are no duplicates and you just need to update again to the positive values:
update table1
set id = -id
where id < 0;
This will do the trick, but any kind of updating the primary key is not a recommended practice

Insert/update trigger updating column value of all rows

I am running into a logical problem.My Trigger is:
create trigger Points1
on Posts
after insert, update
As
declare #value int
declare #postedby int
select #value= Count(Message) from Posts
select #postedby = PostedBy from Posts
update AspNetUsers set User_points = #value * 3
where ( AspNetUsers.Id = #postedby)
I dont know whether i am doing it right or not.
Two tables: AspNetUsers table with User_points column and Id Column as primary key
Posts table with PostId as primary key and PostedBy as foreign key referencing the AspNetUsers table.
Now, i want to compare PostedBy with Id column and if they both are same then update the User_Points column with +3 on every single message he posted.
Now, problem is:
1> It is inserting same number of points in every Row.It should check only currently inserted row and the PostedBy column of that row and then compare with Id column of other table and should Update user's Point of only that Id.
But same result nothing happens
Please tell me how to do it.
thanks in advance
change
select #postedby = PostedBy from Posts
to
select #postedby = PostedBy from INSERTED
'INSERTED' is a magic table that keep insert/updated data in this scope.
Same as this 'DELETED' table keep previous data in update a row

SQLITE fill value with unique random table

I want to create a table with a field that is unique and limited to a certain value. Lets say that the limit is 100, the table is full, I remove a random row, and when I create a new row it has the value that was freed before.
It doesn't need to be the fastest thing in the world (the limit is quite small), I just want to implement it in a DB.
Any ideas?
Create one more column in main table, say deleted (integer, 0 or 1). When you need to delete with certain id, do not really delete it, but simply update deleted to 1:
UPDATE mytable SET deleted=1 WHERE id = <id_to_delete>
When you need to insert, find id to be reused:
SELECT id FROM mytable WHERE deleted LIMIT 1
If this query returns empty result, then use INSERT to create new id. Otherwise, simply update your row:
UPDATE mytable SET deleted=0, name='blah', ... WHERE id=<id_to_reuse>
All queries reading from your main table should have WHERE constraint with NOT deleted condition:
SELECT * FROM mytable WHERE NOT deleted
If you add index on deleted, this method should work fast even for large number of rows.
This solution does everything in a trigger, so you can just use a normal INSERT.
For the table itself, we use an autoincrementing ID column:
CREATE TABLE MyTable(ID INTEGER PRIMARY KEY, Name);
We need another table to store an ID temporarily:
CREATE TABLE moriturus(ID INTEGER PRIMARY KEY);
And the trigger:
CREATE TRIGGER MyTable_DeleteAndReorder
AFTER INSERT ON MyTable
FOR EACH ROW
WHEN (SELECT COUNT(*) FROM MyTable) > 100
BEGIN
-- first, select a random record to be deleted, and save its ID
DELETE FROM moriturus;
INSERT INTO moriturus
SELECT ID FROM MyTable
WHERE ID <> NEW.ID
ORDER BY random()
LIMIT 1;
-- then actually delete it
DELETE FROM MyTable
WHERE ID = (SELECT ID
FROM moriturus);
-- then change the just inserted record to have that ID
UPDATE MyTable
SET ID = (SELECT ID
FROM moriturus)
WHERE ID = NEW.ID;
END;

Read last Inserted row in Sql according to its Time stamp

sql has a Table called emp.
emp(emp_id int IDENTITY primary key, EmployeeName varchar(50),.......)
I want to Insert a record to above table. Here is my code in asp.net.
DBconnection dbcon = new DBconnection();
string query = "insert into emp values('" + TextBox_EmpName.Text + "','" + ....);
int no1 = dbcon.insertQuery(query);
I have another table called emp-relation
emp-relation(emp_id int primary key, count int, ....)
-- foreign key (emp_id)references emp(emp_id)
My problem is when I inserting the emp row ,I dont know what is the emp_id since it created by auto. And when I am going to insert to emp-relation , I want to get emp-id since it is the foreign key.
How can I do this? Is there any way to read last Insert row in Sql according to Time stamp or some thing? I believe that records are not sorted according to inserted timestamp in nature. please help me.
There's bascally two ways. The first way is to return the new ID from the first insert query:
insert into emp values(...)
select scope_identity() as NewID
The second way is to lookup the first row when you insert into the relation table:
insert emp-relation
(emp_idm, ...)
select emp_id
, ...
from emp
where emp_name = #EmpName
You have to pass in enough columns to make the reference unique.

Resources