18 ms·
SQLite the only database you will ever need in most cases
- makapuf 6y agoSqlite is awesome and just enough for many many uses. The thing I wonder if it will come or if its deeply embedded in the DB design are column types. Having everything as a string is the main difference with a standard DB for me. Maybe some optional typing could be enforced ? Anyway, I'm not criticising, being more than grateful for this awesome under the radar but cornerstone piece if tech, just like curl
- slver 6y agoEverything is not stored as string. You set a column to number and pass a number, it's stored as a number. SQLite doesn't enforce it. But people forget the major reason for DB enforcement is multiple application on one database. This pattern has fallen out of favor in general for all databases (we prefer one service layer in front of the DB, and then multiple apps use that service layer). And when you have one app or one service layer, that's where the enforcement can easily come from.
- 7steps2much 6y ago> But people forget the major reason for DB enforcement is multiple application on one database. While that may be the major reason there are other reasons that are just as valid. Such as multiple developers working on a single application, loading "wrong" values into the database for example. If SQLite enforced typing it would be a great alternative for me, but the way it is right now it is "nice", but not nice enough to beat PostgreSQL in any way unless I need an embedded DB. At least in my opinion.
- massysett 6y agoAll you have to do is put a column constraint on there. CREATE TABLE t ( intcol CHECK (typeof(intcol) = ‘integer’));
- jhgb 6y ago> If SQLite enforced typing it would be a great alternative for me, but the way it is right now it is "nice", but not nice enough to beat PostgreSQL in any way unless I need an embedded DB. At least in my opinion. You still have the option of embedding Firebird if you want enforced types AND embedded operation.
- makapuf 6y agoYou could say that for applicative code static typing : it's only useful for multiple callers of your apis. But it can be useful. More generally, the multiple applications can be: the one I write, the one I will refactor to, the one my colleague writes, sqlite3 when manually called for misc. operations and/or sqlite3 when called by admin scripts.
- slver 6y agoIt is actually the same in static typing. JavaScript didn't need formal classes and argument and return types, until Node, NPM, and other large scale projects made those necessary (ergo, TypeScript). Even when using TypeScript, typing your local variables isn't THAT useful. Some do it out of sense of diligence, but the odds are you know what's the type of a local variable in a 30 line method, just by looking at the code. But for libraries to cooperate, or even people to cooperate within a single large project, that represents objects and functions used by multiple callers who don't know that code by heart, and aren't looking at its implementation while using it. Hence, types.
- andrewstuart 6y agoPostgres is the database I use for everything. I find databases of all sorts extremely interesting and I've tried many of them, of all flavors. In the end, I always come back to Postgres. It's unbelievably powerful, lightweight and there's not much it can't do. Why not use sqlite? Here's one example - I like to access my database from my IDE remotely - my understanding is that remote access is not possible with sqlite. Another example - multitenancy is dead easy in postgres, makes things more secure and makes coding easier. Another is that Postgres had an extremely rich set of data types, including arrays and json. Also Postgres is designed for symmetric multiprocessing which matters in today's multicore world.
- ellimilial 6y agoIt can’t run embedded. Having no live parts is a real paradigm shift for so many scenarios.
- andrewstuart 6y agoWhat does "can't run embedded" mean exactly? I've run Postgres in a pure RAM only configuration, never touching the disk except to start. If you mean "it can't be compiled in to another application as a library", then yes that's true - it's not an embedded database.
- mfontani 6y agoCan it be contained within the application, like SQLite? Or has it to run as a separate process?
- yaur 6y ago"can't run embedded" means you have to have a dedicated DB server process. For anything I would use a database for this is a non issue, but if you want a DB in your mobile app (for example) it might be.
- skohan 6y ago
- not_knuth 6y agoCool article. I definitely agree that SQLite is the way to go in 99% of the cases you're making some kind of app. I have often seen Postgres, MySQL and MongoDB in places where they were really overkill and added unnecessary network and deployment complexity. And upon asking the designers it turns out they simply didn't know about SQLite... Small gripe in case the poster reads this: There's a malopropism in the opening bit: > SQLite is properly the only database you will ever need in most cases. Should be: > SQLite is probably
- diarrhea 6y ago> malopropism Malapropism? Can just call it a typo (which is incorrect but people get it).
- thom 6y agoAlways fun to see this sort of comment under an article about using the right tool for the job.
- jmchuster 6y agoIf you wanted to recommend a less descriptive yet more commonly known word, why not use "error" or "mistake"? Typo literally means the opposite of what the OP wants to convey. A typo is when you pick the right word, but type it wrong. A malopropism is when you pick the wrong word, but type it correctly.
- agumonkey 6y agoIn 2021 a typo means an autocorrect fir free.
- niceairport 6y agoI think this is a bit of a case of "Why use many word when few word do trick?"
- bregma 6y agoAre you imploring that 'malapropism' is too sesquipedalian and that one should generally eschew obfuscationism?
- TicklishTiger 6y agoI wish someone would write a set of shell scripts that overcome the hardships when dealing with SQLite databases. For example, deleting a column is a pain in the ass. A single purpose script "rename_column.sh" would be nice, which combines all necessary steps and gives some guidance regarding edge cases.
- antimatter15 6y agoThe latest version (3.35.4) adds `ALTER TABLE DROP COLUMN` https://sqlite.org/releaselog/3_35_4.html https://sqlite.org/releaselog/3_35_4.html
- TicklishTiger 6y agoThat is cool. What is a good way to use 3.35.4 on a system with a Debian version that comes with an older SQLite version?
- feinte 6y agoCompiling it yourself from source is quite easy, you can find instruction here: https://www.sqlite.org/howtocompile.html https://www.sqlite.org/howtocompile.html Here is an article from Julia Evans explaining it: https://jvns.ca/blog/2019/10/28/sqlite-is-really-easy-to-compile/ https://jvns.ca/blog/2019/10/28/sqlite-is-really-easy-to-com... Or if you are familiar with Docker, you can use a more recent Debian in a container and install sqlite inside it.
- TicklishTiger 6y agoIf you compile it yourself, how do security updates get to your system? As for a more recent Debian version: The latest stable Debian has sqlite3 3.27.2 in the repos, so that is not an option.
- xorcist 6y agoSince sqlite is local to your application, you can just bundle a newer version. Speaking generally, if the Debian version is the way to go, the easiest way is often to grab the source package from sid and build it. It's literally just one command. Sometimes new dependencies will cause trouble, in which case some manual tinkering is required.
- lilyball 6y agoThis article says you can back up your database by just copying it, as it’s a single file (and apparently copying it while it’s in use is fine?). It also suggests enabling WAL mode. But WAL mode means you now have two files. Does the use of WAL introduce any concerns while backing up?
- deleted 6y ago[deleted]
- wfriesen 6y agoThe .wal file comes and goes, so occasionally things like rsync will fail if the file no longer exists by the time it tries to transfer.
- izacus 6y agoThe .wal file shouldn't be backed up though.
- CodesInChaos 6y agoWhy? An atomic filesystem snapshot is very similar to power loss. Since WAL is required to handle that scenario, it's just as important when backing up through snapshots.
- dpwm 6y agoIf the .wal file is not backed up, then any information in it will not be backed up. Depending on the settings for the WAL, this can be quite a lot. You would need to do something like the VACUUM INTO trick described above if you want to safely backup the sqlite database from a live filesystem, because there is a risk of the WAL and database being out of sync. I’m not sure that SQLite, good though it is, can get around the WAL being taken at a different time to the rest of the database. The problem here isn’t the .wal file, but doing backups from a moving filesystem. The solution is to use snapshots. ZFS supports snapshots natively, and Linux’s device mapper supports snapshots of any block device. [0] [0] https://www.kernel.org/doc/html/latest/admin-guide/device-mapper/snapshot.html https://www.kernel.org/doc/html/latest/admin-guide/device-ma...
- ABeeSea 6y agoI’m no expert, but isn’t having your entire DB as a single file on the same machine as the application a security risk for a web service?
- dt3ft 6y agoIt makes things very convenient for hackers.
- rplnt 6y agoBut also for the ops, as it means securing one place instead of two.
- collyw 6y agoIf you have access to the application machine, you will likely have access to DB credentials, no? Actually if anyone has some more to add to this discussion, I would be interested to hear, in case I am missing something. I am currently using an SQLite database for a small internal Django app.
- fogihujy 6y agoYou will need to have the database accessible for the process serving the web page and there's no way around that. When using a database stored elsewhere, the config file will still contain the user name and password, but the user's permissions could be restricted in order to prevent access to parts of the data in the database. In the real world though, 99% of all web sites run with a user with full permissions anyway, so if the site gets compromised, you're screwed regardless.
- collyw 6y ago> In the real world though, 99% of all web sites run with a user with full permissions anyway, so if the site gets compromised, you're screwed regardless. Yeah, I was kind of working under that assumption.
- 6y ago
- RcouF1uZ4gsC 6y agoIf you want an super easy way to back up your sqlite database, check out https://litestream.io/ https://litestream.io/ It will continuously backup your database to an S3 compatible service. There are very nice detailed instructions for various backends (AWS, Minio, B2, Digital Ocean) as well as instructions on how to run as a service.
- Namidairo 6y agoHmm, that could be a good solution for backing up a bitwardenrs install, which I think may have more than a few users as of late.
- unixhero 6y agoHow many concurrent write connections and read operations will a SQLite handle?
- slver 6y agoOne write, infinite read. Per file (which matters, since you can have many files). Writes can wait for one another. So you can still handle multiple writers, but serialized. BTW, most people vastly overestimate their concurrency and write frequency needs. For example something like a CMS is 99.999% reads and 0.001% writes (yes, I pulled this out of my behind, but it's close).
- unixhero 6y agoInteresting, thank you!
- cosmotic 6y agoCMS would be low writes assuming no tracking or authentication audit trails or maybe buffered copies of all those.
- slver 6y agoI wouldn't store web logs in an SQLite DB, but I wouldn't do that in any RDBMS typically. Easiest solution is a flat file, which you can import and analyze offsite (in SQLite, or Excel, or whatever :-).
- rickette 6y agoSite gives a "App Error: Error: read ECONNRESET". Is this site powered by SQLite ;).
- pastafooyoung 6y agoAsk A1h about that. The first automated database on this planet was made by IBM to sort the Jews for the Holocaust. Make sure your transaction “semantics” aren’t “anti-Semitic”
- Fordec 6y ago> SQLite is a relational database management system contained in a C library. This got me thinking, had someone done a rewrite in Rust yet?
- mohitsingh 6y agoYou thought right. https://github.com/joaoh82/rust_sqlite https://github.com/joaoh82/rust_sqlite
- combatentropy 6y agoYes, and discussed here about a week ago too: https://news.ycombinator.com/item?id=26749737 https://news.ycombinator.com/item?id=26749737
- the-dude 6y agoOver the last few weeks I built a Rails app, after a ~10 yr hiatus. I love Rails. Rails switched to SQLite for at least the development environment. As soon as I started to test the app with multiple clients ( browsers, websockets, embedded websockets ), I was hit with concurrency errors. So I switched to PostgreSQL ( which I love ). But I had to.
- deleted 6y ago[deleted]
- akvadrako 6y agoSQLite can handle concurrent access but it needs to be used correctly. Each connection should only be used by one thread.
- atat7024 6y agoCan you elaborate/other (maybe lesser known?)/best practices related to this?
- TeMPOraL 6y agoSQLite has good documentation. It covers multithreading and multi-process access too: https://www.sqlite.org/faq.html#q5 https://www.sqlite.org/faq.html#q5 https://www.sqlite.org/faq.html#q6 https://www.sqlite.org/faq.html#q6 https://www.sqlite.org/threadsafe.html https://www.sqlite.org/threadsafe.html TL;DR: - Multiple processes can read the database, but only one can write at any given time; this is enforced using FS locking. - For threading, there are three modes SQLite can operate in: single-threaded (unsafe for use in multiple threads), multi-threaded (safe to use in multiple threads, as long as each thread establishes its own connection) and serialized (do whatever you like, however you like). - The caveat for threading is that if SQLite was compiled with -DSQLITE_THREADSAFE=0 (i.e. single-threaded), then multi-threaded and serialized modes cannot be enabled at runtime, because locking code gets compiled out of the binary.
- jeeeb 6y agoIn my experience SQLite is fine for single process concurrency (just push everything onto a worker thread). However multiprocess concurrency support is very primitive even with WAL support enabled. Internally SQLite relies on file locks to mediate access and this seems to necessitate very coarse locking (lots of table locks). Comparatively the client server model of other databases like PostgreSQL seems to allow better coordination between writes and much finer grained (row level) locking.
- yaur 6y agoSQLlite is awesome right up to the point where it corrupts everything and leaves you in an unrecoverable state. At that point you need to have working backups and a plan to migrate to a real DB server. Actually, if "working backups" is a thing that makes sense for your use case just figure out how to use PostgreSQL now.
- justsomeuser 6y agoHas this happened often? Can you reproduce it? I was under the impression that it’s very difficult to corrupt a DB file if you are using the SQLite API
- yaur 6y agocall fork()
- justsomeuser 6y agoThe docs are quite specific where you can and cannot move connection pointers over threads. You should probably keep each connection owned by a single thread. This is a general “do not share memory” issue, you could fork any non-thread safe C code and see undefined behaviour. Any other issues?
- theamk 6y agoMistakes happen. But only on sqlite, the "undefined behavior" means "all your data is gone". In postgres, you can crash or fail or get invalid results, but you are not going to lose all your data at once.
- justsomeuser 6y agoBut you cannot compare products based on the mistakes programmers make. We are all human. Any tool can be misused though. I think "do not share memory with multiple writers" is in the same category as "do not use a default user/pass, only allow access from the LAN". Both are programmer errors not related to the specific products they are implemented on top of.
- olavgg 6y agoI use Gitea(Github clone) locally with SQLite running on ZFS where I can take atomic snapshots of both the SQLite database and git repositories. This would not be possible if I used a remote database, as there is no way to do a atomic snapshot of both the remote database on another filesystem(even if its ZFS) and the git repository. Developers of multiple services, please support SQLite and don't lock yourself to a single database like PostgreSQL and MySQL. Even if the service is embedded in a Docker Container it is still painful to manage.
- croon 6y agoI've deployed Bitbucket and Postgres as a docker stack under the same subvolume and done snapshots on that. As long as you have WAL enabled in Postgres there shouldn't be an issue, and I've restored multiple times without problems.
- mulander 6y ago> I use Gitea(Github clone) locally with SQLite running on ZFS where I can take atomic snapshots of both the SQLite database and git repositories. ZFS snapshots may not result in a consistent databases backup of sqlite. You should use VACUUM INTO and then do a snapshot or use the sqlite Backup API. See my other comment: https://www.sqlite.org/backup.html https://www.sqlite.org/backup.html Essentially, while you have a proper atomic snapshot of changes on disk the in flight transactions won't be there and you will be on the mercy of having a sucessful recovery from the journal/wal if you have that.
- CodesInChaos 6y agoWhen I back up a database, I expect to get a consistent snapshot of the database, which includes all committed transactions. Uncommitted transactions can't be included in this, since there is no guarantee they'd ever commit. From your answer it sounds like I'd get such a snapshot (even if it relies on recovery from a journal internally). So I don't understand why you see a problem here. Is the recovery process unreliable?
- 6y ago
- saberience 6y agoIn "most cases"? I take it by most cases it means, non enterprise applications with no load and basic use-cases? I can't think of a single application for SQLite at any company I've ever worked for, perhaps my first job for a small e-commerce company. Every database I work with has hundreds of GBs of data at the minimum and has to be highly available (i.e. tolerate any DB server dying with zero downtime) and in most cases, extremely low latency. I.e. respond to hundreds or usual thousands of requests per second with a response time ranging from 100ms to 1ms. Recently most of the databases I'm working with are responding to 10000+ requests per second at an average request time of less than 1ms. Sure, for embedded databases with not much data and a single user, use SQLite, but for actual serious applications it's a toy.
- sdoering 6y ago> but for actual serious applications it's a toy I tend to disagree. As do a lot of others [1]. [1]: https://www.sqlite.org/famous.html https://www.sqlite.org/famous.html
- saberience 6y agoAgain, these are not distributed high throughput applications. This is a database as a bank-end for single user applications or otherwise small-scale usage.
- mrweasel 6y agoThere's a huge range between "a toy" and "high throughput applications", most of which are still serious business.
- citrin_ru 6y agoIf you need HA then SQLite is out of the question, but query latency is usually lower than for MySQL/Postgres - with an embedded DB you are avoiding network latency. See also https://sqlite.org/np1queryprob.html https://sqlite.org/np1queryprob.html
- staticelf 6y agoI really like SQLite but I also like postgres because it supports more complex data types. Sure you can do the same in SQLite by destructuring the data over multiple tables but it's just not as easy or straightforward. This is why developing with MongoDB is so fast and easy in the beginning. You just go, store shit like you structure your data in code which makes the mapping extremely easy in most cases.
- mdoms 6y agoOh good we've met our monthly quota for wildly exaggerating the capabilities of SQLite.
- Jweb_Guru 6y agoI feel like most of the hyperbole would be resolved if people would differentiate between SQLite the storage engine (which is indeed excellent, especially if you're working in a language like C or Rust that allows plugging into the virtual tables API) and SQLite the RDBMS, which is very much not and is actually guilty of most of the things people accuse MySQL of. There are plenty of reasons not to use SQLite that have nothing to do with its performance for your workload.
- atat7024 6y ago> There are plenty of reasons not to use SQLite that have nothing to do with its performance for your workload. Go on
- Jweb_Guru 6y agoIf you like foreign key constraints to actually be enforced automatically (without turning them on in a pragma and/or expecting that everyone who connects to your database does the same or uses a version compiled with custom flags), transactions not to allow an accidental commit after a syntax error, richer indices than btree ones, enforced typechecking without a CHECK constraint, DML commands other than SELECT telling you what rows were returned, etc., the functionality is simply missing in SQLite. Some of it is for backwards compatibility, some not, but at the end of the day it's just not as pleasant to use as something like Postgres as a SQL database. These have all caused issues I actually ran into while using the database, some of which led to integrity violations that took a long time to fix. Sure, they're documented behaviors, but that does not mean they're good behaviors, and they substantially restrict the situations in which I'm willing to deploy it far more than any scalability issues do. If, on the other hand, you're just using it as a transactional storage engine, none of this stuff really matters and I understand the praise--hence why I think the two modes of use should be differentiated. The other thread responding to me is basically all about extending the very barebones provided interface with custom, application-level semantics. I agree that SQLite is excellent for this, but you have to remember that this is not the only thing people want out of a database.
- cosmotic 6y ago1ms write latency means max 1000 writes per second. That seems low for a "medium sized app".
- elnygren 6y agoUgh a dynamically typed SQL database, no thanks. I always find I have to build quite a bit of a "data layer" on top of SQLite for example when using it in mobile apps. Also you have to build some basic stuff yourself like Enum or JSON support. It's not hard but honestly I would feel much better using PostgreSQL in those situations.
- klysm 6y agoIt's not really dynamically typed in the sense that there isn't a schema.
- elnygren 6y agoHowever the schema does look like type schema = { field1: any, field2: any, ... } AFAIK the column types are not really enforced and you can even leave them out. https://stackoverflow.com/questions/2489936/sqlite3s-dynamic-typing https://stackoverflow.com/questions/2489936/sqlite3s-dynamic...
- CodesInChaos 6y agoAFAIK it's even worse than that. The field types can trigger lossy transformation of the input data, but aren't enforced. https://www.sqlite.org/datatype3.html#type_affinity https://www.sqlite.org/datatype3.html#type_affinity
- rplnt 6y agoFor JSON support, there seems to be an extension: https://www.sqlite.org/json1.html https://www.sqlite.org/json1.html Haven't used it, was just wondering if there's something as I found myself quite happy with JSON support in mysql/aurora.
- shakkhar 6y agoTake a look at https://cgsql.dev/ https://cgsql.dev/. It's supposed to be a lightweight and strict type-checked data layer on top of sqlite.
- forgotmypw17 6y agoI think the file system is the best database we have to date, and it's what I use for the "base" data store in my most recent applications. However, for querying, SQLite makes a nice caching layer.
- atat7024 6y agoAre these consumer apps? Are you doing this in LocalStorage?
- forgotmypw17 6y agoNo. No.
- deleted 6y ago[deleted]
- l0rn 6y agoIt's a nice wrap up of why SQLite might be more powerful than one might think. And actually is suitable for more usecases than testing or client application storage. But imho the title is a clickbaity and not very accurate. The featureset of postgres has so much convenience that I do use in most web applications, like spatial queries and indexes (via postgis), trigram similarity, queryable JSON fields etc. Wouldn't wanna miss all that niceness.
- jhgb 6y agoSQLite does have a spatial extension in Spatialite. Whether it's enough for you is up to you to decide. FTS5 does seem to have some trigram matching function that again may or may not be sufficient for you.
- EMM_386 6y agoIf anyone is looking for an open source Windows/MacOS GUI for SQLite, this one has worked well for me: https://github.com/sqlitebrowser/sqlitebrowser https://github.com/sqlitebrowser/sqlitebrowser
- EMM_386 6y agoI'm too late to edit but this client also supports Linux and has a FreeBSD port.
- cloudfabrix 6y agoNicely summed up
- napolux 6y ago> Several processes or threads may access the same database concurrently and read accesses can be run in parallel. Because the database consists of a single file, a write access can only be satisfied if no other accesses are currently writing to the database. Which is perfectly fine for many of my sideprojects. I use SQLite and quite happy with that, but when I need to write to the DB I still prefer PostgreSQL
- hardwaresofton 6y agoPostgres is better in the I-need-concurrency case -- I think it's the greatest RDBMS that's ever been made and would like someone to prove me wrong some day. SQLite's amazing too though, when you don't need concurrency (and most websites don't really -- especially the ones that should be scaling vertically instead of horizontally). Anyway here's some cool SQLite stuff: - https://github.com/CanonicalLtd/dqlite https://github.com/CanonicalLtd/dqlite - https://github.com/rqlite/rqlite https://github.com/rqlite/rqlite - https://datasette.readthedocs.io/en/stable/ https://datasette.readthedocs.io/en/stable/ - https://www.sqlite.org/rtree.html https://www.sqlite.org/rtree.html - https://github.com/sqlcipher/sqlcipher https://github.com/sqlcipher/sqlcipher - https://github.com/benbjohnson/litestream https://github.com/benbjohnson/litestream - https://github.com/aergoio/aergolite https://github.com/aergoio/aergolite - https://sqlite.org/lang_with.html#rcex3 https://sqlite.org/lang_with.html#rcex3 - https://github.com/sql-js/sql.js https://github.com/sql-js/sql.js - https://www.gaia-gis.it/fossil/libspatialite/index https://www.gaia-gis.it/fossil/libspatialite/index - https://github.com/h3rald/litestore https://github.com/h3rald/litestore - https://github.com/adamlouis/squirrelbyte https://github.com/adamlouis/squirrelbyte - https://github.com/chunky/sqlite3todot https://github.com/chunky/sqlite3todot - https://github.com/nalgeon/sqlite-plus/ https://github.com/nalgeon/sqlite-plus/ - https://www.sqlite.org/json1.html#jsonpath https://www.sqlite.org/json1.html#jsonpath
- bob1029 6y agoIf you only ever have 1 database server and 1 application server, then SQLite is deterministically faster in the embedded single-server scenario. This is our configuration model for our application. I acknowledge this is not everyone's configuration model (today), but if you entertain the insanity for a moment you might find the performance uplift of a single-machine app to be staggering. Query execution latency for SQLite on the same machine running on NVMe disk can be measured in microseconds. You will never see this kind of performance across the network, or even loopback. Thus, there is literally no way from an information theory perspective, that Postgres, SQL Server, Oracle, DB2, MongoDB, Dynamo, Aurora, et. al. could ever hope to beat the throughput of (properly-configured) SQLite operating embedded in the application itself.
- 6y ago
- nxpnsv 6y agoSQLite is cool and all, but using ever with the caveat most cases really is indicative of that it is not ever. Additionally, I would contest not even most cases. The post is correct in that SQLite often is fine though.
- gwd 6y ago> SQLite is cool and all, but using ever with the caveat most cases really is indicative of that it is not ever. I think the "ever" is about "will I ever need to upgrade to a server-based database in this particular case". I.e., in cases A and B, you might do OK for a year or two with SQLite, but if your project grows, eventually you'll have to upgrade to Postgres; in these cases, SQLite is not the only database you'll ever need. But in cases C, D, E, and F, you'll never have to upgrade; in these cases, SQLite is the only database you'll ever need. The cases where SQLite is the only database you'll ever need outnumber the cases where SQLite is not the only database you'll ever need; thus, "SQLite is the only database you'll ever need in most cases."
- nxpnsv 6y agoHowever, in many of your cases C, D, E, and F perhaps it is not even a data base you need, but a simple .csv or .json file...
- chousuke 6y agoIf the data changes, it's nearly unconditionally a better idea to use SQLite over those things. CSV and JSON are serialization formats for data exchange between systems, not something suitable as application storage. SQLite is also much more convenient for anyone who later wants to explore your application's data than JSON structures.
- laurent123456 6y agoEvery other day there's a "Use SQLite for everything" article on HN, yet like all RDBMS it's good for certain things and not so much for other things.
- bob1029 6y agoWe've been using SQLite as our principal data store for 6 years. Our application services potentially hundreds of simultaneous users at once, each pushing 1-15 megabytes of business state to/from disk 1-2 times per second. We have not had a single incident involving performance or data integrity issues throughout this time. The trick to this success is as follows: - Use a single SqliteConnection instance per physical database file and share it responsibly within your application. I have seen some incorrect comments in this thread already regarding the best way to extract performance from SQLite using multiple connections. SQLite (by default for most distributions) is built with serialized mode enabled, so it would be very counterproductive to throw a Parallel.ForEach against one of these. - Use WAL. Make sure you copy all 3 files if you are grabbing a snapshot of a running system, or moving databases around after an unclean shutdown. - Batch operations if feasible. Leverage application-level primitives for this. Investigate techniques like LMAX Disruptor and other fancy ring-buffer-like abstractions if you are worried about millions of things per second on a single machine. You can insert many orders of magnitude faster if you have an array of contiguous items you want to put to disk. - Just snapshot the whole VM if you need a backup. This is dead simple. We've never had a snapshot that wouldn't restore to a perfectly-functional application, and we test it all the time. This is a huge advantage of going all-in with SQLite. One app, one machine, one snapshot, etc...
- 3np 6y ago- Don't run on network-attached or distributed file systems because you will have corruption with WAL
- warmwaffles 6y agoThis is only true if you have more than one writing connection to the database. But that said, it is still a good idea to not have the database housed on a network attached store.
- bob1029 6y agoOpening connections to SQLite over the network defeats the entire purpose of using this library.
- rcarmo 6y agoThe article kind of glosses over the lack of common column data types. I love SQLite and use it on everything, but parsing and formatting dates (for instance) gets really old after a while.
- bob1029 6y agoI know this potentially turns into a wildfire debate about future meeting dates across timezones, but for us we still have not had any problems storing all datetimes as 64 bit unix timestamp values. There is only 1 situation where we actually care about the timezone of something, and it is stored on the basis of the user profile, not any specific timestamps. Time is just time. The TZ info is usually part of something entirely separate. Any timestamp can be interpreted in any tz, as long as you have a consistent UTC basis to operate from and knowledge of the desired tz. If the concern is the final formatting, then maybe consider writing some UDFs in your app to quickly format fields. Comparison and sorting of 64 bit integers is trivial, so none of this should be a problem at all...
- flohofwoe 6y ago> Even if you start out small and later need to upscale, as long as your web application can run on the same machine as the database, which it can in 99% of the time... It's not really "upscaling" if it still can be handled by one machine though isn't it? And it might be much cheaper to handle the same load on a number of weaker "machines" than a single powerful "machine" (replace "machine" with cloud VMs). And for such "small-scale" problems, it's also not a big deal to run a "proper" DB server process on the same machine (but with the advantage that it's absolutely trivial to switch to multiple machines).
- Ensorceled 6y agoYeah, I don't get some of these "advantages", I have a standalone server running MySQL and another running Postgres. No problems for years. Being a DBA for these things isn't even a 1hr a month job these days, I'm not sure I did any DBA work since 2019 unless you count the migrations.
- Markxr 6y agosqlite is amazing and everything. I still use Postgresql for most things - the tool support is genuinely a lot better. I also find the explain output much easier to understand. There are also features which I occasionally use which Postgresql support such as partitioning, functional indexes, partial indexes. These can be emulated in some way with sqlite I'm sure, but they are fairly nice. I have implemented some really critical stuff in sqlite and it's been amazing though. Anyone using sqlite in production needs to really understand the concurrency limits though.
- 3np 6y agoNot in its current state - it becomes entirely unsuitable as soon as you need to have multiple instances (be it for scalability or availability). Sqlite is inherently single instance. What really makes this an issue is that it doesn't work safely/reliably on distributed filesystems like GlusterFS and Ceph. See here for example of a project that needs to be forked in order to not have data corruption on remote filesystems (it depends on the WAL mode AIUI): https://github.com/Sonarr/Sonarr/issues/1886 https://github.com/Sonarr/Sonarr/issues/1886 I really do hope that this will be addressed in a future version of Sqlite, which would at least allow running it on redundant network-attached storage. But even if it is, you will still have issues once you want to scale horizontally for performance. If you're building strictly in-house proprietary software, none of this really matters as you have full control. But if it's either FLOSS or otherwise to be operated by anyone else than the developer and their internal organization, SQLite is not suitable. I die inside a bit every time I am expected to take responsibility for a software built on Sqlite.
- gwd 6y agoFrom TFA: The only time you need to consider a client-server setup is: - Where you have multiple physical machines accessing the same database server over a network. In this setup you have a shared database between multiple clients. - If your machine is extremely write busy, like accepting thousand upon thousands of simultaneous write requests every second, then you also need a client-server setup because a client-server database is specifically build to handle that. - If you're working with very big datasets, like in the terabytes size. A client-server approach is better suited for large datasets because the database will split files up into smaller files whereas SQLite only works with a single file. I have run SQLite as a web application database with thousands concurrent writes every second, coming from different HTTP requests, without any delays or issues. This is because even on a very busy site, the hardware is extremely fast and fully capable of handling that. The claim is that most of the time you don't actually need multiple instances.
- 3np 6y agoNot covered: Single application server with network-attached highly available storage
- jstsch 6y agoI love SQLite. Used it to set up a small PHP tool which allowed users to check if their data was present in the latest Facebook leak. Took 30 mins of coding, incl. data import. The tool got picked up by the national media and the tiny 1GB VPS got quite hammered with traffic (±50 lookups a second, 5.5M records). But it didn't break a sweat. The only snag I ran into was running out of file descriptors/sockets, which was easily solved.
- hesk 6y agoSQLite is great! But if you have mainly analytical queries over your data, you might want to give DuckDB [1] a go. It's an embedded database that uses a columnar representation similar to MonetDB (it's from the same group). [1] https://duckdb.org/ https://duckdb.org/
- legg0myegg0 6y agoI completely agree!! We see 20-100x performance from DuckDB over SQLite for OLAP style queries.
- ricg 6y agoIs SQLite a good choice for a user facing file format? I.e. were the user can access the database file in Finder/Explorer and make a copy at any point in time to share, backup, etc. Would that copy be consistent?
- snuxoll 6y agoAs long as it’s not actively being written to, yes. Even enabling WAL won’t save you from inconsistent backups without use of the backup API or atomic file system snapshots when writers are active.
- ricg 6y agoWell, I'm thinking of an app that lets the user edit some kind of document. At some point the changes have to be saved. Could this happen to the "live" file or would the workaround be to keep a temporary copy somewhere away from the user and copy that back and forth?
- snuxoll 6y agoYes, using the backup API you could load on on-disk database into memory and then do the reverse to a temp file and atomically move it to replace the saved copy. There’s even an example of using the backup API for this on the SQLite website https://www.sqlite.org/backup.html https://www.sqlite.org/backup.html This wouldn’t be a great solution for large databases, but if you’re using it as a document format up to the couple dozen MB range it’s the perfectly acceptable. Alternatively you could just go the working copy route - make a copy of the database on open and move it back in place when closed. This would also let you recover unsaved changes if you crash or are terminated before the user hits save, as well as the obvious benefit of not needing to keep the entire database loaded in memory and needing to write the entire thing out on save.
- ricg 6y agoThanks for the details. I'll take a closer look. The documents of my app can get quite large, up to 300 to 400 MB (lots of small images). I was thinking to use SQLite as an alternative to the ZIP based format that I'm using at the moment, hoping to avoid the working copy route that I use today, but looks like that would be tricky.
- zubairq 6y agoI really agree with this article. I actually built an App with Sqlite as the backend that works locally, on kubernetes, on the mac app store , on Raspberry PIs, and almost anywhere and it has performed fantastically for years now. The biggest thing is that you have to make sure you always wrap your SQLite queries in a transaction, otherwise you can get corruption: https://github.com/yazz/visualjavascript https://github.com/yazz/visualjavascript
- nikisweeting 6y agoI love SQLite but it's really a pain to do concurrent writes from multiple long-lived threads. Even in WAL mode, having multiple writers leads to tons of "database locked" errors and applications fall over. The writes don't even have to be complicated, single-row atomic updates with no table locking, and SQLite is not able to serialize them and handle them gracefully without triggering errors, that's up to the application. The extra work of having to manually implement inter-thread coordination to prevent hitting the DB at the same time is a lot of work that never gets mentioned. When people talk about SQLite being able to handle tens of thousands of writes per second, there's a big asterisk, that's only if the application takes care of not making them write at the same time.
- utxaa 6y agowe just slurp/dump clojure maps to disk. clojure is our query language.
- harperlee 6y agoAs a clojure user, that's an apples-to-oranges comparison. Out of the box clojure does not provide you with out-of-order slurp/dump info against a file, does not provide you with indexes, etc. You can load everything into memory and create an efficient structure in your EDN but a) you need to implement it yourself; b) if your machine crashes, you lose it, because by default you work in memory, so you need to manually manage saving to disk. So basically I can just say the same thing you said with C: "I just fopen/fgetc strings to disk. C is my query language."
- utxaa 6y agoit's not that apples to oranges. op is saying they use sqlite, i'm saying we use edn files. just offering another point of view. if by out-of-order you mean loading parts of a file, of course we don't do that. we don't load everything into memory (there's more than one file). just like you wouldn't load your whole sqlite db into memory. if the machine crashes we lose what we didn't save. same with a db. > So basically I can just say the same thing you said with > C: "I just fopen/fgetc strings to disk. C is my query > language." as a clojure user you know this is not a good analogy. c has macros too. the main problem with our approach is that the server needs to have access to the edn files. that's not always doable ... but same problem with sqlite. and it is oh so nice to investigate stuff in the repl: (:prio (load-file (filter #(= "secret-id" (:id %)) index))) btw, i loved to kill a mocking bird.
- harperlee 6y agoHow is not apples to oranges? You are comparing a library that implements a database (with a specific binary file format that any sqlite instance understands, and a query language, among other functionalities) to a programming language! With sqlite, creating an index is a one-liner. How do you cover that in clojure? With sqlite, a whole database fits in one file that can be read by almost any macos / linux machine. With clojure, you need your specific program created on top of clojure installed in the machine. Etc. At the end of the day, you can reimplement sqlite on clojure, which basically proves that we are talking about different abstraction levels, thus apples to oranges.
- kjgkjhfkjf 6y ago> you can just upgrade the hardware to a beefier machine and keep business as usual One of the troubles with having a single machine is that your service will become unavailable when you upgrade it.
- geebee 6y agoI personally think that SQL and tabular data should be built into languages in a manner similar to text and regular expressions. I get his (partially) in python by using pandas and pandasql, which (to my understanding) initiates sqlite in the background. There are a few other modules that do this as well. Recreating relational table query operations as a set of operations unique to a specific programming language instead of integrating SQL makes, to me, as much conceptual sense as recreating a unique text pattern matching search for each language rather than integrating regular expressions. This is only a small sliver of the topic here, but I do think that SQLite is probably a good backend for this.
- weird-eye-issue 6y agoThat's basically what an ORM is. In fact Django uses SQLite out of the box and their ORM overrides lots of Python's operators so there we are!
- geebee 6y agoI haven't used an ORM for some time (back when I programmed in Rails), but my experience and understanding is that an ORM largely replaces hand written SQL for a number of CRUD-style queries to manage object relational mapping for a persistence tier, and addresses a different issue than native vs SQL based operations in tabular environment such as as Pandas or R-dataframes. What I'm talking about is this: https://pandas.pydata.org/pandas-docs/stable/getting_started/comparison/comparison_with_sql.html https://pandas.pydata.org/pandas-docs/stable/getting_started... I personally am not especially interested in recreating relational set operation using pandas operations. There are things I'd much rather do in pandas (such as summary statistics), and some things I'd much rather do in SQL elaborate JOINs and aggregations. I do admit there will be a grey area. Interestingly, there are a lot of people who absolutely can't stand SQL, whereas I (and a lot of people) vastly prefer it. As for ORMs - I actually did like them back when I did this sort of programming (managing the back and forth between objects and tables was honestly very boring), though once I was into reports, I often went straight to raw SQL. I no longer do that sort of work, and almost all code I now write is for analytical purposes, so I don't do any CRUD.
- guenthert 6y agoI think I need help understanding the use case. Like others, I'm quite happily using a PostgreSQL server, when I need to query a DB using SQL. This clearly doesn't work in the embedded case, but why would I need SQL there? Why wouldn't be an embedded key/value DB like Berkeley DB (which also offers ACID, transactions and write-ahead-logging) be sufficient there? I for one am quite surprised to learn that a web browser would have a SQL DB built-in.
- asimpletune 6y agoWhat’s the portability between SQLite and something like Postgres or MySQL? Can you easily start with SQLite and then go to one of the others easily? If so I don’t see why you wouldn’t always start noodling with SQLite.
- rattray 6y agoIt's a bummer that DBeaver can't just open a sqlite file and do the right thing. Anyone know an app that makes it easy to just "double-click" a sqlite file and get it pulled up in a convenient db GUI?
- LeonM 6y agoHaven't tried it with SQLite databases yet, but you could give JetBrains DataGrip a try.
- anaganisk 6y agoBeekeeper Studio
- rattray 6y agoWow, looks very slick! Surprised I hadn't heard of this one. Doesn't have the functionality I was asking for, though – filed an issue here: https://github.com/beekeeper-studio/beekeeper-studio/issues/629 https://github.com/beekeeper-studio/beekeeper-studio/issues/...
- blacklight 6y agoI use SQLite for many of my applications, but definitely not for all of them. SQLite is probably not the right tool if you have concurrent access to the database, nor if you want to enforce database consistency through triggers. It is the perfect application if you need a database that you can easily move around, access from a single application and your use case is simply to load and dump data with no further transformation. Anything more than that requires an RDBMS.
- aryeshalev 6y agoI love SQLite, I do all of my projects prototyping before I move to postgres which is also awesome. One if the major problems in facing is that heroku for example in every build will override/delete the SQLite DB since it treats it the same as every file - which is a shame.