SlideShare a Scribd company logo
Introduction 4 SQLite


        Stanley Huang
    wenline1001@gmail.com




                            1/20
Agenda
How to install SQLite on Ubuntu
SQLite client samples
SQLite performance tuning and optimization
 tips
FAQ
Reference
Q&A

                                2/20
How to install SQLite on Ubuntu
Use apt-get
      stanley@Stanley-Ubuntu:/etc$ sudo apt-get -y install sqlite3
      Reading package lists... Done
      Building dependency tree
      Reading state information... Done
      Suggested packages:
       sqlite3-doc
      The following NEW packages will be installed:
       sqlite3
      0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
      Need to get 28.3kB of archives.
      After this operation, 119kB of additional disk space will be used.
      Get:1 http://us.archive.ubuntu.com/ubuntu/ lucid/main sqlite3 3.6.22-1 [28.3kB]
      Fetched 28.3kB in 1s (21.6kB/s)
      Selecting previously deselected package sqlite3.
      (Reading database ... 455043 files and directories currently installed.)
      Unpacking sqlite3 (from .../sqlite3_3.6.22-1_amd64.deb) ...
      Processing triggers for man-db ...
      Setting up sqlite3 (3.6.22-1) ...
      stanley@Stanley-Ubuntu:/etc$


                                                                                        3/20
SQLite client samples
$ which sqlite3
/usr/bin/sqlite3
$ sqlite3
sqlite>




                         4/20
.help
sqlite> .help
.backup ?DB? FILE        Backup DB (default "main") to FILE
.bail ON|OFF         Stop after hitting an error. Default OFF
.databases          List names and files of attached databases
.dump ?TABLE? ...       Dump the database in an SQL text format
               If TABLE specified, only dump tables matching
               LIKE pattern TABLE.
.echo ON|OFF          Turn command echo on or off
.exit          Exit this program
.explain ?ON|OFF?       Turn output mode suitable for EXPLAIN on or off.
               With no args, it turns EXPLAIN on.
.genfkey ?OPTIONS? Options are:
               --no-drop: Do not drop old fkey triggers.
               --ignore-errors: Ignore tables with fkey errors
               --exec: Execute generated SQL immediately
              See file tool/genfkey.README in the source
              distribution for further information.

                                                                           5/20
.help (cont.)
.import FILE TABLE Import data from FILE into TABLE
.indices ?TABLE?      Show names of all indices
               If TABLE specified, only show indices for tables
               matching LIKE pattern TABLE.
.load FILE ?ENTRY? Load an extension library
.mode MODE ?TABLE? Set output mode where MODE is one of:
               csv    Comma-separated values
               column Left-aligned columns. (See .width)
               html HTML <table> code
               insert SQL insert statements for TABLE
               line One value per line
               list Values delimited by .separator string
               tabs Tab-separated values
               tcl   TCL list elements

                                                          6/20
.help (cont.)
.output FILENAME        Send output to FILENAME
.prompt MAIN CONTINUE Replace the standard prompts
.quit          Exit this program
.read FILENAME         Execute SQL in FILENAME
.restore ?DB? FILE Restore content of DB (default "main") from FILE
.schema ?TABLE?          Show the CREATE statements
               If TABLE specified, only show tables matching
               LIKE pattern TABLE.
.show            Show the current values for various settings
.tables ?TABLE?       List names of tables
               If TABLE specified, only list tables matching
               LIKE pattern TABLE.



                                                          7/20
Create Databases
$ sqlite3
sqlite> attach database '/tmp/db1' as db1;
sqlite> attach database '/tmp/db2' as db2;
sqlite> .database
seq name               file
--- --------------- ----------------------------------------------------------
0 main
2 db1               /tmp/db1
3 db2               /tmp/db2




                                                                  8/20
Create Tables
sqlite> create table db1.t11 (id int);
sqlite> create table db1.t12 (id int);
sqlite> create table db2.t21 (id int);
sqlite> create table db2.t22 (id int);




                                     9/20
Insert Data
sqlite> insert into db1.t11 values (11);
sqlite> insert into db1.t12 values (12);
sqlite> insert into db2.t21 values (21);
sqlite> insert into db2.t22 values (22);




                                    10/20
Show Tables/Schema
sqlite> .restore db1
sqlite> .tables
t11 t12
sqlite> .restore db2
sqlite> .tables
t21 t22
sqlite> .schema t21
CREATE TABLE t11(id int);


                            11/20
SQLite performance tuning and
        optimization tips
Back it up or lose it!
  File base, easy to backup by cp command.
Always add an anonymous primary key!
PRAGMA cache_size = ?
  Prior SQLite 2.8.6 split into a BTREE with default “1K” size pages, after 2.8.6 default cache size
   is “2K”.
PRAGMA temp_store = 1
  The choices are DEFAULT (0), FILE (1) and MEMORY (2).
PRAGMA synchronous = OFF
  Default SQLite would wait data write to file, when set synchronous “OFF” and process crash,
   the data file might be corrupt.
PRAGMA journal_mode = MEMORY
  Transaction would be fast, but if process crash, data file might be corrupt.
USE TRANSACTION



                                                                            12/20
SQLite performance tuning and
   optimization tips (Cont.)
Create proper index.
  Proper column of indexes.
  Proper number of indexes.
Compare with “create index then insert data” and “insert data then
 create index”
  With mass of data, “insert data then create index” would be faster.
Simplify the database schema
Don't generalize the database schema
Use temporary tables for intermediate result
Avoid using view and sub-queries
Ordering the tables correctly in where clause



                                                            13/20
SQLite performance tuning and
  optimization tips (Cont.)
Optimizing queries
  Use EXPLAIN command
  Temporary tables
  Order subqueries and smaller results returned
   first
  Use LIMIT and OFFSET
  Replace GLOB and LIKE when possible
  USE IN instead of OR


                                     14/20
SQLite performance tuning and
  optimization tips (Cont.)
Reduce data file size
  Compact database
  Recompiling SQLite with different page size
  Compress large data




                                     15/20
FAQ
What datatype does SQLite support?
  SQLite uses dynamic typing. Content could be INTEGER, REAL,
   TEXT, BOLB or NULL
SQLite let me insert a string into a integer column.
  SQLite uses dynamic typing.
Is SQLite threadsafe?
  SQLite is threadsafe.
  Prior to 3.3.1, SQLite could only used in the same thread.
What's the maximum size for varchar?
  SQLite does not enforce the length of a VARCHAR.



                                                    16/20
FAQ (cont.)
Does SQLite support BOLB?
  SQLite 3.0 and later supported.
How to delete columns from existing table?
  Alter table only support “add column” and “rename table”. Else, you need to
    re-create table.
Does SQLite support foreign key?
  As of verson 3.6.19, SQLite supports foreign key constraint.
I deleted lots of data but data file didn't get smaller.
  You need to run “VACUUM” command to shrink it.
  In SQLite 3.1, you could use auto_vacuum pragma to shrink it automatically.
    But not recommanded, because it take a long time to do it.




                                                            17/20
Reference
SQLite Document
http://sqlite.org/docs.html
Pragma of SQLite
http://www.sqlite.org/pragma.html
Limits of SQLite
http://www.sqlite.org/limits.html


                                    18/20
Q&A




      19/20
Thanks




         20/20

More Related Content

PPTX
SQLite: Light, Open Source Relational Database Management System
PPTX
SQLite - Overview
PPTX
Sqlite
PDF
SQLite 3
PDF
SQLite3
PPTX
Sq lite presentation
PDF
Introduction to SQLite: The Most Popular Database in the World
PPT
Sqlite
SQLite: Light, Open Source Relational Database Management System
SQLite - Overview
Sqlite
SQLite 3
SQLite3
Sq lite presentation
Introduction to SQLite: The Most Popular Database in the World
Sqlite

What's hot (20)

PPTX
A brief introduction to SQLite PPT
PPTX
SQLite database in android
PPTX
PPTX
android sqlite
PDF
Getting Started with SQLite
PDF
Persitance Data with sqlite
PPTX
Android Training (Storing data using SQLite)
PDF
Mysql
PPTX
Using sqlite database in android with sqlite manager browser add ons
PPTX
Microsoft sql server architecture
PDF
HPE NonStop SQL WebDBS - Introduction
DOCX
Android database tutorial
PDF
PGConf.ASIA 2019 Bali - A step towards SQL/MED - DATALINK - Gilles Darold
PPTX
Geek Sync | SQL Security Principals and Permissions 101
PPTX
Geek Sync | Data Integrity Demystified - Deborah Melkin | IDERA
PPTX
Sql server backup internals
PPTX
Android Database
PDF
Difference between sql server 2008 and sql server 2012
PDF
Developers’ mDay 2021: Bogdan Kecman, Oracle – MySQL nekad i sad
A brief introduction to SQLite PPT
SQLite database in android
android sqlite
Getting Started with SQLite
Persitance Data with sqlite
Android Training (Storing data using SQLite)
Mysql
Using sqlite database in android with sqlite manager browser add ons
Microsoft sql server architecture
HPE NonStop SQL WebDBS - Introduction
Android database tutorial
PGConf.ASIA 2019 Bali - A step towards SQL/MED - DATALINK - Gilles Darold
Geek Sync | SQL Security Principals and Permissions 101
Geek Sync | Data Integrity Demystified - Deborah Melkin | IDERA
Sql server backup internals
Android Database
Difference between sql server 2008 and sql server 2012
Developers’ mDay 2021: Bogdan Kecman, Oracle – MySQL nekad i sad
Ad

Viewers also liked (12)

PPT
MySQL進階介紹
PPT
MySQL入門介紹
PDF
Python sqlite3
PPTX
PPTX
Hdmi cables
PDF
SQLite
PPTX
SQLite
PPTX
Graphical User Interface (Gui)
PPT
Uml - An Overview
PPT
XML - Parte 2
PPTX
Extreme programming
MySQL進階介紹
MySQL入門介紹
Python sqlite3
Hdmi cables
SQLite
SQLite
Graphical User Interface (Gui)
Uml - An Overview
XML - Parte 2
Extreme programming
Ad

Similar to Introduction4 SQLite (20)

DOCX
PDF
The sqlite3 commnad line tool
PDF
How sqlite works
PPTX
Sq lite
PPTX
Sqlite3 command reference
PDF
IR SQLite Session #1
PDF
Sq lite module5
PDF
Android Level 2
PPT
Os Owens
PDF
Waiting too long for Excel's VLOOKUP? Use SQLite for simple data analysis!
PPTX
Data Handning with Sqlite for Android
PDF
2011 06-sq lite-forensics
PDF
Introduction to sq lite
PPTX
Databases for Beginners SQLite
PPT
Geek Austin PHP Class - Session 4
DOCX
SQLiteWrittenExplanation
PPT
MySql slides (ppt)
PPTX
Python SQLite3...
PDF
IR SQLite Session #3
The sqlite3 commnad line tool
How sqlite works
Sq lite
Sqlite3 command reference
IR SQLite Session #1
Sq lite module5
Android Level 2
Os Owens
Waiting too long for Excel's VLOOKUP? Use SQLite for simple data analysis!
Data Handning with Sqlite for Android
2011 06-sq lite-forensics
Introduction to sq lite
Databases for Beginners SQLite
Geek Austin PHP Class - Session 4
SQLiteWrittenExplanation
MySql slides (ppt)
Python SQLite3...
IR SQLite Session #3

Recently uploaded (20)

PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
KodekX | Application Modernization Development
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
cuic standard and advanced reporting.pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPT
Teaching material agriculture food technology
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
Big Data Technologies - Introduction.pptx
PDF
Encapsulation theory and applications.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
Programs and apps: productivity, graphics, security and other tools
PPTX
Spectroscopy.pptx food analysis technology
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
KodekX | Application Modernization Development
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Encapsulation_ Review paper, used for researhc scholars
The Rise and Fall of 3GPP – Time for a Sabbatical?
Agricultural_Statistics_at_a_Glance_2022_0.pdf
cuic standard and advanced reporting.pdf
NewMind AI Weekly Chronicles - August'25 Week I
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Chapter 3 Spatial Domain Image Processing.pdf
Teaching material agriculture food technology
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Big Data Technologies - Introduction.pptx
Encapsulation theory and applications.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
Dropbox Q2 2025 Financial Results & Investor Presentation
Programs and apps: productivity, graphics, security and other tools
Spectroscopy.pptx food analysis technology
sap open course for s4hana steps from ECC to s4
Mobile App Security Testing_ A Comprehensive Guide.pdf

Introduction4 SQLite

  • 1. Introduction 4 SQLite Stanley Huang wenline1001@gmail.com 1/20
  • 2. Agenda How to install SQLite on Ubuntu SQLite client samples SQLite performance tuning and optimization tips FAQ Reference Q&A 2/20
  • 3. How to install SQLite on Ubuntu Use apt-get stanley@Stanley-Ubuntu:/etc$ sudo apt-get -y install sqlite3 Reading package lists... Done Building dependency tree Reading state information... Done Suggested packages: sqlite3-doc The following NEW packages will be installed: sqlite3 0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded. Need to get 28.3kB of archives. After this operation, 119kB of additional disk space will be used. Get:1 http://us.archive.ubuntu.com/ubuntu/ lucid/main sqlite3 3.6.22-1 [28.3kB] Fetched 28.3kB in 1s (21.6kB/s) Selecting previously deselected package sqlite3. (Reading database ... 455043 files and directories currently installed.) Unpacking sqlite3 (from .../sqlite3_3.6.22-1_amd64.deb) ... Processing triggers for man-db ... Setting up sqlite3 (3.6.22-1) ... stanley@Stanley-Ubuntu:/etc$ 3/20
  • 4. SQLite client samples $ which sqlite3 /usr/bin/sqlite3 $ sqlite3 sqlite> 4/20
  • 5. .help sqlite> .help .backup ?DB? FILE Backup DB (default "main") to FILE .bail ON|OFF Stop after hitting an error. Default OFF .databases List names and files of attached databases .dump ?TABLE? ... Dump the database in an SQL text format If TABLE specified, only dump tables matching LIKE pattern TABLE. .echo ON|OFF Turn command echo on or off .exit Exit this program .explain ?ON|OFF? Turn output mode suitable for EXPLAIN on or off. With no args, it turns EXPLAIN on. .genfkey ?OPTIONS? Options are: --no-drop: Do not drop old fkey triggers. --ignore-errors: Ignore tables with fkey errors --exec: Execute generated SQL immediately See file tool/genfkey.README in the source distribution for further information. 5/20
  • 6. .help (cont.) .import FILE TABLE Import data from FILE into TABLE .indices ?TABLE? Show names of all indices If TABLE specified, only show indices for tables matching LIKE pattern TABLE. .load FILE ?ENTRY? Load an extension library .mode MODE ?TABLE? Set output mode where MODE is one of: csv Comma-separated values column Left-aligned columns. (See .width) html HTML <table> code insert SQL insert statements for TABLE line One value per line list Values delimited by .separator string tabs Tab-separated values tcl TCL list elements 6/20
  • 7. .help (cont.) .output FILENAME Send output to FILENAME .prompt MAIN CONTINUE Replace the standard prompts .quit Exit this program .read FILENAME Execute SQL in FILENAME .restore ?DB? FILE Restore content of DB (default "main") from FILE .schema ?TABLE? Show the CREATE statements If TABLE specified, only show tables matching LIKE pattern TABLE. .show Show the current values for various settings .tables ?TABLE? List names of tables If TABLE specified, only list tables matching LIKE pattern TABLE. 7/20
  • 8. Create Databases $ sqlite3 sqlite> attach database '/tmp/db1' as db1; sqlite> attach database '/tmp/db2' as db2; sqlite> .database seq name file --- --------------- ---------------------------------------------------------- 0 main 2 db1 /tmp/db1 3 db2 /tmp/db2 8/20
  • 9. Create Tables sqlite> create table db1.t11 (id int); sqlite> create table db1.t12 (id int); sqlite> create table db2.t21 (id int); sqlite> create table db2.t22 (id int); 9/20
  • 10. Insert Data sqlite> insert into db1.t11 values (11); sqlite> insert into db1.t12 values (12); sqlite> insert into db2.t21 values (21); sqlite> insert into db2.t22 values (22); 10/20
  • 11. Show Tables/Schema sqlite> .restore db1 sqlite> .tables t11 t12 sqlite> .restore db2 sqlite> .tables t21 t22 sqlite> .schema t21 CREATE TABLE t11(id int); 11/20
  • 12. SQLite performance tuning and optimization tips Back it up or lose it! File base, easy to backup by cp command. Always add an anonymous primary key! PRAGMA cache_size = ? Prior SQLite 2.8.6 split into a BTREE with default “1K” size pages, after 2.8.6 default cache size is “2K”. PRAGMA temp_store = 1 The choices are DEFAULT (0), FILE (1) and MEMORY (2). PRAGMA synchronous = OFF Default SQLite would wait data write to file, when set synchronous “OFF” and process crash, the data file might be corrupt. PRAGMA journal_mode = MEMORY Transaction would be fast, but if process crash, data file might be corrupt. USE TRANSACTION 12/20
  • 13. SQLite performance tuning and optimization tips (Cont.) Create proper index. Proper column of indexes. Proper number of indexes. Compare with “create index then insert data” and “insert data then create index” With mass of data, “insert data then create index” would be faster. Simplify the database schema Don't generalize the database schema Use temporary tables for intermediate result Avoid using view and sub-queries Ordering the tables correctly in where clause 13/20
  • 14. SQLite performance tuning and optimization tips (Cont.) Optimizing queries Use EXPLAIN command Temporary tables Order subqueries and smaller results returned first Use LIMIT and OFFSET Replace GLOB and LIKE when possible USE IN instead of OR 14/20
  • 15. SQLite performance tuning and optimization tips (Cont.) Reduce data file size Compact database Recompiling SQLite with different page size Compress large data 15/20
  • 16. FAQ What datatype does SQLite support? SQLite uses dynamic typing. Content could be INTEGER, REAL, TEXT, BOLB or NULL SQLite let me insert a string into a integer column. SQLite uses dynamic typing. Is SQLite threadsafe? SQLite is threadsafe. Prior to 3.3.1, SQLite could only used in the same thread. What's the maximum size for varchar? SQLite does not enforce the length of a VARCHAR. 16/20
  • 17. FAQ (cont.) Does SQLite support BOLB? SQLite 3.0 and later supported. How to delete columns from existing table? Alter table only support “add column” and “rename table”. Else, you need to re-create table. Does SQLite support foreign key? As of verson 3.6.19, SQLite supports foreign key constraint. I deleted lots of data but data file didn't get smaller. You need to run “VACUUM” command to shrink it. In SQLite 3.1, you could use auto_vacuum pragma to shrink it automatically. But not recommanded, because it take a long time to do it. 17/20
  • 18. Reference SQLite Document http://sqlite.org/docs.html Pragma of SQLite http://www.sqlite.org/pragma.html Limits of SQLite http://www.sqlite.org/limits.html 18/20
  • 19. Q&A 19/20
  • 20. Thanks 20/20