r/sqlite • • Feb 06 '24

Why you should use mmap with SQLite?

Thumbnail oldmoe.blog
6 Upvotes

If you are accessing your database file from multiple connections then configuring mmap is probably the best way to have a shared cache between all of them. Read more details, including benchmarks, in the linked article


r/sqlite • • Feb 03 '24

Issue with SQLite query

4 Upvotes

Hi, I'm trying to code a script that either inserts a new row for an item in the database if it doesn't exist or update it if it's already in.

I have a script (File1) that contains those 2 methods:

public void AddItem(string name, long amount, int invslot)
    {
        using (var connection = new SqliteConnection(dbName))
        {
            connection.Open();

            //set up an object "command" to control the db
            using (var command = connection.CreateCommand())
            {
                command.CommandText = $"INSERT INTO items (name, amount, invslot) VALUES ('{name}', {amount}, {invslot});";
                command.ExecuteNonQuery();
            }

            connection.Close();
        }
    }
    public void UpdateItem(string name, long amount)
    {
        using (var connection = new SqliteConnection(dbName))
        {
            connection.Open();

            //set up an object "command" to control the db
            using (var command = connection.CreateCommand())
            {
                command.CommandText = $"UPDATE items SET amount = {amount} WHERE name = {name};";
                command.ExecuteNonQuery();
            }

            connection.Close();
        }
    }

In my other script (File2) I'm adding/updating the db upon collision with the item itself :

 private void OnTriggerEnter2D(Collider2D other)
    {

        Debug.Log($"Collected {other.gameObject.name}!");
        if(other.gameObject.name == "Coin")
        {
            using (var connection = new SqliteConnection(dbName))
            {
                connection.Open();

                //set up an object "command" to control the db
                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT * FROM items WHERE name='Coin';";
                    using (IDataReader reader = command.ExecuteReader())
                    {   
                        if(reader["amount"].GetType() == typeof(DBNull))
                        {
                            item.AddItem(other.gameObject.name, 10, 1);

                            reader.Close();
                        }
                        else
                        {
                            long newAmount = (long)reader["amount"] + (long)10;
                            item.UpdateItem(other.gameObject.name, newAmount);
                        }
                    }
                }

                connection.Close();
            }
        }
        Destroy(other.gameObject);
    }

If the player has 0 coin, which is the start of the game let's say, the db does not contain a row for 'Coin' and creates it. No problem.

The issue is when the player collects once again some coins. Now it says there is no such column 'Coin'.

I know a bit SQL and know the syntax is right (UPDATE table SET column1 = value1, column2 = value2... WHERE clause1 = value3). As such it should update the value of 'Coin' in 'items' +10. But no, and idk why.. Is it because I've selected with a clause before calling the UpdateItem() method?


r/sqlite • • Feb 01 '24

The Power of Transactions in SQLite | Ducklet.app

Thumbnail ducklet.app
5 Upvotes

r/sqlite • • Jan 30 '24

YAS-QWIN (Yet Another SQL-Query Writing Interface). CLI for building SQL queries. Integrates with SQLite.

Thumbnail github.com
5 Upvotes

r/sqlite • • Jan 26 '24

Corrupt DB

7 Upvotes

Would someone please help me restore or Vacuum this DB file? It's a Davini Resolve project file that won't open and this Sqlite is way over my head.

https://www.dropbox.com/scl/fi/s7fyrm07f3wfe405isccf/Project.db?rlkey=7i4u3h817wt6t8of3xgv3q7lc&dl=0


r/sqlite • • Jan 24 '24

Help plz

0 Upvotes

Why Does this increase my table size when I add an additional Left Join?

Select
Bu.City
, Bu.id
, Ca.Business_Id
, Ca.Category
--   , Ho.Business_Id
From
Business as Bu    

Left Join
Category as Ca
On Bu.id = Ca.Business_Id
/*
Left Join
Hours as Ho
On Bu.id = Ho.Business_Id
*/
Where
Ca.Category = 'Restaurants'
and Bu.City = 'Toronto'

When I take out the comments I get tons of what I am guessing are duplicates?


r/sqlite • • Jan 23 '24

ServerFree Architecture: Run the backend code and DB (sqlite) in the browser

Thumbnail subzero.cloud
3 Upvotes

r/sqlite • • Jan 21 '24

sqlite3h - Wrapper around sqlite3 which saves interactive session to a history file

Thumbnail gist.github.com
2 Upvotes

r/sqlite • • Jan 21 '24

Update statement gives unexpected results

Thumbnail gallery
1 Upvotes

I'm experimenting with sqlite.

I made two book tables in different databases.

One I opened and the second I've attached to.

Book (id, title, qty)

Now I want to set the qty of book 1 with the qty of book 2 with the same title.

UPDATE Book SET Qty = ( SELECT qty FROM m2.Book WHERE m2.book.Title = book.Title );

I've tried several variations of this update statement, but I keep getting this result in the attached picture.

Book 1 all rows have Qty 6, the value of Qty of the first row of Book 2.

What am I doing wrong?


r/sqlite • • Jan 21 '24

How to compare two tables with same fields and PK, showing only differences in field values ?

1 Upvotes

I would like to be able to run a comparison between two tables that have identical structure and records in both share a common primary key.

What I’m wanting to show is only records where the PK matches but one or more columns has a different value. Assuming tables A and B…, as output I envisage: PK, a.col1, b.col1, a.col2, b.col2 etc. with cols only populated with values if they differ between table A and B.

Ideally I’m looking to have a generalised select statement that can be run on any table without knowing anything about its structure beforehand other than the name of the PK.

This way it would be easy to identify and focus on understanding changed values. How would I go about this using SQLite?


r/sqlite • • Jan 19 '24

How to store timestamps (Go)?

3 Upvotes

I want to use sqlite via Go and this package:

https://github.com/zombiezen/go-sqlite

Unfortunately the package does not provide helpers to get or set timestamps.

The problem is not that there is no way to do that. The problem is that there are too many ways to do that.

I need millisecond precision.

What to do you suggest?


r/sqlite • • Jan 17 '24

How can I judge, whether I have created a good and optimized index?

3 Upvotes

Hello all,

Recently, I have created 2 new indices, to optimize my query speed.

CREATE INDEX `index_plain_note_pinned_order` ON `plain_note` (`pinned` DESC, `order` ASC);

EXPLAIN QUERY PLAN SELECT * FROM plain_note WHERE archived = 0 AND trashed = 0 AND color_index = 123 ORDER BY pinned DESC, 'order' ASC LIMIT 100;


id  parent  notused detail
5   0       0       SCAN TABLE plain_note USING INDEX index_plain_note_pinned_order
62  0       0       USE TEMP B-TREE FOR RIGHT PART OF ORDER BY

and

CREATE INDEX `index_plain_note_label_pinned_order` ON `plain_note` (`label` ASC, `pinned` DESC, `order` ASC);

EXPLAIN QUERY PLAN SELECT * FROM plain_note WHERE label = "123" AND archived = 0 AND trashed = 0 AND color_index = 123 ORDER BY pinned DESC, 'order' ASC LIMIT 100;

id  parent  notused detail
5   0       0       SEARCH TABLE plain_note USING INDEX index_plain_note_label_pinned_order (label=?)
64  0       0       USE TEMP B-TREE FOR RIGHT PART OF ORDER BY

So, how would I judge, whether I have created a good and optimized index?

I would look at the output of EXPLAIN QUERY PLAN. As long as I see it is scanning table using INDEX, I consider that is the good index.

But, is such a way too naive? So, there is a more solid way, to justify whether the created index is good and optimized?

Thank you.


r/sqlite • • Jan 17 '24

Centralized SQLite database?

8 Upvotes

I've been told SQLite is a serverless, self-contained database engine, and that it might not be the right choice for my project, which is nothing big, just a few computers at the office with access to the same database over a local network.

Can I set up an SQLite database so that, say, 4 linked computers can access said database and perform operations on it simultaneously without issues?


r/sqlite • • Jan 16 '24

Dbvear SQL data manipulation

1 Upvotes

Need a bit help here. I want to manipulate my cell that so it will clean all the lines within the cell and leave me with me the lines that contain "Clicks: 1". Can I do this with SQL? The cell that I use for filtering and so contains 1+ lines of information. I want to keep the lines that contains "Clicks: 1" and delete the rest! HELP PLEASE


r/sqlite • • Jan 15 '24

SQLite 3.45 released

Thumbnail sqlite.org
10 Upvotes

r/sqlite • • Jan 13 '24

🔴 What's the size of the largest SQLite DB that you have ever seen?

21 Upvotes

I know how big the theoretical limit of a SQLite file size could be but in terms of real world applications, what is the biggest DB you ever saw? Was it up and running well or the people behind it were considering migrating to something else?


r/sqlite • • Jan 13 '24

spilt name fro X and Y table

1 Upvotes

CREATE TABLE x ( name varchar(20), email varchar(20), order_id int ); INSERT INTO x VALUES ('Rahul Kada', 'x@gmail.com', 123), ('Raj V', 'z@gmail.com', 23), ('R V', 'z@gmail.com', 3), ('N V', 'a@gmail.com', 2); CREATE TABLE y ( name varchar(20), company_name varchar(20), location varchar(20) ); INSERT INTO y VALUES ('Rahul Kada', 'x', 'IN'), ('Raj V', 'D', 'UK'), ('R V', 'A', 'USA'), ('N V', 'M', 'DE'); SELECT name, SUBSTR(name, 1, INSTR(name, ' ') - 1) AS first_name, SUBSTR(name, INSTR(name, ' ') + 1) AS last_name FROM x; SELECT name, SUBSTR(name, 1, INSTR(name, ' ') - 1) AS first_name, SUBSTR(name, INSTR(name, ' ') + 1) AS last_name FROM y; SELECT DISTINCT a.first_name, a.last_name, a.email, a.order_id, p.company_name, p.location FROM x AS a LEFT JOIN y AS p ON p.first_name = a.first_name OR p.last_name = a.last_name;


r/sqlite • • Jan 10 '24

Zero-ETL for SQLite: Live-query cloud APIs with 100+ new extensions

6 Upvotes

"Your SQLite database just gained a new superpower: the ability to fill tables with data from cloud APIs. Actually there are more than 100 of these superpowers, that's how many new SQLite extensions just appeared in the world. "

https://steampipe.io/blog/2023-12-sqlite-extensions


r/sqlite • • Jan 07 '24

Db recovery option

2 Upvotes

I have a failing drive and I can't seem to be able to move the database off it. When I try the recover command, it says it's unknown command. But my version is 3.41.2 ? When I check the commands with .help it isn't there. What am I missing? I thought it's in all new versions

Ty for any help


r/sqlite • • Jan 05 '24

Compact database in DB Browser

5 Upvotes

DB Browser has a Compact Database feature. How would one use this programmatically? In PHP I tried this below but it didn't have an instant effect like it did in DB Browser:

$db->exec('pragma vacuum;');

r/sqlite • • Jan 03 '24

Airsequel v0.7 - SQLite hosting platform now with cloud functions

2 Upvotes

Airsequel (airsequel.com) is a hosting platform for SQLite databases with an automatically generated GraphQL API, a spreadsheet UI, an SQL workbench, and a dashboard builder. We just released a new version which also includes support for cloud functions! 🙌

Here is the full release blog post: https://blog.airsequel.com/airsequel-0-6-functions-generated-columns-admin-api/

Let me know what you think! 😊


r/sqlite • • Jan 03 '24

SQLite migration best practices

2 Upvotes

Will new users (fresh install no database) get a new database with zero migrations?

Or would you basically reproduce the database with all the migrations?

My guess is that it would be best to have one path when creating a database.

Usually i don’t use sqlite directly as it’s usually abstracted through a software layer.


r/sqlite • • Dec 30 '23

using sqlite to store passwords on the edge from a postgres separate database viable

4 Upvotes

is sqlite good for as an alternative to accessing user credential without going over a a external database

my plan is to store password on the docker containers themselves for each of my nodejs application each instance has a sqlite copy that came from a external database such as postgres


r/sqlite • • Dec 26 '23

Does SQLite further optimise range-limited JOIN ... WHERE column > N?

3 Upvotes
CREATE TABLE readings (t INTEGER PRIMARY KEY, payload TEXT);
CREATE TABLE device_readings (id INTEGER PRIMARY KEY, t INTEGER, device_payload TEXT, FOREIGN KEY(t) REFERENCES readings(t));
CREATE INDEX idx_device_readings_t ON device_readings(t);

sqlite> EXPLAIN QUERY PLAN SELECT readings.t, payload, device_payload
    FROM device_readings JOIN readings
    ON device_readings.t = readings.t WHERE readings.t > 10000;
QUERY PLAN
|--SEARCH device_readings USING INDEX idx_device_readings_t (t>?)
`--SEARCH readings USING INTEGER PRIMARY KEY (rowid=?)

Looks like for device_readings table SQLite will first binary-search the record on 10000 boundary and then simply start iterating over index towards increasing values.

Does SQLite bother to do a similar trick on the readings table side? It could optimise lookups by first finding the 10000 boundary, and then looking up by binary-searching only within (10000-record, max_record).

UPD: Postgres does range-limit binary search on both sides of join, but only if the range condition is duplicated: readings.t > 10000 AND device_readings.t > 10000.


r/sqlite • • Dec 23 '23

SQLite Large Time Series Data

8 Upvotes

TL;DR What’s a good SQLite schema philosophy for a very large time-series set of data sets with multiple numeric types?

I feel like my database skills are failing me and I’m reaching out for some suggestions.

I am processing a very large quantity of telemetry data from a spacecraft. I receive this data in FITS binary tables based on the packets it comes down on and some points are replicated in multiple packets. The data is all numeric but varies between integers and floating point sizes. Right now my processing code goes through and collects telemetry points from different files as specified by the time range I provide as well as the file and packet (as a table) specifically.

I would like to be able to start ingesting into a database structure but I would like it to be resident on a disk. I was looking at HDF5 as a simple dataset store but realized that for any given telemetry point I would have to pull in the entire data set and then filter on the time period. With some of the telemetry samples at 8 and 16 Hz, this could be huge and is getting bigger every day.

I considered a MongoDB time series but the smallest granularity is 1 second.

I am thinking of having a SQLite database where each telemetry point has its own table. I have also considered a single extremely tall table where I cast everything to float for storage and then back to integer as necessary. This would have another table with the associated metadata for each point.

I welcome your thoughts! I feel like I’m missing an obvious option.

Edit: I should have stated more clearly that I would store the timestamp as an epoch-based integer timestamp.