Unexpected behaviour with sqlite - sqlite

I have 2 tables, 1 is {number,letter} the other {number,number}
I want to select {number,letter} where number is mentioned anywhere in {number,number}
It looks like your post is mostly code; please add some more details. So I'll waffle on for a little while after having gone to some trouble to make the issue extremely easy reproduce via the code below.
/*
Unexpected behaviour with sqlite.
Save this as problem.sql and do sqlite3 < problem.sql
to demonstrate the effect.
I have 2 tables, 1 is {number,letter} the other {number,number}
I want to select {number,letter} where number is mentioned
anywhere in {number,number}
So my query is
SELECT ALL num,letter
FROM numberLetter
WHERE num IN (
(
SELECT n1 FROM pairs
UNION
SELECT n2 FROM pairs;
)
);
I've actually wrapped this up with some views in the sql below,
results are the same whatever way you do it.
I think I'm making a stupid mistake or have a conceptual problem?
results:
$ sqlite3 < problem.sql
this is pairList
n1
2
3
4
5
7
8
this is selectedNumberLetter which I expect to have 6 rows...
num|letter
2|b
*/
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE pairs(
"n1" TEXT,
"n2" TEXT
);
INSERT INTO pairs VALUES('2','3');
INSERT INTO pairs VALUES('5','4');
INSERT INTO pairs VALUES('8','7');
CREATE TABLE numberLetter(
"num" TEXT,
"letter" TEXT
);
INSERT INTO numberLetter VALUES('1','a');
INSERT INTO numberLetter VALUES('2','b');
INSERT INTO numberLetter VALUES('3','c');
INSERT INTO numberLetter VALUES('4','d');
INSERT INTO numberLetter VALUES('5','e');
INSERT INTO numberLetter VALUES('6','f');
INSERT INTO numberLetter VALUES('7','g');
INSERT INTO numberLetter VALUES('8','h');
INSERT INTO numberLetter VALUES('9','i');
INSERT INTO numberLetter VALUES('10','j');
CREATE VIEW pairList AS
SELECT n1 FROM pairs
UNION
SELECT n2 FROM pairs;
CREATE VIEW selectedNumberLetter AS
SELECT ALL num,letter
FROM numberLetter
WHERE num IN (
(
SELECT n1 FROM pairList
)
);
COMMIT;
SELECT 'this is pairList';
.header on
SELECT * FROM pairList;
.header off
SELECT '
this is selectedNumberLetter which I expect to have 6 rows...';
.header on
SELECT * FROM selectedNumberLetter;

The problem is here:
WHERE num IN ((SELECT n1 FROM pairList));
You must not enclose the SELECT statement in another set of parentheses, because if you do then SQLite will finally return only 1 row from pairList instead of all the rows.
Change to:
CREATE VIEW selectedNumberLetter AS
SELECT num,letter
FROM numberLetter
WHERE num IN (SELECT n1 FROM pairList);
But it is easier to solve this requirement with EXISTS:
select n.*
from numberLetter n
where exists (select 1 from pairs p where n.num in (p.n1, p.n2));
See the demo.

Related

SQLite3 run a trigger insert multiple times besed on inserted vlaue

Want to run an insert n-times, the n is defined by inserted value on another table.
table 1:
create table Table1
(
id INTEGER default 1 not null
primary key
unique,
name TEXT not null
unique,
keys_number INTEGER default 1 not null
);
table 2:
create table table_2
(
id INTEGER default 1 not null
primary key
unique,
table_1_id INTEGER not null
references table_1,
);
Now when i insert into table_1 like:
INSERT INT table_1 (name, keys_number) VALUES ('dummy_name', 5)
want to run a trigger
CREATE TRIGGER insert_keys_after_insert_table_1
AFTER INSERT ON table_1
WHEN (SELECT COUNT(*) FROM table_2 WHERE table_1_id=new.id) < new.keys_number
BEGIN
INSERT INTO keys (table_1_id) VALUES (new.id);
END;
But this runs only once.
Finally, I want to have on table_2 values after the trigger
INSERT INT table_1 (name, keys_number) VALUES ('dummy_name_1', 5)
make the result like:
id;name;keys_number
1;dummy_name_1;5
and the result on table_2 after the trigger, should be
id;table_1_id
1;1
2;1
3;1
4;1
5;1
or if I insert another one on table_1
INSERT INT table_1 (name, keys_number) VALUES ('dummy_name_2', 2)
will make the result on table_1 like:
id;name;keys_number
1;dummy_name_1;5
2;dummy_name_2;2
and the trigger will give the result on table_2:
id;table_1_id
1;1
2;1
3;1
4;1
5;1
6;2
7;2
For this requirement you need a loop, which in SQL is implemented via a recursive CTE.
Unfortunately SQLite does not allow CTEs inside a trigger.
A workaround is to create a new table with only 1 column which will store the numbers 1 to the max expected value of keys_number in table_1:
CREATE TABLE table_numbers AS
WITH cte(keys_number) AS (
SELECT 1
UNION ALL
SELECT keys_number + 1 FROM cte WHERE keys_number < 100 -- change 100 to the max keys_number you expect
)
SELECT keys_number FROM cte
Now you can create your trigger:
CREATE TRIGGER insert_keys_after_insert_table_1 AFTER INSERT ON table_1
BEGIN
INSERT INTO table_2(table_1_id)
SELECT NEW.id
FROM table_numbers
WHERE keys_number <= NEW.keys_number - (SELECT COUNT(*) FROM table_2 WHERE table_1_id = NEW.id);
END;
See the demo.

I'd like to have Characters only (no signs, numbers and spaces at all)

It should be done with SQLite
just like this;
yes, I know, it is quite easy task, If I use UDF(User Define Function).
but, I have severe difficulty with it.
so, looking for another way (no UDF way) to achieve my goal.
Thanks
for your reference,
I leave a link that I have failed to make UDF (using AutoHotkey)
SQLite/AutoHotkey, I have problem with Encoding of sqlite3_result_text return function
I believe that you could base the resolution on :-
WITH RECURSIVE eachchar(counter,rowid,c,rest) AS (
SELECT 1,rowid,'',mycolumn AS rest FROM mytable
UNION ALL
SELECT counter+1,rowid,substr(rest,1,1),substr(rest,2) FROM eachchar WHERE length(rest) > 0 LIMIT 100
)
SELECT group_concat(c,'') AS mycolumn, myothercolumn, mycolumn AS original
FROM eachchar JOIN mytable ON eachchar.rowid = mytable.rowid
WHERE length(c) > 0
AND (
unicode(c) BETWEEN unicode('a') AND unicode('z')
OR unicode(c) BETWEEN unicode('A') AND unicode('Z')
)
GROUP BY rowid;
Demo :-
Perhaps consider the following :-
/* Create the Test Environment */
DROP TABLE IF EXISTS mytable;
CREATE TABLE IF NOT EXISTS mytable (mycolumn TEXT, myothercolumn);
/* Add the Testing data */
INSERT INTO mytable VALUES
('123-abc_"D E F()[]{}~`!##$%^&*-+=|\?><<:;''','A')
,('123-xyz_"X Y Z()[]{}~`!##$%^&*-+=|\?><<:;''','B')
,('123-abc_"A B C()[]{}~`!##$%^&*-+=|\?><<:;''','C')
;
/* split each character thenconcatenat only the required characters*/
WITH RECURSIVE eachchar(counter,rowid,c,rest) AS (
SELECT 1,rowid,'',mycolumn AS rest FROM mytable
UNION ALL
SELECT counter+1,rowid,substr(rest,1,1),substr(rest,2) FROM eachchar WHERE length(rest) > 0 LIMIT 100
)
SELECT group_concat(c,'') AS mycolumn, myothercolumn, mycolumn AS original
FROM eachchar JOIN mytable ON eachchar.rowid = mytable.rowid
WHERE length(c) > 0
AND (
unicode(c) BETWEEN unicode('a') AND unicode('z')
OR unicode(c) BETWEEN unicode('A') AND unicode('Z')
)
GROUP BY rowid;
/* Cleanup Test Environment */
DROP TABLE IF EXISTS mytable;
This results in :-

how to select the same content of the field and to delete it in sqlite?

C:\Users\pengsir>sqlite3 e:\\test.db
sqlite> create table test (f1 TEXT,f2 TEXT, f3 TEXT);
sqlite> insert into test values("x1","y1","w1");
sqlite> insert into test values("x1","y1","w2");
sqlite> insert into test values("x1","y3","w2");
sqlite> insert into test values("x2","y3","w2");
sqlite> insert into test values("x3","y4","w4");
sqlite> insert into test values("x2","y3","w4");
sqlite> insert into test values("x1","y3","w2");
sqlite>
1.select the record rows which contain the same f1 and f2 ,and the rowid .
sqlite> select rowid,f1,f2 from test group by f1,f2 having(count(f2)>1 and count(f2)>1);
2|x1|y1
7|x1|y3
6|x2|y3
I want the result to be :
1|x1|y1
2|x1|y1
3|x1|y3
4|x2|y3
6|x2|y3
7|x1|y3
2.select the record rows which contain the same f1 f2 and f3,and the rowid .
sqlite> select rowid,f1,f2,f3 from test group by f1,f2,f3 having(count(f2)>1 and count(f3)>1);
7|x1|y3|w2
I want the result to be
3|x1|y3|w2
7|x1|y3|w2
let us discuss this problem further , i want to delete one |x1|y3|w2 and keep one |x1|y3|w2 in the table?here is my method.
DELETE FROM test
WHERE rowid in(
SELECT rowid FROM test
WHERE (SELECT count(*)
FROM test AS t2
WHERE t2.f1 = test.f1
AND t2.f2 = test.f2
AND t2.f3 = test.f3
) >= 2 limit 1);
Is there more simple and smart way to do that? (the method is wrong)
I find the proper way to do .
delete from test
where rowid not in
(
select max(rowid)
from test
group by
f1,f2,f3
);
and the method to more than one duplicate for a f1/f2 combination is :
delete from test
where rowid not in
(select rowid from test group by f1,f2);
It will be executed only one time.
You want records that have duplicates (in those fields), i.e., where the number of records with the same values in those fields is at least two:
SELECT rowid, f1, f2
FROM test
WHERE (SELECT count(*)
FROM test AS t2
WHERE t2.f1 = test.f1
AND t2.f2 = test.f2
) >= 2
This requires executing the subquery for each record.
Alternatively, compute the records with duplicates in a subquery once; this might be more efficient:
SELECT test.rowid, test.f1, test.f2
FROM test
JOIN (SELECT f1, f2
FROM test
GROUP BY f1, f2
HAVING count(*) >= 2
) USING (f1, f2)
If you want to remove one of the duplicates, this is easier to do because GROUP BY already returns exactly one output row for each group:
DELETE FROM test
WHERE rowid IN (SELECT max(rowid)
FROM test
GROUP BY f1, f2
HAVING COUNT(*) >= 2)
(If there is more than one duplicate for a f1/f2 combination, you have to execute this multiple times.)
Try using SELECT ALL instead of SELECT but according to the linked docs SELECT should behave like SELECT ALL by default and not like SELECT DISTINCT so I don't know where the problem may be.

SQLite : Select from the end of tree to the top

from this awesome answer, now i can implement recursive query properly ,
and here i have another question,
first:
i create a table :
CREATE TABLE tree(
id_tree integer PRIMARY KEY AUTOINCREMENT,
id_boss TEXT,
id_child TEXT,
answ TEXT);
insert some value :
INSERT INTO tree(id_boss,id_child,answ) VALUES('1','2','T');
INSERT INTO tree(id_boss,id_child,answ) VALUES('1','3','F');
INSERT INTO tree(id_boss,id_child,answ) VALUES('2','P1','T');
INSERT INTO tree(id_boss,id_child,answ) VALUES('2','4','F');
INSERT INTO tree(id_boss,id_child,answ) VALUES('3','P2','T');
INSERT INTO tree(id_boss,id_child,answ) VALUES('3','8','F');
and then i running a recursive query from this awesome answer :
WITH RECURSIVE
under_alice(name,level,order_nr) AS (
VALUES('1','0',0)
UNION ALL
SELECT tree.id_child, under_alice.level+1, tree.id_tree
FROM tree, under_alice
WHERE tree.id_boss=under_alice.name
ORDER BY 2 DESC, 3
)
SELECT substr('..........',1,level*3) || name FROM under_alice;
the result will be like this :
1
...2
......P1
......4
...3
......P2
......8
"Edited" ------>
and my question is, is this posible to reverse it,
for example i choose id_child = 'P2', result will be :
P2
3
1
and if i choose id_child = 'P1' :
P1
2
1
The recursive query starts at P1:
VALUES('P1')
In the recursion step, we go from some record (ancestor) to its parent by looking up the id_boss value of that entry:
SELECT tree.id_boss
FROM tree JOIN ancestor ON tree.id_child = ancestor.id
Everything together:
WITH RECURSIVE
ancestor(id) AS (
VALUES('P1')
UNION ALL
SELECT tree.id_boss
FROM tree JOIN ancestor ON tree.id_child = ancestor.id
)
SELECT id FROM ancestor;

SQLITE equivalent for Oracle's ROWNUM?

I'm adding an 'index' column to a table in SQLite3 to allow the users to easily reorder the data, by renaming the old database and creating a new one in its place with the extra columns.
The problem I have is that I need to give each row a unique number in the 'index' column when I INSERT...SELECT the old values.
A search I did turned up a useful term in Oracle called ROWNUM, but SQLite3 doesn't have that. Is there something equivalent in SQLite?
You can use one of the special row names ROWID, OID or _ROWID_ to get the rowid of a column. See http://www.sqlite.org/lang_createtable.html#rowid for further details (and that the rows can be hidden by normal columns called ROWID and so on).
Many people here seems to mix up ROWNUM with ROWID. They are not the same concept and Oracle has both.
ROWID is a unique ID of a database ROW. It's almost invariant (changed during import/export but it is the same across different SQL queries).
ROWNUM is a calculated field corresponding to the row number in the query result. It's always 1 for the first row, 2 for the second, and so on. It is absolutely not linked to any table row and the same table row could have very different rownums depending of how it is queried.
Sqlite has a ROWID but no ROWNUM. The only equivalent I found is ROW_NUMBER() function (see http://www.sqlitetutorial.net/sqlite-window-functions/sqlite-row_number/).
You can achieve what you want with a query like this:
insert into new
select *, row_number() over ()
from old;
No SQLite doesn't have a direct equivalent to Oracle's ROWNUM.
If I understand your requirement correctly, you should be able to add a numbered column based on ordering of the old table this way:
create table old (col1, col2);
insert into old values
('d', 3),
('s', 3),
('d', 1),
('w', 45),
('b', 5465),
('w', 3),
('b', 23);
create table new (colPK INTEGER PRIMARY KEY AUTOINCREMENT, col1, col2);
insert into new select NULL, col1, col2 from old order by col1, col2;
The new table contains:
.headers on
.mode column
select * from new;
colPK col1 col2
---------- ---------- ----------
1 b 23
2 b 5465
3 d 1
4 d 3
5 s 3
6 w 3
7 w 45
The AUTOINCREMENT does what its name suggests: each additional row has the previous' value incremented by 1.
I believe you want to use the constrain LIMIT in SQLite.
SELECT * FROM TABLE can return thousands of records.
However, you can constrain this by adding the LIMIT keyword.
SELECT * FROM TABLE LIMIT 5;
Will return the first 5 records from the table returned in you query - if available
use this code For create Row_num 0....count_row
SELECT (SELECT COUNT(*)
FROM main AS t2
WHERE t2.col1 < t1.col1) + (SELECT COUNT(*)
FROM main AS t3
WHERE t3.col1 = t1.col1 AND t3.col1 < t1.col1) AS rowNum, * FROM Table_name t1 WHERE rowNum=0 ORDER BY t1.col1 ASC

Resources