Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vectors/Lists in SQLite

Tags:

sql

sqlite

I am new to SQL, are there list or vector variable types? Can I have a column whose type is a list of strings?

Maybe something like:

CREATE TABLE myTbl(domain varchar PRIMARY KEY, linkList list<varchar>);

Can I append a string like so(by using the '+=' operator):

UPDATE myTbl SET linkList += "www.test.com," WHERE domain="blah";
// Table is like so
CREATE TABLE myTbl(domain varchar PRIMARY KEY, linkList varchar);
// Column linkList is a string of links separated by comma's
like image 804
sazr Avatar asked Mar 18 '12 03:03

sazr


People also ask

Can you store lists in SQLite?

You can do this by just storing them in some format that you transform to/from the list of strings on reading from the table. Eg. a common method would be the JSON representation of your list.

What are the 4 main data types in SQLite3?

SQLite only has four primitive data types: INTEGER, REAL, TEXT, and BLOB.

Can you store arrays in SQLite?

SQLite3 does not support arrays directly. See here the type it supports. Basically, it only does Ints, Floats and Text. To accomplish what you need, you have to use a custom encoding, or use an FK, i.e. create another table, where each item in the array is stored as a row.

Can you declare variables in SQLite?

SQLite doesn't support native variable syntax, but you can achieve virtually the same using an in-memory temp table.


1 Answers

You can store lists in a SQLite field with the json1 extension: https://www.sqlite.org/json1.html

So your schema would look like:

CREATE TABLE myTbl(
    domain varchar PRIMARY KEY,
    linkList JSON DEFAULT('[]'));

and to append an item:

UPDATE myTbl
SET linkList = json_insert(linkList, '$[#]', "www.test.com")
WHERE domain="blah";

The SQLite JSON support is quite flexible, particularly with newer versions of SQLite. You can set up indices on JSON expressions for fast matching depending on the contents of your JSON. You can use it with generated columns for dynamic data extraction. You can SELECT from a JSON list with the json_each() table valued function.

Try copy-pasting this into on the sqlite3 command line or in https://sqliteonline.com/ :

CREATE TABLE myTbl(
    domain varchar PRIMARY KEY,
    linkList JSON DEFAULT('[]'));
INSERT INTO myTbl(domain) VALUES ("blah");

UPDATE myTbl
SET linkList = json_insert(linkList, '$[#]', "www.test.com")
WHERE domain="blah";

UPDATE myTbl
SET linkList = json_insert(linkList, '$[#]', "www.example.com")
WHERE domain="blah";

SELECT * FROM myTbl;

Note: This example requires SQLite 3.31 for the $[#] notation.

like image 121
Will Manley Avatar answered Sep 28 '22 04:09

Will Manley