sqlite3

Interactively query and update a sqllite database

Sqlite is a non-client/server database using dbname.db, .db-shm and .db-wal files.
No database configuration or installation is needed.
Tables etc are accessable by multiprocesses and access is controled by filesystem constraints.

sqlite3 [options] [databasefile] ['SQLstatments']

-init file Execute file, containng SQL and meta-commands.
-echo Output commands before execution. (useful if commands are in a file)
-cmd [no]header  
-separator sep Output field separator. Default |.
-nullvalue string String used to represent NULL values. Default '' (empty string).
-version  
-help
Use ".open FILENAME" to reopen on a persistent database.

.table .show .schema .indices ?table? .dump ?table? .exit

.help ?-all? ?PATTERN?   Show help text for PATTERN

SQLite version 3.51.0 2025-06-12 13:14:41
Connected to a transient in-memory database.


.changes on|off          Show number of rows changed by SQL
.cd DIRECTORY            Change the working directory to DIRECTORY
.crlf ?on|off?           Whether or not to use \r\n line endings
 -configuration type commands
.progress N              Invoke progress handler after every N opcodes
.quit                    Stop interpreting input stream, exit if primary.
.echo on|off             Turn command echo on or off
.timer on|off            Turn SQL timer on or off
.auth ON|OFF             Show authorizer callbacks
.bail on|off             Stop after hitting an error.  Default OFF
.connection [close] [#]  Open or close an auxiliary database connection
.shell CMD ARGS...       Run CMD ARGS... in a system shell
.show                    Show the current values for various settings
.stats ?ARG?             Show stats or turn stats on or off
.system CMD ARGS...      Run CMD ARGS... in a system shell
.log FILE|on|off         Turn logging on or off.  FILE can be stderr/stdout
.mode ?MODE? ?OPTIONS?   Set output mode
.separator COL ?ROW?     Change the column and row separators
.width NUM1 NUM2 ...     Set minimum column widths for columnar output
.output ?FILE?           Send output to FILE or stdout if FILE is omitted
.exit ?CODE?             Exit this program with return-code CODE

 -database action commands
.tables ?TABLE?          List names of tables matching LIKE pattern TABLE
.fullschema ?--indent?   Show schema and the content of sqlite_stat tables
.dbconfig ?op? ?val?     List or change sqlite3_db_config() options
.dbinfo ?DB?             Show status information about the database
.databases               List names and files of attached databases
.dbtotxt                 Hex dump of the database file

.dump ?OBJECTS?          Render database content as SQL

.backup ?DB? FILE        Backup DB (default "main") to FILE
.check GLOB              Fail if output since .testcase does not match
.clone NEWDB             Clone data into NEWDB from the existing database
.eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN
.excel                   Display the output of next command in spreadsheet
.expert                  EXPERIMENTAL. Suggest indexes for queries
.explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto
.filectrl CMD ...        Run various sqlite3_file_control() operations
.headers on|off          Turn display of headers on or off
.import FILE TABLE       Import data from FILE into TABLE
.import FILE TABLE       Import data from FILE into TABLE
.indexes ?TABLE?         Show names of indexes
.intck ?STEPS_PER_UNLOCK?  Run an incremental integrity check on the db
.limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT
.lint OPTIONS            Report potential schema issues.
.nonce STRING            Suspend safe mode for one command if nonce matches
.nullvalue STRING        Use STRING in place of NULL values
.once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE
.open ?OPTIONS? ?FILE?   Close existing database and reopen FILE
.parameter CMD ...       Manage SQL parameter bindings
.print STRING...         Print literal STRING
.prompt MAIN CONTINUE    Replace the standard prompts
.read FILE               Read input from FILE or command output
.recover                 Recover as much data as possible from corrupt db.
.rekey OLD NEW NEW     Change the encryption key
.restore ?DB? FILE       Restore content of DB (default "main") from FILE
.save ?OPTIONS? FILE     Write database to FILE (an alias for .backup ...)
.scanstats on|off|est    Turn sqlite3_stmt_scanstatus() metrics on or off
.schema ?PATTERN?        Show the CREATE statements matching PATTERN
.session ?NAME? CMD ...  Create or control sessions
.sha3sum ...             Compute a SHA3 hash of database content
.timeout MS              Try opening locked tables for MS milliseconds
.trace ?OPTIONS?         Output each SQL statement as it is run
.version                 Show source, library and compiler versions
.archive ...             Manage SQL archives

.vfsinfo ?AUX?           Information about the top-level VFS
.vfslist                 List all available VFSes
.vfsname ?AUX?           Print the name of the VFS stack

.text-rekey OLD NEW NEW  Change the encryption key using hexadecimal
.hex-rekey OLD NEW NEW   Change the encryption key using hexadecimal
.www                     Display output of the next command in web browser
Results display format:
-list with the separator (| default) between fields
-column tabular format, using space characters to separate the columns and align the output.
-html HTML tables.
-line one value per line, rows separated by a blank line. Easily parsed by other programs

sqlite3 db "vacuum;" can be used to "clean up" the database.

If the database file does not exist, it will be silently created (i.e. no message like "database does not exist " is displayed).

Example: create a new database file named mydata.db, with a table named memos and insert a couple of records into it;

 $ sqlite3 mydata.db  -column -header
       SQLite version 3.7.13  with MAC OSX Mavericks 10.9
       Enter ".help" for instructions
       sqlite> create table memos(text, priority INTEGER);
       sqlite> insert into memos values('deliver project description', 10);
       sqlite> insert into memos values('lunch with Chris', 100);
       sqlite> select * from memos order by priority;
        text                         priority  
        ---------------------------  ----------
        deliver project description  10        
        lunch with Chris             100 
       sqlite> 
ATTACH to multiple databases, useful for migrating data between databases, possibly changing the schema.

SQL statements (separated by semi-colons) can be supplied as an argument. For example:

sqlite3 -line mydata.db 'select * from memos where priority>20; '

META-COMMANDS

Control the output format, examine the database files, or perform maintenance operations on databases (such as rebuilding indices).
Meta-commands are prefixed with a dot (.) .

A pattern is specified using ?object?

.tables [?tabl?] List names of tables`
.schema [?tabl?] Show the CREATE statements that created the table.
Withouit ?tabl? displays ALL.
.indices ?tabl? Show names of indices
.dump ?tabl? ... Dump the database in an SQL text format
.dump access
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;

CREATE TABLE access (    service        TEXT        NOT NULL,     client         TEXT        NOT NULL,     client_type    INTEGER     NOT NULL,     auth_value     INTEGER     NOT NULL,     auth_reason    INTEGER     NOT NULL,     auth_version   INTEGER     NOT NULL,     csreq          BLOB,     policy_id      INTEGER,     indirect_object_identifier_type    INTEGER,     indirect_object_identifier         TEXT NOT NULL DEFAULT 'UNUSED',     indirect_object_code_identity      BLOB,     flags          INTEGER,     last_modified  INTEGER     NOT NULL DEFAULT (CAST(strftime('%s','now') AS INTEGER)), pid INTEGER, pid_version INTEGER, boot_uuid TEXT NOT NULL DEFAULT 'UNUSED', last_reminded INTEGER NOT NULL DEFAULT 0,     PRIMARY KEY (service, client, client_type, indirect_object_identifier),    FOREIGN KEY (policy_id) REFERENCES policies(id) ON DELETE CASCADE ON UPDATE CASCADE);

INSERT INTO access VALUES('kTCCServiceSystemPolicyAllFiles','com.gog.galaxy',0,2,4,1,X'fade0c000000009c0000000100000006000000020000000e636f6d2e676f672e67616c6178790000000000060000000f000000060000000e000000010000000a2a864886f76364060206000000000000000000060000000e000000000000000a2a864886f7636406010d0000000000000000000b000000000000000a7375626a6563742e4f550000000000010000000a395753333651383838360000',NULL,0,'UNUSED',NULL,0,1641059835,NULL,NULL,'UNUSED',0);


          
.read filename Execute filename
.output filename |stdout Direct output
.explain ON|OFF Control output mode suitable for EXPLAIN. default on
.import file table Import data from FILE into TABLE
.log file|
   off |
   stdout |
   stderr
Control logging
.mode mode ?tabl? display
current output mode: column --wrap 60 --wordwrap off --noquote
OR Set output mode (format) where mode is one of:
column Left-aligned columns.
Long column names with short values will place many spaces between values.
select service,client,client_type,auth_value,auth_reason,auth_version,csreq,policy_id from access limit 2;
service                          client          client_type  auth_value  auth_reason  auth_version  csreq  policy_id
-------------------------------  --------------  -----------  ----------  -----------  ------------  -----  ---------
kTCCServiceSystemPolicyAllFiles  com.gog.galaxy  0            2           4            1             ??              
kTCCServiceAccessibility         com.gog.galaxy  0            2           4            1             ??     
.width num1 num2
 label          weight      source      identifier         version     conditions       
-------------  ----------  ----------  -----------------  ----------  -----------------
google chrome  200.0       EQHXZ  com.google.Chrome              {errors=[-613]}
google chrome  300.0       EQHXZ  com.google.Chrome              {errors=[-613]}
csv Comma-separated values
 label,weight,source,identifier,version,conditions
"google chrome",200.0,EQHXZ,com.google.Chrome,,{errors=[-613]}
"google chrome (canary)",300.0,EQHXZ,com.google.Chrome.canary,,{errors=[-613]} 
html HTML <table> code
 <TR><TH>label</TH> <TH>weight</TH> <TH>source</TH>
     <TH>identifier</TH> <TH>version</TH> <TH>conditions</TH> </TR>
<TR><TD>google chrome</TD> <TD>200.0</TD> <TD>EQHXZ</TD>
    <TD>com.google.Chrome</TD> <TD></TD> <TD>{errors=[-613]}</TD> </TR>
<TR><TD>google chrome (canary)</TD> <TD>300.0</TD> <TD>EQHXZ</TD>
    <TD>com.google.Chrome.canary</TD> <TD></TD> <TD>{errors=[-613]}</TD> </TR> 
Which a browser will display as:
label weight source identifier version conditions
google chrome 200.0 EQHXZ com.google.Chrome {errors=[-613]}
google chrome (canary) 300.0 EQHXZ com.google.Chrome.canary {errors=[-613]}

insert SQL insert statements for TABLE
INSERT INTO table(label,weight,source,identifier,version,conditions)
    VALUES('google chrome',200.0,'EQHXZ','com.google.Chrome',NULL,'{errors=[-613]}');
INSERT INTO table(label,weight,source,identifier,version,conditions) 
   VALUES('google chrome (canary)',300.0,'EQHXZ','com.google.Chrome.canary',NULL,'{errors=[-613]}');
line One value per line
    label = google chrome
    weight = 200.0
    source = EQHXZ
identifier = com.google.Chrome
   version = 
conditions = {errors=[-613]} 
     label = google chrome (canary)
    weight = 300.0
    source = EQHXZ
identifier = com.google.Chrome.canary
   version = 
conditions = {errors=[-613]}
list Values delimited by .separator string
 label|weight|source|identifier|version|conditions
google chrome|200.0|EQHXZ|com.google.Chrome||{errors=[-613]}
google chrome (canary)|300.0|EQHXZ|com.google.Chrome.canary||{errors=[-613]}
label,weight,source,identifier,version,conditions
google chrome,200.0,EQHXZ,com.google.Chrome,,{errors=[-613]}
google chrome (canary),300.0,EQHXZ,com.google.Chrome.canary,,{errors=[-613]} 
tabs Tab-separated values
label weight source identifier version conditions
google chrome  200.0 EQHXZ com.google.Chrome {errors=[-613]} 
google chrome (canary) 300.0 EQHXZ com.google.Chrome.canary {errors=[-613]}

Tcl Tcl list elements
"label" "weight" "source" "identifier" "version" "conditions"
"google chrome" "200.0" "EQHXZ" "com.google.Chrome" "" "{errors=[-613]}"
"google chrome (canary)" "300.0" "EQHXZ" "com.google.Chrome.canary" "" "{errors=[-613]}"

.header(s) ON|OFF Turn headers on or off
.bail ON|OFF Stop on error. Default OFF
.prompt main continue prompts
.backup ?DB? fILE DEFAULT "MAIN"
.restore ?DB? file DEFAULT "MAIN"
.show current values
echo: off
eqp: off
explain: off
headers: off
mode: list
nullvalue: ""
output: stdout
colseparator: "|"
rowseparator: "\n"
stats: off
width: 
.stats ON|OFF Set stats
.timeout ms Wait for locked table.
.vfsname ?AUX? VFS stack name unix
.timer ON|OFF Control display of the CPU time
Run Time: real 0.001 user 0.000098 sys 0.000046
.databases List names and files of attached databases
.nullvalue string display string for NULLs
.separator string used by output mode and .import
.trace file|off Display statements as they are run.
.echo ON|OFF
.quit 
.help  

INIT FILE

The sequence of initialization is :
  1. The defaults:
    mode            = LIST  (i.e. Values delimited by separator )
    separator       = "|"
    main prompt     = " " continue prompt = "   ...> "
  2. ~/.sqliterc
  3. -init file
  4. command line options

fts

Allows full-text searches SQLite.org

See also

SQLite.org current version 3.44.2 (2023-11-21) The sqlite-doc package data manuliption commands

Example

see ~/.bin/0ShowQuarantineEvents.sh
 ~/Library/Preferences/com.apple.LaunchServices.QuarantineEventsV2

CREATE TABLE LSQuarantineEvent ( LSQuarantineEventIdentifier TEXT PRIMARY KEY NOT NULL, LSQuarantineTimeStamp REAL, yuck LSQuarantineAgentBundleIdentifier TEXT, LSQuarantineAgentName TEXT, LSQuarantineDataURLString TEXT, LSQuarantineSenderName TEXT, LSQuarantineSenderAddress TEXT, LSQuarantineTypeNumber INTEGER, LSQuarantineOriginTitle TEXT, LSQuarantineOriginURLString TEXT, LSQuarantineOriginAlias BLOB ); CREATE INDEX LSQuarantineEventIndex ON LSQuarantineEvent ( LSQuarantineEventIdentifier );