SQLITE
SQLITE
SQLITE TUTORIAL
Simply Easy Learning by tutorialspoint.com
tutorialspoint.com
i
ABOUT THE TUTORIAL
SQLite Tutorial
SQLite is a software library that implements a self-contained, serverless, zero-configuration,
transactional SQL database engine. SQLite is the most widely deployed SQL database engine in the
world. The source code for SQLite is in the public domain.
This tutorial will give you quick start with SQLite and make you comfortable with SQLite programming.
Audience
This reference has been prepared for the beginners to help them understand the basic to advanced
concepts related to SQLite Database Engine.
Prerequisites
Before you start doing practice with various types of examples given in this reference, I'm making an
assumption that you are already aware about what is database, especially RDBMS and what is a
computer programming language.
This tutorial may contain inaccuracies or errors and tutorialspoint provides no guarantee regarding the
accuracy of the site or its contents including this tutorial. If you discover that the tutorialspoint.com site
or this tutorial content contains some errors, please contact us at webmaster@tutorialspoint.com
TUTORIALS POINT
Simply Easy Learning
Table of Content
SQLite Tutorial...............................................................2
Audience........................................................................2
Prerequisites..................................................................2
Copyright & Disclaimer Notice.......................................2
SQLite Overview...........................................................12
What is SQLite?...........................................................................12
Why SQLite?................................................................................12
History.........................................................................................13
SQLite Limitations.......................................................................13
SQLite Commands:......................................................................13
DDL - Data Definition Language..................................................13
DML - Data Manipulation Language............................................13
DQL - Data Query Language.......................................................14
SQLite Installation........................................................15
Install SQLite On Windows..........................................................15
Install SQLite On Linux................................................................15
Install SQLite On Mac OS X.........................................................16
SQLite Commands........................................................17
Formatting output.......................................................................19
The sqlite_master Table..............................................................19
SQLite Syntax..............................................................20
Case Sensitivity...........................................................................20
Comments...................................................................................20
SQLite Statements......................................................................20
SQLite ANALYZE Statement:.......................................................20
SQLite AND/OR Clause................................................................21
SQLite ALTER TABLE Statement..................................................21
SQLite ALTER TABLE Statement (Rename):................................21
SQLite ATTACH DATABASE Statement:.......................................21
SQLite BEGIN TRANSACTION Statement:....................................21
SQLite BETWEEN Clause.............................................................21
SQLite COMMIT Statement:.........................................................21
SQLite CREATE INDEX Statement:...............................................21
SQLite CREATE UNIQUE INDEX Statement:.................................21
SQLite CREATE TABLE Statement:..............................................22
SQLite CREATE TRIGGER Statement...........................................22
TUTORIALS POINT
Simply Easy Learning
SQLite CREATE VIEW Statement.................................................22
SQLite CREATE VIRTUAL TABLE Statement.................................22
SQLite COMMIT TRANSACTION Statement..................................22
SQLite COUNT Clause..................................................................22
SQLite DELETE Statement:..........................................................22
SQLite DETACH DATABASE Statement:.......................................23
SQLite DISTINCT Clause..............................................................23
SQLite DROP INDEX Statement...................................................23
SQLite DROP TABLE Statement:..................................................23
SQLite DROP VIEW Statement.....................................................23
SQLite DROP TRIGGER Statement...............................................23
SQLite EXISTS Clause..................................................................23
SQLite EXPLAIN Statement..........................................................23
SQLite GLOB Clause....................................................................23
SQLite GROUP BY Clause.............................................................23
SQLite HAVING Clause................................................................24
SQLite INSERT INTO Statement:..................................................24
SQLite IN Clause..........................................................................24
SQLite Like Clause.......................................................................24
SQLite NOT IN Clause..................................................................24
SQLite ORDER BY Clause.............................................................24
SQLite PRAGMA Statement:........................................................24
SQLite RELEASE SAVEPOINT Statement:.....................................25
SQLite REINDEX Statement:........................................................25
SQLite ROLLBACK Statement:.....................................................25
SQLite SAVEPOINT Statement:....................................................25
SQLite SELECT Statement:..........................................................25
SQLite UPDATE Statement:.........................................................25
SQLite VACUUM Statement:........................................................25
SQLite WHERE Clause.................................................................25
SQLite Data Type.........................................................26
SQLite Storage Classes:..............................................................26
SQLite Affinity Type.....................................................................26
SQLite Affinity and Type Names:.................................................27
Boolean Datatype.......................................................................28
Date and Time Datatype.............................................................28
SQLite Create Database...............................................29
Syntax.........................................................................................29
TUTORIALS POINT
Simply Easy Learning
Example:.....................................................................................29
The .dump Command..................................................................30
SQLite Attach Database...............................................31
Syntax.........................................................................................31
Example:.....................................................................................31
SQLite Detach Database..............................................32
Syntax.........................................................................................32
Example:.....................................................................................32
SQLite Create Table.....................................................33
Syntax.........................................................................................33
Example:.....................................................................................33
SQLite Drop Table........................................................35
Syntax.........................................................................................35
Example:.....................................................................................35
SQLite Insert Query......................................................36
Syntax.........................................................................................36
Example:.....................................................................................36
Populate one table using another table:.....................................37
SQLite Select Query.....................................................38
Syntax.........................................................................................38
Example:.....................................................................................38
Setting output column width.......................................................39
Schema Information....................................................................39
SQLite Operators..........................................................41
SQLite Arithmetic Operators:......................................................41
Example......................................................................................42
SQLite Comparison Operators:....................................................42
Example......................................................................................43
SQLite Logical Operators:............................................................44
Example......................................................................................44
SQLite Bitwise Operators:...........................................................46
Example......................................................................................47
SQLite Expressions.......................................................49
Syntax.........................................................................................49
SQLite - Boolean Expressions:.....................................................49
SQLite - Numeric Expression.......................................................50
SQLite - Date Expressions:..........................................................50
SQLite Where Clause...................................................51
TUTORIALS POINT
Simply Easy Learning
Syntax.........................................................................................51
Example:.....................................................................................51
SQLite AND and OR Operator.......................................54
The AND Operator:......................................................................54
Syntax.........................................................................................54
Example:.....................................................................................54
The OR Operator:........................................................................55
Syntax.........................................................................................55
Example:.....................................................................................55
SQLite Update Query...................................................56
Syntax.........................................................................................56
Example:.....................................................................................56
SQLite Delete Query....................................................58
Syntax.........................................................................................58
Example:.....................................................................................58
SQLite Like Clause.......................................................60
Syntax.........................................................................................60
Example:.....................................................................................61
SQLite Glob Clause.......................................................63
Syntax.........................................................................................63
Example:.....................................................................................64
SQLite LIMIT Clause.....................................................66
Syntax.........................................................................................66
Example:.....................................................................................66
SQLite Order By Clause................................................68
Syntax.........................................................................................68
Example:.....................................................................................68
SQLite Group By Clause...............................................70
Syntax.........................................................................................70
Example:.....................................................................................70
SQLite Having Clause...................................................73
Syntax.........................................................................................73
Example:.....................................................................................73
SQLite Distinct Keyword...............................................75
Syntax.........................................................................................75
Example:.....................................................................................75
SQLite PRAGMA............................................................77
Syntax.........................................................................................77
auto_vacuum Pragma..................................................................77
TUTORIALS POINT
Simply Easy Learning
cache_size Pragma......................................................................78
case_sensitive_like Pragma.........................................................78
count_changes Pragma...............................................................78
database_list Pragma..................................................................78
encoding Pragma........................................................................78
freelist_count Pragma.................................................................78
index_info Pragma......................................................................79
index_list Pragma........................................................................79
journal_mode Pragma.................................................................79
max_page_count Pragma............................................................79
page_count Pragma....................................................................80
page_size Pragma.......................................................................80
parser_trace Pragma...................................................................80
recursive_triggers Pragma..........................................................80
schema_version Pragma.............................................................80
secure_delete Pragma.................................................................80
sql_trace Pragma........................................................................81
synchronous Pragma...................................................................81
temp_store Pragma.....................................................................81
temp_store_directory Pragma.....................................................81
user_version Pragma...................................................................82
writable_schema Pragma............................................................82
SQLite Constraints.......................................................83
NOT NULL Constraint...................................................................83
EXAMPLE.....................................................................................83
DEFAULT Constraint....................................................................83
EXAMPLE.....................................................................................84
UNIQUE Constraint......................................................................84
EXAMPLE.....................................................................................84
PRIMARY KEY Constraint..............................................................84
EXAMPLE.....................................................................................84
CHECK Constraint........................................................................85
EXAMPLE.....................................................................................85
Dropping Constraints:.................................................................85
SQLite Joins..................................................................86
The CROSS JOIN..........................................................................87
The INNER JOIN...........................................................................87
The OUTER JOIN..........................................................................88
TUTORIALS POINT
Simply Easy Learning
SQLite UNIONS Clause.................................................90
Syntax.........................................................................................90
Example:.....................................................................................90
COMPANY TABLE.........................................................................90
The UNION ALL Clause................................................................92
Syntax.........................................................................................92
Example:.....................................................................................93
SQLite NULL Values......................................................94
Syntax.........................................................................................94
Example:.....................................................................................94
SQLite ALIAS Syntax....................................................96
Syntax.........................................................................................96
Example:.....................................................................................96
SQLite Triggers............................................................98
Syntax.........................................................................................98
Example......................................................................................99
Listing TRIGGERS......................................................................100
Dropping TRIGGERS..................................................................100
SQLite Indexes...........................................................101
The CREATE INDEX Command..................................................101
Single-Column Indexes:.............................................................101
Unique Indexes:........................................................................101
Composite Indexes:...................................................................102
Implicit Indexes:........................................................................102
Example....................................................................................102
The DROP INDEX Command......................................................102
When should indexes be avoided?............................................103
SQLite Indexed By......................................................104
Syntax.......................................................................................104
Example....................................................................................104
SQLite Alter Command...............................................106
Syntax.......................................................................................106
Example:...................................................................................106
SQLite Truncate Table................................................108
Syntax.......................................................................................108
Example:...................................................................................108
SQLite Views..............................................................109
Creating Views:.........................................................................109
TUTORIALS POINT
Simply Easy Learning
Example:...................................................................................109
Dropping Views:........................................................................110
SQLite TRANSACTIONS...............................................111
Properties of Transactions:........................................................111
Transaction Control:..................................................................111
The BEGIN TRANSACTION Command........................................112
The COMMIT Command.............................................................112
The ROLLBACK Command.........................................................112
Example:...................................................................................112
SQLite Sub Queries....................................................114
Subqueries with the SELECT Statement:...................................114
Example:...................................................................................115
Subqueries with the INSERT Statement:...................................115
Example:...................................................................................115
Subqueries with the UPDATE Statement:..................................116
Example:...................................................................................116
Subqueries with the DELETE Statement:...................................116
Example:...................................................................................116
SQLite AUTOINCREMENT............................................118
Syntax.......................................................................................118
Example:...................................................................................118
SQLite Injection..........................................................120
Preventing SQL Injection...........................................................120
SQLite Explain............................................................122
Syntax.......................................................................................122
Example:...................................................................................122
SQLite Vacuum..........................................................125
Manual VACUUM........................................................................125
Auto-VACCUM............................................................................125
SQLite Date & Time....................................................127
Time Strings:.............................................................................127
Modifiers....................................................................................128
Formatters:................................................................................128
Examples...................................................................................129
SQLite Useful Functions.............................................131
SQLite COUNT Function.............................................................132
SQLite MAX Function.................................................................132
SQLite MIN Function..................................................................132
SQLite AVG Function.................................................................132
TUTORIALS POINT
Simply Easy Learning
SQLite SUM Function.................................................................133
SQLite RANDOM Function..........................................................133
SQLite ABS Function..................................................................133
SQLite UPPER Function..............................................................133
SQLite LOWER Function............................................................134
SQLite LENGTH Function...........................................................134
SQLite sqlite_version Function..................................................134
SQLite C/C++ Tutorial................................................135
C/C++ Interface APIs................................................................135
Connecting To Database...........................................................136
Create a Table...........................................................................136
INSERT Operation......................................................................137
SELECT Operation.....................................................................138
UPDATE Operation.....................................................................140
DELETE Operation.....................................................................141
SQLite Java Tutorial....................................................144
Connecting To Database...........................................................144
Create a Table...........................................................................145
INSERT Operation......................................................................145
SELECT Operation.....................................................................146
UPDATE Operation.....................................................................148
DELETE Operation.....................................................................149
SQLite PHP Tutorial....................................................151
PHP Interface APIs.....................................................................151
Connecting To Database...........................................................152
Create a Table...........................................................................152
INSERT Operation......................................................................153
SELECT Operation.....................................................................154
UPDATE Operation.....................................................................155
DELETE Operation.....................................................................156
SQLite Perl Tutorial....................................................158
DBI Interface APIs......................................................................158
Connecting To Database...........................................................159
Create a Table...........................................................................160
INSERT Operation......................................................................161
SELECT Operation.....................................................................161
UPDATE Operation.....................................................................162
DELETE Operation.....................................................................164
TUTORIALS POINT
Simply Easy Learning
SQLite Python............................................................165
Python sqlite3 module APIs.......................................................165
Connecting To Database...........................................................167
Create a Table...........................................................................167
INSERT Operation......................................................................168
SELECT Operation.....................................................................168
UPDATE Operation.....................................................................169
DELETE Operation.....................................................................170
TUTORIALS POINT
Simply Easy Learning
1
CHAPTER
SQLite Overview
T this tutorial helps you to understand what is SQLite , how it differs from SQL, why it is
What is SQLite?
SQLite is an in-process library that implements a self-contained, serverless, zero-configuration,
transactional SQL database engine. It is the one database, which is zero-configured, that means like
other database you do not need to configure it in your system.
SQLite engine is not a standalone process like other databases, you can link it statically or
dynamically as per your requirement with your application. The SQLite accesses its storage files
directly.
Wh┞ SQLite?
SQLite does not require a separate server process or system to operate (serverless).
SQLite is very small and light weight, less than 400KiB fully configured or less than 250KiB
with optional features omitted.
SQLite transactions are fully ACID-compliant, allowing safe access from multiple processes or threads.
SQLite supports most of the query language features found in the SQL92 (SQL2) standard.
SQLite is available on UNIX (Linux, Mac OS-X, Android, iOS) and Windows (Win32, WinCE, WinRT).
TUTORIALS POINT
Simply Easy Learning
Histor┞:
1. 2000 -- D. Richard Hipp had designed SQLite for the purpose of no administration required for
operating a program.
3. 2011 -- Hipp announced to add UNQl interface to SQLite DB and to develop UNQLite (Document
oriented database).
SQLite Li マ itatio ミ s:
There are few unsupported features of SQL92 in SQLite which are shown below:
Feature Description
RIGHT OUTER
Only LEFT OUTER JOIN is implemented.
JOIN
FULL OUTER
Only LEFT OUTER JOIN is implemented.
JOIN
The RENAME TABLE and ADD COLUMN variants of the ALTER TABLE command are
ALTER TABLE
supported. The DROP COLUMN, ALTER COLUMN, ADD CONSTRAINT not supported.
Trigger support FOR EACH ROW triggers are supported but not FOR EACH STATEMENT triggers.
VIEWs in SQLite are read-only. You may not execute a DELETE, INSERT, or UPDATE
VIEWs
statement on a view.
GRANT and The only access permissions that can be applied are the normal file access permissions
REVOKE of the underlying operating system.
SQLite Co ママ a ミ ds:
The standard SQLite commands to interact with relational databases are similar as SQL. They are
CREATE, SELECT, INSERT, UPDATE, DELETE and DROP. These commands can be classified into
groups based on their operational nature:
DROP Deletes an entire table, a view of a table or other object in the database.
TUTORIALS POINT
Simply Easy Learning
DQL - Data Quer┞ La ミ guage:
Command Description
TUTORIALS POINT
Simply Easy Learning
2
CHAPTER
SQLite Installation
T he SQLite is famous for its great feature zero-configuration, which means no complex setup
or administration is needed. This chapter will take you through the process of setting up SQLite on
Windows, Linux and Mac OS X.
C:\>sqlite3
SQLite version 3.7.15.2 2013-01-09 11:53:05
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite>
I ミ stall SQLite O ミ Li ミ u┝
Today, almost all the flavours of Linux OS are being shipped with SQLite. So you just issue
the following command to check if you already have SQLite installed on your machine or not.
$sqlite3
SQLite version 3.7.15.2 2013-01-09 11:53:05
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite>
If you do not see above result, then it means you do not have SQLite installed on your Linux
machine. So let's follow the following steps to install SQLite:
Go to SQLite download page and download sqlite-autoconf-*.tar.gz from source code section.
TUTORIALS POINT
Simply Easy Learning
$tar xvfz sqlite-autoconf-3071502.tar.gz
$cd sqlite-autoconf-3071502
$./configure --prefix=/usr/local
$make
$make install
Above procedure will end with SQLite installation on your Linux machine which you can verify as
explained above.
Above procedure will end with SQLite installation on your Mac OS X machine which you can verify
by issuing following command:
$sqlite3
SQLite version 3.7.15.2 2013-01-09 11:53:05
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite>
Finally, you have SQLite command prompt where you can issue SQLite commands to do your excercises.
TUTORIALS POINT
Simply Easy Learning
3
CHAPTER
SQLite Commands
T his chapter will take you through simple and useful commands used by SQLite
programmers. These commands are called SQLite dot commands and exception with these
commands is that they should not be terminated by a semi-colon (;).
Let's start with typing a simple sqlite3 command at command prompt which will provide you
SQLite command prompt where you will issue various SQLite commands.
$sqlite3
SQLite version 3.3.6
Enter ".help" for instructions
sqlite>
For a listing of the available dot commands, you can enter ".help" at any time. For example:
sqlite>.help
Above command will display a list of various important SQLite dot commands, which are as follows:
Command Description
Dump the database in an SQL text format. If TABLE specified, only dump
.dump ?TABLE?
tables matching LIKE pattern TABLE.
.explain ON|OFF Turn output mode suitable for EXPLAIN on or off. With no args, it turns
EXPLAIN on.
.header(s) ON|OFF Turn display of headers on or off
.indices ?TABLE? Show names of all indices. If TABLE specified, only show indices for tables
matching
LIKE pattern TABLE.
TUTORIALS POINT
Simply Easy Learning
.load FILE ?ENTRY? Load an extension library
.prompt
Replace the standard prompts
MAIN
CONTINUE
.quit Exit SQLite prompt
Let's try .show command to see default setting for your SQLite command prompt.
sqlite>.show
echo: off
explain: off
headers: off
mode: column
nullvalue: ""
output: stdout
separator: "|"
width:
sqlite>
TUTORIALS POINT
Simply Easy Learning
Make sure there is no space in between sqlite> prompt and dot command, otherwise it will not work.
sqlite>.header on
sqlite>.mode column
sqlite>.timer on
sqlite>
sqlite>.schema sqlite_master
TUTORIALS POINT
Simply Easy Learning
4
CHAPTER
SQLite Syntax
S QLite is followed by unique set of rules and guidelines called Syntax. This tutorial gives you a
quick start with SQLite by listing all the basic SQLite Syntax.
Case Se ミ siti┗it┞
Important point to be noted is that SQLite is case insensitive, but there are some commands, which
are case sensitive like GLOB and glob have different meaning in SQLite statements.
Co ママ e ミ ts
SQLite comments are extra notes, which you can add in your SQLite code to increase its readability
and they can appear anywhere; whitespace can occur, including inside expressions and in the
middle of other SQL statements but they can not be nested.
SQL comments begin with two consecutive "-" characters (ASCII 0x2d) and extend up to and
including the next newline character (ASCII 0x0a) or until the end of input, whichever comes first.
You can also use C-style comments, which begin with "/*" and extend up to and including the next
"*/" character pair or until the end of input, whichever comes first. C-style comments can span
multiple lines.
SQLite State マ e ミ ts
All the SQLite statements start with any of the keywords like SELECT, INSERT, UPDATE, DELETE,
ALTER, DROP, etc., and all the statements end with a semicolon (;).
TUTORIALS POINT
Simply Easy Learning
SQLite AND/OR Clause:
SELECT column1, column2..........columnN
FROM table_name
WHERE CONDITION-1 {AND|OR} CONDITION-2;
TUTORIALS POINT
Simply Easy Learning
SQLite CREATE TABLE State マ e ミ t:
CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);
TUTORIALS POINT
Simply Easy Learning
SQLite DETACH DATABASE State マ e ミ t:
DETACH DATABASE 'Alias-Name';
TUTORIALS POINT
Simply Easy Learning
FROM table_name
WHERE CONDITION
GROUP BY column_name;
SQLite IN Clause:
SELECT column1, column2..........columnN
FROM table_name
WHERE column_name IN (val-1, val-2,.......val-N);
For example:
PRAGMA page_size;
PRAGMA cache_size = 1024;
PRAGMA table_info(table_name);
TUTORIALS POINT
Simply Easy Learning
SQLite RELEASE SAVEPOINT State マ e ミ t:
RELEASE savepoint_name;
TUTORIALS POINT
Simply Easy Learning
5
CHAPTER
S QLite data type is an attribute that specifies type of data of any object. Each column,
You would use these data types while creating your tables. SQLite uses a more general dynamic
type system. In SQLite, the datatype of a value is associated with the value itself, not with its
container.
REAL The value is a floating point value, stored as an 8-byte IEEE floating point
number.
The value is a text string, stored using the database encoding (UTF-8,
TEXT
UTF-16BE or UTF-16LE)
SQLite storage class is slightly more general than a datatype. The INTEGER storage class, for
example, includes 6 different integer datatypes of different lengths.
Affinity Description
TEXT This column stores all data using storage classes NULL, TEXT or BLOB.
NUMERIC This column may contain values using all five storage classes.
INTEGER Behaves the same as a column with NUMERIC affinity with an exception in a
CAST
TUTORIALS POINT
Simply Easy Learning
expression.
Behaves like a column with NUMERIC affinity except that it forces integer
REAL
values into floating point representation
A column with affinity NONE does not prefer one storage class over another
NONE
and no attempt is made to coerce data from one storage class into another.
INT
INTEGER
TINYINT
SMALLINT
MEDIUMINT INTEGER
BIGINT
INT2
INT8
CHARACTER(20)
VARCHAR(255)
VARYING
CHARACTER(255)
TEXT
NCHAR(55)
NATIVE
CHARACTER(70)
NVARCHAR(100)
TEXT
CLOB
TUTORIALS POINT
Simply Easy Learning
BLOB
NONE
no datatype specified
REAL
DOUBLE
REAL
DOUBLE PRECISION
FLOAT
NUMERIC
DECIMAL(10,5
) BOOLEAN NUMERIC
DATE
DATETIME
Boolea ミ Datat┞pe:
SQLite does not have a separate Boolean storage class. Instead, Boolean values are stored as
integers 0 (false) and 1 (true).
Date a ミ d Ti マ e Datat┞pe:
SQLite does not have a separate storage class for storing dates and/or times, but SQLite is
capable of storing dates and times as TEXT, REAL or INTEGER values.
REAL The number of days since noon in Greenwich on November 24, 4714
B.C.
INTEGER The number of seconds since 1970-01-01 00:00:00 UTC.
TUTORIALS POINT
Simply Easy Learning
6
CHAPTER
T he SQLite sqlite3 command is used to create new SQLite database. You do not need to
S┞ミ ta┝:
Basic syntax of sqlite3 command is as follows:
$sqlite3 DatabaseName.db
E┝a マ ple:
If you want to create new database <testDB.db>, then SQLite3 statement would be as follows:
$sqlite3 testDB.db
SQLite version 3.7.15.2 2013-01-09 11:53:05
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite>
Above command will create a file testDB.db in the current directory. This file will be used as
database by SQLite engine. If you have noticed while creating database, sqlite3 command will
provide a sqlite>prompt after creating database file successfully.
Once a database is created, you can check it in the list of databases using SQLite .databases
command as follows:
sqlite>.databases
seq name file
0 main /home/sqlite/testDB.db
You will use SQLite .quit command to come out of the sqlite prompt as follows:
sqlite>.quit
$
TUTORIALS POINT
Simply Easy Learning
The .du マ p Co ママ a ミ d
You can use .dump dot command to export complete database in a text file using SQLite command
at command prompt as follows:
Above command will convert the entire contents of testDB.db database into SQLite statements and
dump it into ASCII text file testDB.sql. You can do restoration from the generated testDB.sql in
simple way as follows:
At this moment your database is empty, so you can try above two procedures once you have few
tables and data in your database. For now, let's proceed to next chapter.
TUTORIALS POINT
Simply Easy Learning
7
CHAPTER
C onsider a case when you have multiple databases available and you want to use any one of
them at a time. SQLite ATTACH DTABASE statement is used to select a particular database, and
after this command, all SQLite statements will be executed under the attached database.
S┞ミ ta┝:
Basic syntax of SQLite ATTACH DATABASE statement is as follows:
Above command will also create a database in case database is already not created, otherwise it
will just attach database file name with logical database 'Alias-Name'.
E┝a マ ple:
If you want to attach an existing database testDB.db, then ATTACH DATABASE statement would be as
follows:
sqlite> .database
seq name file
0 main /home/sqlite/testDB.db
2 test /home/sqlite/testDB.db
The database names main and temp are reserved for the primary database and database to hold
temporary tables and other temporary data objects. Both of these database names exist for every
database connection and should not be used for attachment, otherwise you will get a warning
message something as follows:
TUTORIALS POINT
Simply Easy Learning
8
CHAPTER
S QLite DETACH DTABASE statement is used to detach and dissociate a named database from
a database connection which was previously attached using ATTACH statement. If the same
database file has been attached with multiple aliases, then DETACH command will disconnect only
given name and rest of the attachement will still continue. You cannot detach the main or temp
databases.
If the database is an in-memory or temporary database, the database will be destroyed and the
contents will be lost.
S┞ミ ta┝:
Basic syntax of SQLite DETACH DATABASE 'Alias-Name' statement is as follows:
Here 'Alias-Name' is the same alias, which you had used while attaching database using ATTACH statement.
E┝a マ ple:
Consider you have a database, which you created in previous chapter and attached it with 'test'
and 'currentDB' as we can see using .database command:
sqlite>.databases
seq name file
0 main /home/sqlite/testDB.db
2 test /home/sqlite/testDB.db
3 currentDB /home/sqlite/testDB.db
Now, if you will check current attachment, you will find that testDB.db is still connected with 'test' and 'main'.
sqlite>.databases
seq name file
0 main /home/sqlite/testDB.db
2 test /home/sqlite/testDB.db
TUTORIALS POINT
Simply Easy Learning
9
CHAPTER
T he SQLite CREATE TABLE statement is used to create a new table in any of the given
database. Creating a basic table involves naming the table and defining its columns and each
column's data type.
S┞ミ ta┝:
Basic syntax of CREATE TABLE statement is as follows:
CREATE TABLE is the keyword telling the database system to create a new table. The unique name
or identifier for the table follows the CREATE TABLE statement. Optionally you can specify
database_name along with table_name.
E┝a マ ple:
Following is an example, which creates a COMPANY table with ID as primary key and NOT NULL are
the constraints showing that these fields can not be NULL while creating records in this table:
Let us create one more table, which we will use in our exercises in subsequent chapters:
TUTORIALS POINT
Simply Easy Learning
You can verify if your table has been created successfully using SQLIte command .tables
command, which will be used to list down all the tables in an attached database.
sqlite>.tables
COMPANY DEPARTMENT
Here, you can see COMPANY table twice because it's showing COMPANY table for main database
and test.COMPANY table for 'test' alias created for your testDB.db. You can get complete
information about a table using SQLite .schema command as follows:
sqlite>.schema COMPANY
CREATE TABLE COMPANY(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL
);
TUTORIALS POINT
Simply Easy Learning
CHAPTER
10
SQLite Drop Table
T he SQLite DROP TABLE statement is used to remove a table definition and all associated
data, indexes, triggers, constraints and permission specifications for that table.
You have to be careful while using this command because once a table is deleted then all the
information available in the table would also be lost forever.
S┞ミ ta┝:
Basic syntax of DROP TABLE statement is as follows. You can optionally specify database name
along with table name as follows:
E┝a マ ple:
Let us first verify COMPANY table and then we would delete it from the database.
sqlite>.tables
COMPANY test.COMPANY
This means COMPANY table is available in the database, so let us drop it as follows:
Now, if you would try .TABLES command, then you will not find COMPANY table anymore:
sqlite>.tables
sqlite>
It shows nothing means the table from your database has been dropped successfully.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
11
SQLite Insert Query
T he SQLite INSERT INTO Statement is used to add new rows of data into a table in the database.
S┞ミ ta┝:
There are two basic syntaxes of INSERT INTO statement as follows:
Here, column1, column2,...columnN are the names of the columns in the table into which you want to insert
data.
You may not need to specify the column(s) name in the SQLite query if you are adding values for all
the columns of the table. But make sure the order of the values is in the same order as the columns
in the table. The SQLite INSERT INTO syntax would be as follows:
E┝a マ ple:
Consider you already have created COMPANY table in your testDB.db as follows:
TUTORIALS POINT
Simply Easy Learning
INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );
All the above statements would create following records in COMPANY table. Next chapter will teach
you how to display all these records from a table.
For now, you can skip above statement, first let's learn SELECT and WHERE clauses, which will be
covered in subsequent chapters.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
12
SQLite Select Query
S QLite SELECT statement is used to fetch the data from a SQLite database table which
returns data in the form of result table. These result tables are also called result-sets.
S┞ミ ta┝:
The basic syntax of SQLite SELECT statement is as follows:
Here, column1, column2...are the fields of a table, whose values you want to fetch. If you want
to fetch all the fields available in the field, then you can use the following syntax:
E┝a マ ple:
Consider COMPANY table is having following records:
Following is an example to fetch and display all these records using SELECT statement. Here,
first three commands have been used to set properly formatted output.
sqlite>.header on
sqlite>.mode column
sqlite> SELECT * FROM COMPANY;
TUTORIALS POINT
Simply Easy Learning
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
If you want to fetch only selected fields of COMPANY table, then use the following query:
ID NAME SALARY
1 Paul 20000.0
2 Allen 15000.0
3 Teddy 20000.0
4 Mark 65000.0
5 David 85000.0
6 Kim 45000.0
7 James 10000.0
Above .width command sets first column width to 10, second column width to 20 and third column
width to 10. So finally above SELECT statement will give the following result:
Assuming you have only COMPANY table in your testDB.db, this will produce the following result:
tbl_name
TUTORIALS POINT
Simply Easy Learning
COMPANY
You can list down complete information about COMPANY table as follows:
sqlite> SELECT sql FROM sqlite_master WHERE type = 'table' AND tbl_name =
'COMPANY';
Assuming you have only COMPANY table in your testDB.db, this will produce the following result:
TUTORIALS POINT
Simply Easy Learning
CHAPTER
13
SQLite Operators
What is an operator in SQLite?
Operators are used to specify conditions in an SQLite statement and to serve as conjunctions
for multiple conditions in a statement.
Arithmetic operators
Comparison operators
Logical operators
Bitwise operators
a + b will
+ Addition - Adds values on either side of the operator
give 30
a - b will
- Subtraction - Subtracts right hand operand from left hand operand
give -10
a * b will
* Multiplication - Multiplies values on either side of the operator
give 200
b / a will
/ Division - Divides left hand operand by right hand operand
give 2
b % a will
% Modulus - Divides left hand operand by right hand operand and returns
give 0
remainder
TUTORIALS POINT
Simply Easy Learning
E┝a マ ple
Here are simple examples showing usage of SQLite Arithmetic Operators:
sqlite> select 10 / 5;
10 / 5 = 2
sqlite> select 12 % 5;
12 % 5 = 2
(a ==
Checks if the values of two operands are equal or not, if yes then condition
== b) is
becomes true.
not
true.
Checks if the values of two operands are equal or not, if yes then condition (a = b)
=
becomes true. is not
true.
Checks if the values of two operands are equal or not, if values are not (a !=
!=
equal then condition becomes true. b) is
true.
Checks if the values of two operands are equal or not, if values are not (a <>
<>
equal then condition becomes true. b) is
true.
Checks if the value of left operand is greater than the value of right (a > b)
>
operand, if yes then condition becomes true. is not
true.
Checks if the value of left operand is less than the value of right operand, if (a < b)
<
yes then condition becomes true. is true.
(a >=
Checks if the value of left operand is greater than or equal to the value of
>= b) is
right operand, if yes then condition becomes true.
not
true.
Checks if the value of left operand is less than or equal to the value of right (a <=
<=
operand, if yes then condition becomes true. b) is
true.
TUTORIALS POINT
Simply Easy Learning
Checks if the value of left operand is not less than the value of right (a !<
!<
operand, if yes then condition becomes true. b) is
false.
!> Checks if the value of left operand is not greater than the value of right (a !> b)
operand, if yes
then condition becomes true. is true.
E┝a マ ple
Consider COMPANY table has the following records:
Below example will show the usage of various SQLite Comparison Operators.
Here, we have used WHERE clause, which will be explained in a separate chapter but for now you
can understand that WHERE clause is used to put a conditional statement along with SELECT
statement.
Following SELECT statement lists down all the records having SALARY greater than 50,000.00:
Following SELECT statement lists down all the records having SALARY equal to 20,000.00:
Following SELECT statement lists down all the records having SALARY not equal to 20,000.00:
Following SELECT statement lists down all the records having SALARY not equal to 20,000.00:
TUTORIALS POINT
Simply Easy Learning
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Following SELECT statement lists down all the records having SALARY greater than or equal to 65,000.00:
Operator Description
The AND operator allows the existence of multiple conditions in an SQL statement's
AND
WHERE clause.
The BETWEEN operator is used to search for values that are within a set of values,
BETWEEN
given the minimum value and the maximum value.
The EXISTS operator is used to search for the presence of a row in a specified table that
EXISTS
meets certain criteria.
IN The IN operator is used to compare a value to a list of literal values that have been
specified.
The negation of IN operator which is used to compare a value to a list of literal values
NOT IN
that have been specified.
LIKE The LIKE operator is used to compare a value to similar values using wildcard operators.
The GLOB operator is used to compare a value to similar values using wildcard
GLOB
operators. Also, GLOB is case sensitive, unlike LIKE.
The NOT operator reverses the meaning of the logical operator with which it is used. Eg.
NOT
NOT EXISTS, NOT BETWEEN, NOT IN, etc. This is negate operator.
UNIQUE The UNIQUE operator searches every row of a specified table for uniqueness (no
duplicates).
E┝a マ ple
Consider COMPANY table has the following records:
TUTORIALS POINT
Simply Easy Learning
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Here are simple examples showing usage of SQLite Logical Operators. Following SELECT statement
lists down all the records where AGE is greater than or equal to 25 and salary is greater than or
equal to 65000.00:
sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 AND SALARY >= 65000;
Following SELECT statement lists down all the records where AGE is greater than or equal to 25
OR salary is greater than or equal to 65000.00:
sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 OR SALARY >= 65000;
ID NAME AGE ADDRESS SALARY
Following SELECT statement lists down all the records where AGE is not NULL which means all
the records because none of the record is having AGE equal to NULL:
Following SELECT statement lists down all the records where NAME starts with 'Ki', does not matter
what comes after 'Ki'.
Following SELECT statement lists down all the records where NAME starts with 'Ki', does not matter
what comes after 'Ki':
Following SELECT statement lists down all the records where AGE value is either 25 or 27:
TUTORIALS POINT
Simply Easy Learning
2 Allen 25 Texas 15000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
Following SELECT statement lists down all the records where AGE value is neither 25 nor 27:
Following SELECT statement lists down all the records where AGE value is in BETWEEN 25 AND 27:
Following SELECT statement makes use of SQL sub-query where sub-query finds all the records with
AGE field having SALARY > 65000 and later WHERE clause is being used along with EXISTS operator
to list down all the records where AGE from the outside query exists in the result returned by sub-
query:
32
25
23
25
27
22
24
Following SELECT statement makes use of SQL sub-query where subquery finds all the records with
AGE field having SALARY > 65000 and later WHERE clause is being used along with > operator to
list down all the records where AGE from outside query is greater than the age in the result
returned by sub-query:
P Q p&q p|q
0 0 0 0
TUTORIALS POINT
Simply Easy Learning
0 1 0 1
1 1 1 1
1 0 0 1
Assume if A = 60; and B = 13; now in binary format, they will be as follows:
A = 0011 1100
B = 0000 1101
~A = 1100 0011
The Bitwise operators supported by SQLite language are listed in the following table. Assume
variable A holds 60 and variable B holds 13, then:
E┝a マ ple
Here are simple examples showing usage of SQLite Bitwise Operators:
TUTORIALS
sqlite> POINT
select (60 << 2);
Simply Easy Learning
TUTORIALS POINT
Simply Easy Learning
(60 << 2) = 240
TUTORIALS POINT
Simply Easy Learning
CHAPTER
14
SQLite Expressions
A n expression is a combination of one or more values, operators and SQL functions that
evaluate to a value.
SQL EXPRESSIONs are like formulas and they are written in query language. You can also use to
query the database for specific set of data.
S┞ミ ta┝:
Consider the basic syntax of the SELECT statement as follows:
There are different types of SQLite expressions, which are mentioned below:
TUTORIALS POINT
Simply Easy Learning
ID NAME AGE ADDRESS SALARY
There are several built-in functions like avg(), sum(), count(), etc., to perform what is known as
aggregate data calculations against a table or a specific table column.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
15
SQLite Where Clause
T he SQLite WHERE clause is used to specify a condition while fetching the data from one
If the given condition is satisfied, means true, then it returns specific value from the table. You
would use WHERE clause to filter the records and fetching only necessary records.
The WHERE clause not only used in SELECT statement, but it is also used in UPDATE, DELETE
statement, etc., which we would study in subsequent chapters.
S┞ミ ta┝:
The basic syntax of SQLite SELECT statement with WHERE clause is as follows:
E┝a マ ple:
You can specify a condition using Comparision or Logical Operators like >, <, =, LIKE, NOT, etc.
Consider COMPANY table has the following records:
Here are simple examples showing usage of SQLite Logical Operators. Following SELECT statement
lists down all the records where AGE is greater than or equal to 25 AND salary is greater than or
equal to 65000.00:
sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 AND SALARY >= 65000;
TUTORIALS POINT
Simply Easy Learning
5 David 27 Texas 85000.0
Following SELECT statement lists down all the records where AGE is greater than or equal to 25
OR salary is greater than or equal to 65000.00:
sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 OR SALARY >= 65000;
ID NAME AGE ADDRESS SALARY
Following SELECT statement lists down all the records where AGE is not NULL which means all
the records because none of the record is having AGE equal to NULL:
Following SELECT statement lists down all the records where NAME starts with 'Ki', does not matter
what comes after 'Ki'.
Following SELECT statement lists down all the records where NAME starts with 'Ki', does not matter
what comes after 'Ki':
Following SELECT statement lists down all the records where AGE value is either 25 or 27:
Following SELECT statement lists down all the records where AGE value is neither 25 nor 27:
TUTORIALS POINT
Simply Easy Learning
7 James 24 Houston 10000.0
Following SELECT statement lists down all the records where AGE value is in BETWEEN 25 AND 27:
Following SELECT statement makes use of SQL sub-query where sub-query finds all the records with
AGE field having SALARY > 65000 and later WHERE clause is being used along with EXISTS
operator to list down all the records where AGE from the outside query exists in the result returned
by sub-query:
32
25
23
25
27
22
24
Following SELECT statement makes use of SQL sub-query where sub-query finds all the records with
AGE field having SALARY > 65000 and later WHERE clause is being used along with > operator to
list down all the records where AGE from outside query is greater than the age in the result
returned by sub-query:
TUTORIALS POINT
Simply Easy Learning
CHAPTER
16
SQLite AND and OR Operator
T he SQLite AND and OR operators are used to combine multiple conditions to narrow down
selected data in an SQLite statement. These two operators are called conjunctive operators.
These operators provide a means to make multiple comparisons with different operators in the
same SQLite statement.
S┞ミ ta┝:
The basic syntax of AND operator with WHERE clause is as follows:
You can combine N number of conditions using AND operator. For an action to be taken by the
SQLite statement, whether it be a transaction or query, all conditions separated by the AND must
be TRUE.
E┝a マ ple:
Consider COMPANY table is having the following records:
Following SELECT statement lists down all the records where AGE is greater than or equal to 25
ANDsalary is greater than or equal to 65000.00:
sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 AND SALARY >= 65000;
TUTORIALS POINT
Simply Easy Learning
ID NAME AGE ADDRESS SALARY
The OR Operator:
The OR operator is also used to combine multiple conditions in an SQLite statement's WHERE
clause. While using OR operator, complete condition will be assumed true when at least any of the
conditions is true. For example, [condition1] OR [condition2] will be true if either condition1 or
condition2 is true.
S┞ミ ta┝:
The basic syntax of OR operator with WHERE clause is as follows:
You can combine N number of conditions using OR operator. For an action to be taken by the SQLite
statement, whether it be a transaction or query, only any ONE of the conditions separated by the
OR must be TRUE.
E┝a マ ple:
Consider COMPANY table is having the following records:
Following SELECT statement lists down all the records where AGE is greater than or equal to 25
ORsalary is greater than or equal to 65000.00:
sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 OR SALARY >= 65000;
ID NAME AGE ADDRESS SALARY
TUTORIALS POINT
Simply Easy Learning
CHAPTER
17
SQLite Update Query
T he SQLite UPDATE Query is used to modify the existing records in a table. You can use
WHERE clause with UPDATE query to update selected rows, otherwise all the rows would be
updated.
S┞ミ ta┝:
The basic syntax of UPDATE query with WHERE clause is as follows:
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
E┝a マ ple:
Consider COMPANY table is having the following records:
TUTORIALS POINT
Simply Easy Learning
6 Kim 22 Texas 45000.0
7 James 24 Houston 10000.0
If you want to modify all ADDRESS and SALARY column values in COMPANY table, you do not
need to use WHERE clause and UPDATE query would be as follows:
TUTORIALS POINT
Simply Easy Learning
CHAPTER
18
SQLite Delete Query
T he SQLite DELETE Query is used to delete the existing records from a table. You can
use WHERE clause with DELETE query to delete selected rows, otherwise all the records would be
deleted.
S┞ミ ta┝:
The basic syntax of DELETE query with WHERE clause is as follows:
E┝a マ ple:
Consider COMPANY table is having the following records:
TUTORIALS POINT
Simply Easy Learning
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
If you want to DELETE all the records from COMPANY table, you do not need to use WHERE
clause with DELETE query, which would be as follows:
Now, COMPANY table does not have any record because all the records have been deleted by
DELETE statement.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
19
SQLite Like Clause
T he SQLite LIKE operator is used to match text values against a pattern using wildcards. If
the search expression can be matched to the pattern expression, the LIKE operator will return true,
which is 1. There are two wildcards used in conjunction with the LIKE operator:
The percent sign represents zero, one, or multiple numbers or characters. The underscore
represents a single number or character. These symbols can be used in combinations.
S┞ミ ta┝:
The basic syntax of % and _ is as follows:
or
or
or
or
TUTORIALS POINT
Simply Easy Learning
E┝a マ ple:
Here are number of examples showing WHERE part having different LIKE clause with '%' and '_' operators:
Statement Description
WHERE SALARY LIKE '200%' Finds any values that start with 200
WHERE SALARY LIKE '%200%' Finds any values that have 200 in any position
WHERE SALARY LIKE '_00%' Finds any values that have 00 in the second and third positions
WHERE SALARY LIKE '2_%_%' Finds any values that start with 2 and are at least 3 characters in
length
WHERE SALARY LIKE '%2' Finds any values that end with 2
WHERE SALARY LIKE '_2%3' Finds any values that have a 2 in the second position and end with
a3
WHERE SALARY LIKE '2 3' Finds any values in a five-digit number that start with 2 and end
with 3
Let us take a real example, consider COMPANY table is having the following records:
Following is an example, which would display all the records from COMPANY table where AGE starts with 2:
Following is an example, which would display all the records from COMPANY table where ADDRESS
will have a hyphen (-) inside the text:
20
SQLite Glob Clause
T he SQLite GLOB operator is used to match only text values against a pattern using
wildcards. If the search expression can be matched to the pattern expression, the GLOB operator
will return true, which is 1. Unlike LIKE operator, GLOB is case sensitive and it follows syntax of
UNIX for specifying the following wildcards.
The asterisk sign (*)
The asterisk sign represents zero or multiple numbers or characters. The ? represents a single
number or character.
S┞ミ ta┝:
The basic syntax of * and ? is as follows:
or
or
or
or
or
TUTORIALS POINT
Simply Easy Learning
SELECT FROM table_name
WHERE column GLOB '????'
You can combine N number of conditions using AND or OR operators. Here XXXX could be any
numberic or string value.
E┝a マ ple:
Here are number of examples showing WHERE part having different LIKE clause with '*' and '?' operators:
Statement Description
WHERE SALARY GLOB '200*' Finds any values that start with 200
WHERE SALARY GLOB '*200*' Finds any values that have 200 in any position
WHERE SALARY GLOB '?00*' Finds any values that have 00 in the second and third positions
WHERE SALARY GLOB '2??' Finds any values that start with 2 and are at least 3 characters in
length
WHERE SALARY GLOB '*2' Finds any values that end with 2
WHERE SALARY GLOB '?2*3' Finds any values that have a 2 in the second position and end with
a3
WHERE SALARY GLOB '2???3' Finds any values in a five-digit number that start with 2 and end
with 3
Let us take a real example, consider COMPANY table is having the following records:
Following is an example, which would display all the records from COMPANY table where AGE starts with 2:
Following is an example, which would display all the records from COMPANY table where ADDRESS
will have a hyphen (-) inside the text:
TUTORIALS POINT
Simply Easy Learning
ID NAME AGE ADDRESS SALARY
TUTORIALS POINT
Simply Easy Learning
CHAPTER
21
SQLite LIMIT Clause
T he SQLite LIMIT clause is used to limit the data amount returned by the SELECT statement.
S┞ミ ta┝:
The basic syntax of SELECT statement with LIMIT clause is as follows:
Following is the syntax of LIMIT clause when it is used along with OFFSET clause:
SQLite engine will return rows starting from the next row to the given OFFSET as shown below
in the last example.
E┝a マ ple:
Consider COMPANY table is having the following records:
Following is an example, which limits the row in the table according to the number of rows you
want to fetch from table:
TUTORIALS POINT
Simply Easy Learning
ID NAME AGE ADDRESS SALARY
But in certain situations, you may need to pick up a set of records from a particular offset. Here is
an example, which picks up 3 records starting from 3rd position:
TUTORIALS POINT
Simply Easy Learning
CHAPTER
22
SQLite Order By Clause
T he SQLite ORDER BY clause is used to sort the data in ascending or descending order,
S┞ミ ta┝:
The basic syntax of ORDER BY clause is as follows:
SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
You can use more than one column in the ORDER BY clause. Make sure whatever column you are
using to sort, that column should be available in column-list.
E┝a マ ple:
Consider COMPANY table is having the following records:
Following is an example, which would sort the result in descending order by SALARY:
TUTORIALS POINT
Simply Easy Learning
3 Teddy 23 Norway 20000.0
6 Kim 22 South-Hall 45000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
Following is an example, which would sort the result in descending order by NAME and SALARY:
Following is an example, which would sort the result in descending order by NAME:
TUTORIALS POINT
Simply Easy Learning
CHAPTER
23
SQLite Group By Clause
T he SQLite GROUP BY clause is used in collaboration with the SELECT statement to arrange
S┞ミ ta┝:
The basic syntax of GROUP BY clause is given below. The GROUP BY clause must follow the
conditions in the WHERE clause and must precede the ORDER BY clause if one is used.
SELECT column-list
FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2..........columnN
ORDER BY column1, column2..........columnN
You can use more than one column in the GROUP BY clause. Make sure whatever column you
are using to group, that column should be available in column-list.
E┝a マ ple:
Consider COMPANY table is having the following records:
If you want to know the total amount of salary on each customer, then GROUP BY query would be as follows:
TUTORIALS POINT
Simply Easy Learning
NAME SUM(SALARY)
Allen 15000.0
David 85000.0
James 10000.0
Kim 45000.0
Mark 65000.0
Paul 20000.0
Teddy 20000.0
Now, let us create three more records in COMPANY table using the following INSERT statements:
Now, our table has the following records with duplicate names:
Again, let us use the same statement to group-by all the records using NAME column as follows:
sqlite> SELECT NAME, SUM(SALARY) FROM COMPANY GROUP BY NAME ORDER BY NAME;
NAME SUM(SALARY)
Allen 15000
David 85000
James 20000
Kim 45000
Mark 65000
Paul 40000
Teddy 20000
NAME SUM(SALARY)
Teddy 20000
Paul 40000
Mark 65000
Kim 45000
TUTORIALS POINT
Simply Easy Learning
James 20000
David 85000
Allen 15000
TUTORIALS POINT
Simply Easy Learning
CHAPTER
24
SQLite Having Clause
T he HAVING clause enables you to specify conditions that filter which group results appear
The WHERE clause places conditions on the selected columns, whereas the HAVING clause places
conditions on groups created by the GROUP BY clause.
S┞ミ ta┝:
The following is the position of the HAVING clause in a SELECT query:
SELECT
FROM
WHERE
GROUP BY
HAVING
ORDER BY
The HAVING clause must follow the GROUP BY clause in a query and must also precede the ORDER
BY clause if used. The following is the syntax of the SELECT statement, including the HAVING
clause:
E┝a マ ple:
Consider COMPANY table is having the following records:
TUTORIALS POINT
Simply Easy Learning
7 James 24 Houston 10000.0
8 Paul 24 Houston 20000.0
9 James 44 Norway 5000.0
10 James 45 Texas 5000.0
Following is the example, which would display record for which name count is less than 2:
sqlite > SELECT * FROM COMPANY GROUP BY name HAVING count(name) < 2;
Following is the example, which would display record for which name count is greater than 2:
sqlite > SELECT * FROM COMPANY GROUP BY name HAVING count(name) > 2;
TUTORIALS POINT
Simply Easy Learning
CHAPTER
25
SQLite Distinct Keyword
S┞ミ ta┝:
The basic syntax of DISTINCT keyword to eliminate duplicate records is as follows:
E┝a マ ple:
Consider COMPANY table is having the following records:
First, let us see how the following SELECT query returns duplicate salary records:
NAME
TUTORIALS POINT
Simply Easy Learning
Paul
Allen
Teddy
Mark
David
Kim
James
Paul
James
James
Now, let us use DISTINCT keyword with the above SELECT query and see the result:
This would produce the following result, where we do not have any duplicate entry:
NAME
Paul
Allen
Teddy
Mark
David
Kim
James
TUTORIALS POINT
Simply Easy Learning
CHAPTER
26
SQLite PRAGMA
environmental variables and state flags within the SQLite environment. A PRAGMA value can be
read and it can also be set based on requirements.
S┞ミ ta┝:
To query the current PRAGMA value, just provide the name of the pragma:
PRAGMA pragma_name;
To set a new value for PRAGMA, you will use the following syntax:
The set mode can be either the name or the integer equivalent but the returned value will always be an
integer.
auto_┗acuu マ Prag マ a
The auto_vacuum pragma gets or sets the auto-vacuum mode. Following is the simple syntax:
PRAGMA [database.]auto_vacuum;
PRAGMA [database.]auto_vacuum = mode;
TUTORIALS POINT
Simply Easy Learning
cache_size Prag マ a
The cache_size pragma can get or temporarily set the maximum size of the in-memory page cache.
Following is the simple syntax:
PRAGMA [database.]cache_size;
PRAGMA [database.]cache_size = pages;
The pages value represents the number of pages in the cache. The built-in page cache has a
default size of 2,000 pages and a minimum size of 10 pages.
PRAGMA count_changes;
PRAGMA count_changes = [true|false];
By default, this pragma is false and these statements do not return anything. If set to true, each of
the mentioned statement will return an one-column, one-row table consisting of a single integer
value indicating impacted rows by the operation.
dataHase_list Prag マ a
The database_list pragma will be used to list down all the databases attached. Following is the simple syntax:
PRAGMA database_list;
This pragma will return a three-column table with one row per open or attached database
giving database sequence number, its name and file associated.
e ミ codi ミ g Prag マ a
The encoding pragma controls how strings are encoded and stored in a database file. Following is
the simple syntax:
PRAGMA encoding;
PRAGMA encoding = format;
freelist_cou ミ t Prag マ a
The freelist_count pragma returns a single integer indicating how many database pages are
currently marked as free and available. Following is the simple syntax:
PRAGMA [database.]freelist_count;
TUTORIALS POINT
Simply Easy Learning
The format value can be one of UTF-8, UTF-16le, or UTF-16be.
i ミ de┝_i ミ fo Prag マ a
The index_info pragma returns information about a database index. Following is the simple syntax:
The result set will contain one row for each column contained in the index giving column sequence,
column index within table and column name.
i ミ de┝_list Prag マ a
The index_list pragma lists all of the indexes associated with a table. Following is the simple syntax:
The result set will contain one row for each index giving index sequence, index name and flag
indicating whether index is unique or not.
PRAGMA journal_mode;
PRAGMA journal_mode = mode;
PRAGMA database.journal_mode;
PRAGMA database.journal_mode = mode;
DELETE This is default mode. Here at the conclusion of a transaction, the journal file
is deleted.
TRUNCATE The journal file is truncated to a length of zero bytes.
The journal file is left in place, but the header is overwritten to indicate the
PERSIST
journal is no longer valid.
マ a┝_page_cou ミ t Prag マ a
The max_page_count pragma gets or sets the maximum allowed page count for a database.
Following is the simple syntax:
PRAGMA [database.]max_page_count;
PRAGMA [database.]max_page_count = max_page;
The default value is 1,073,741,823 which is one giga-page which means if the default 1 KB page
size, this allows databases to grow up to one terabyte.
TUTORIALS POINT
Simply Easy Learning
page_cou ミ t Prag マ a
The page_count pragma returns the current number of pages in database. Following is the simple syntax:
PRAGMA [database.]page_count;
page_size Prag マ a
The page_size pragma gets or sets the size of the database pages. Following is the simple syntax:
PRAGMA [database.]page_size;
PRAGMA [database.]page_size = bytes;
By default, the allowed sizes are 512, 1024, 2048, 4096, 8192, 16384, and 32768 bytes. The only
way to alter the page size on an existing database is to set the page size and then immediately
VACUUM the database.
parser_trace Prag マ a
The parser_trace pragma controls printing the debugging state as it parses SQL commands.
Following is the simple syntax:
By default, it is set to false but when enabled by setting it to true, the SQL parser will print its state
as it parses SQL commands.
recursi┗e_triggers Prag マ a
The recursive_triggers pragma gets or sets the recursive trigger functionality. If recursive
triggers are not enabled, a trigger action will not fire another trigger. Following is the simple
syntax:
PRAGMA recursive_triggers;
PRAGMA recursive_triggers = [true|false];
PRAGMA [database.]schema_version;
PRAGMA [database.]schema_version = number;
This is a 32-bit signed integer value that keeps track of schema changes. Whenever a schema-
altering command is executed (like, CREATE... or DROP...), this value is incremented.
secure_delete Prag マ a
The secure_delete pragma is used to control how content is deleted from the database. Following is
the simple syntax:
PRAGMA secure_delete;
PRAGMA secure_delete = [true|false];
PRAGMA database.secure_delete;
PRAGMA database.secure_delete = [true|false];
TUTORIALS POINT
Simply Easy Learning
The default value for the secure delete flag is normally off, but this can be changed with
the SQLITE_SECURE_DELETE build option.
s ケ l_trace Prag マ a
The sql_trace pragma is used to dump SQL trace results to the screen. Following is the simple syntax:
PRAGMA sql_trace;
PRAGMA sql_trace = [true|false];
SQLite must be compiled with the SQLITE_DEBUG directive for this pragma to be included.
PRAGMA [database.]synchronous;
PRAGMA [database.]synchronous = mode;
te マ p_store Prag マ a
The temp_store pragma gets or sets the storage mode used by temporary database files. Following
is the simple syntax:
PRAGMA temp_store;
PRAGMA temp_store = mode;
te マ p_store_director┞ Prag マ a
The temp_store_directory pragma gets or sets the location used for temporary database files.
Following is the simple syntax:
PRAGMA temp_store_directory;
PRAGMA temp_store_directory = 'directory_path';
TUTORIALS POINT
Simply Easy Learning
user_┗ersio ミ Prag マ a
The user_version pragma gets or sets the user-defined version value that is stored in the
database header. Following is simple syntax:
PRAGMA [database.]user_version;
PRAGMA [database.]user_version = number;
This is a 32-bit signed integer value, which can be set by the developer for version tracking purpose.
┘ritaHle_sche マ a Prag マ a
The writable_schema pragma gets or sets the ability to modify system tables. Following is the simple syntax:
PRAGMA writable_schema;
PRAGMA writable_schema = [true|false];
If this pragma is set, tables that start with sqlite_ can be created and modified, including the
sqlite_master table. Be careful while using pragma because it can lead to complete database
corruption.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
27
SQLite Constraints
C onstraints are the rules enforced on data columns on table. These are used to limit the
type of data that can go into a table. This ensures the accuracy and reliability of the data in the
database.
Constraints could be column level or table level. Column level constraints are applied only to one
column where as table level constraints are applied to the whole table.
EXAMPLE:
For example, the following SQLite statement creates a new table called COMPANY and adds five
columns, three of which, ID and NAME and AGE, specify not to accept NULLs:
DEFAULT Co ミ strai ミ t
The DEFAULT constraint provides a default value to a column when the INSERT INTO
TUTORIALS POINT
Simply Easy Learning
statement does not provide a specific value.
TUTORIALS POINT
Simply Easy Learning
EXAMPLE:
For example, the following SQLite statement creates a new table called COMPANY and adds five
columns. Here, SALARY column is set to 5000.00 by default, so in case INSERT INTO statement does
not provide a value for this column, then by default, this column would be set to 5000.00.
UNIQUE Co ミ strai ミ t
The UNIQUE Constraint prevents two records from having identical values in a particular
column. In the COMPANY table, for example, you might want to prevent two or more people from
having identical age.
EXAMPLE:
For example, the following SQLite statement creates a new table called COMPANY and adds five
columns. Here, AGE column is set to UNIQUE, so that you can not have two records with same age:
We use them to refer to table rows. Primary keys become foreign keys in other tables, when
creating relations among tables. Due to a 'longstanding coding oversight', primary keys can be
NULL in SQLite. This is not the case with other databases.
A primary key is a field in a table which uniquely identifies the each rows/records in a database
table. Primary keys must contain unique values. A primary key column cannot have NULL values.
A table can have only one primary key which may consist of single or multiple fields. When multiple
fields are used as a primary key, they are called a composite key.
If a table has a primary key defined on any field(s), then you can not have two records having the
same value of that field(s).
EXAMPLE:
You already have seen various examples above where we have created COMAPNY table with ID as primary
key:
CHECK Co ミ strai ミ t
The CHECK Constraint enables a condition to check the value being entered into a record. If
the condition evaluates to false, the record violates the constraint and isn't entered into the table.
EXAMPLE:
For example, the following SQLite creates a new table called COMPANY and adds five columns.
Here, we add a CHECK with SALARY column, so that you can not have any SALARY Zero:
TUTORIALS POINT
Simply Easy Learning
CHAPTER
28
SQLite Joins
T he SQLite Joins clause is used to combine records from two or more tables in a database. A
JOIN is a means for combining fields from two tables by using values common to each.
Before we proceed, let's consider two tables COMPANY and DEPARTMENT. We already have seen
INSERT statements to populate COMPANY table. So just let's assume the list of records available in
COMPANY table:
ID NAME AGE ADDRESS SALARY
TUTORIALS POINT
Simply Easy Learning
INSERT INTO DEPARTMENT (ID, DEPT, EMP_ID)
VALUES (3, 'Finance', 7 );
ID DEPT EMP_ID
1 IT Billing 1
2 Engineerin 2
3 Finance 7
sqlite> SELECT EMP_ID, NAME, DEPT FROM COMPANY CROSS JOIN DEPARTMENT;
1 Paul IT Billing
2 Paul Engineerin
7 Paul Finance
1 Allen IT Billing
2 Allen Engineerin
7 Finance
Allen
1
Teddy IT Billing
2
Teddy Engineerin
7
Teddy Finance
1
2 Mark IT Billing
7 Mark Engineerin
1 Mark Finance
2 David IT Billing
7 David Engineerin
1 David Finance
2 Kim IT Billing
Engineerin
7 Kim Finance
1 James IT Billing
2 James Engineerin
7 James Finance
TUTORIALS POINT
Simply Easy Learning
An INNER JOIN is the most common type of join and is the default type of join. You can use
INNER keyword optionally.
Following is the syntax of INNER JOIN:
To avoid redundancy and keep the phrasing shorter, INNER JOIN conditions can be declared with
a
USING expression. This expression specifies a list of one or more columns:
SELECT ... FROM table1 JOIN table2 USING ( column1 ,... ) ...
A NATURAL JOIN is similar to a JOIN...USING, only it automatically tests for equality between the
values of every column that exists in both tables:
sqlite> SELECT EMP_ID, NAME, DEPT FROM COMPANY INNER JOIN DEPARTMENT
ON COMPANY.ID = DEPARTMENT.EMP_ID;
1 Paul IT Billing
2 Allen Engineerin
7 James Finance
SELECT ... FROM table1 LEFT OUTER JOIN table2 ON conditional_expression ...
To avoid redundancy and keep the phrasing shorter, OUTER JOIN conditions can be declared with a
USING expression. This expression specifies a list of one or more columns:
SELECT ... FROM table1 LEFT OUTER JOIN table2 USING ( column1 ,... ) ...
sqlite> SELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENT
ON COMPANY.ID = DEPARTMENT.EMP_ID;
1 Paul IT Billing
2 Allen Engineerin
TUTORIALS POINT
Simply Easy Learning
Teddy
Mark
David
Kim
7 James Finance
TUTORIALS POINT
Simply Easy Learning
CHAPTER
29
SQLite UNIONS Clause
T he SQLite UNION clause/operator is used to combine the results of two or more SELECT
S┞ミ ta┝:
The basic syntax of UNION is as follows:
UNION
E┝a マ ple:
The tables COMPANY and DEPARTMENT are shown here:
COMPANY TABLE
This is the file to create COMPANY table and to populate it with 7 records.
-- Just copy and past them on sqlite> prompt.
TUTORIALS POINT
Simply Easy Learning
INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Paul', 32, 'California', 20000.00 );
TUTORIALS POINT
Simply Easy Learning
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
ID DEPT EMP_ID
1 IT Billing 1
2 Engineering 2
3 Finance 7
4 Engineering 3
5 Finance 4
6 Engineering 5
7 Finance 6
Now, let us join these two tables using SELECT statement along with UNION clause as follows:
sqlite> SELECT EMP_ID, NAME, DEPT FROM COMPANY INNER JOIN DEPARTMENT
ON COMPANY.ID = DEPARTMENT.EMP_ID
UNION
SELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENT
ON COMPANY.ID = DEPARTMENT.EMP_ID;
1 Paul IT Billing
2 Allen Engineerin
3 Teddy Engineerin
4 Mark Finance
5 David Engineerin
6 Kim Finance
7 James Finance
duplicate rows. The same rules that apply to UNION apply to the UNION ALL operator as well.
S┞ミ ta┝:
The basic syntax of UNION ALL is as follows:
UNION ALL
TUTORIALS POINT
Simply Easy Learning
E┝a マ ple:
Now, let us join above-mentioned two tables in our SELECT statement as follows:
sqlite> SELECT EMP_ID, NAME, DEPT FROM COMPANY INNER JOIN DEPARTMENT
ON COMPANY.ID = DEPARTMENT.EMP_ID
UNION ALL
SELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENT
ON COMPANY.ID = DEPARTMENT.EMP_ID;
1 Paul IT Billing
2 Allen Engineerin
3 Teddy Engineerin
4 Mark Finance
5 David Engineerin
6
Kim Finance
7
1 James Finance
2 Paul IT Billing
Allen Engineerin
3 Teddy Engineerin
4 Mark Finance
5 David Engineerin
6 Kim Finance
7 James Finance
TUTORIALS POINT
Simply Easy Learning
CHAPTER
30
SQLite NULL Values
T he SQLite NULL is the term used to represent a missing value. A NULL value in a table is a
S┞ミ ta┝:
The basic syntax of using NULL while creating a table:
Here, NOT NULL signifies that column should always accept an explicit value of the given data type.
There are two columns where we did not use NOT NULL which means these columns could be NULL.
A field with a NULL value is one that has been left blank during record creation.
E┝a マ ple:
The NULL value can cause problems when selecting data, however, because when comparing an
unknown value to any other value, the result is always unknown and not included in the final
results. Consider the following table, COMPANY having the following records:
Let us use UPDATE statement to set few nullable values as NULL as follows:
TUTORIALS POINT
Simply Easy Learning
sqlite> UPDATE COMPANY SET ADDRESS = NULL, SALARY = NULL where ID IN(6,7);
Next, let us see the usage of IS NOT NULL operator to list down all the records where SALARY is not NULL:
Following is the usage of IS NULL operator, which will list down all the records where SALARY is NULL:
6 Kim 22
7 James 24
TUTORIALS POINT
Simply Easy Learning
CHAPTER
31
SQLite ALIAS Syntax
Y ou can rename a table or a column temporarily by giving another name, which is known as
ALIAS. The use of table aliases means to rename a table in a particular SQLite statement.
Renaming is a temporary change and the actual table name does not change in the database.
The column aliases are used to rename a table's columns for the purpose of a particular SQLite query.
S┞ミ ta┝:
The basic syntax of table alias is as follows:
E┝a マ ple:
Consider the following two tables, (a) COMPANY table is as follows:
ID DEPT EMP_ID
TUTORIALS POINT
Simply Easy Learning
1 IT Billing 1
2 Engineering 2
3 Finance 7
4 Engineering 3
5 Finance 4
6 Engineering 5
7 Finance 6
Now, following is the usage of TABLE ALIAS where we use C and D as aliases for COMPANY and
DEPARTMENT tables respectively:
1 Paul 32 IT Billing
2 Allen 25 Engineerin
3 Teddy 23 Engineerin
4 Mark 25 Finance
5 David 27 Engineerin
6 Kim 22 Finance
7 James 24 Finance
Let us see an example for the usage of COLUMN ALIAS where COMPANY_ID is an alias of ID column and
COMPANY_NAME is an alias of name column:
1 Paul 32 IT Billing
2 Allen 25 Engineerin
3 Teddy 23 Engineerin
4 Mark 25 Finance
5 David 27 Engineerin
6 Kim 22 Finance
7 James 24 Finance
TUTORIALS POINT
Simply Easy Learning
CHAPTER
32
SQLite Triggers
performed/invoked when a specified database event occurs. Following are the important points
about SQLite triggers:
SQLite trigger may be specified to fire whenever a DELETE, INSERT or UPDATE of a particular
database table occurs or whenever an UPDATE occurs on on one or more specified columns of a
table.
At this time, SQLite supports only FOR EACH ROW triggers, not FOR EACH STATEMENT triggers.
Hence, explicitly specifying FOR EACH ROW is optional.
Both the WHEN clause and the trigger actions may access elements of the row being inserted,
deleted or updated using references of the form NEW.column-name and OLD.column-name,
where column-name is the name of a column from the table that the trigger is associated with.
If a WHEN clause is supplied, the SQL statements specified are only executed for rows for which
the WHEN clause is true. If no WHEN clause is supplied, the SQL statements are executed for all
rows.
The BEFORE or AFTER keyword determines when the trigger actions will be executed relative to
the insertion, modification or removal of the associated row.
Triggers are automatically dropped when the table that they are associated with is dropped.
The table to be modified must exist in the same database as the table or view to which the
trigger is attached and one must use just tablename not database.tablename.
A special SQL function RAISE() may be used within a trigger-program to raise an exception.
S┞ミ ta┝:
The basic syntax of creating a trigger is as follows:
Here, event_name could be INSERT, DELETE, and UPDATE database operation on the
mentioned table table_name. You can optionally specify FOR EACH ROW
TUTORIALS POINT
Simply Easy Learning
after table name.
TUTORIALS POINT
Simply Easy Learning
Following is the syntax of creating a trigger on an UPDATE operation on one or more specified
columns of a table as follows:
E┝a マ ple
Let us consider a case where we want to keep audit trial for every record being inserted in
COMPANY table, which we create newly as follows (Drop COMPANY table if you already have it):
To keep audit trial, we will create a new table called AUDIT where log messages will be inserted
whenever there is an entry in COMPANY table for a new record:
Here, ID is the AUDIT record ID, and EMP_ID is the ID which will come from COMPANY table and
DATE will keep timestamp when the record will be created in COMPANY table. So now let's create a
trigger on COMPANY table as follows:
Now, we will start actual work, let's start inserting record in COMPANY table which should result in
creating an audit log record in AUDIT table. So let's create one record in COMPANY table as follows:
Same time, one record will be create in AUDIT table. This record is the result of a trigger, which we
have created on INSERT operation on COMPANY table. Similar way, you can create your triggers on
UPDATE and DELETE operations based on your requirements.
EMP_ID ENTRY_DATE
1 2013-04-05 06:26:00
TUTORIALS POINT
Simply Easy Learning
Listi ミ g TRIGGERS
You can list down all the triggers from sqlite_master table as follows:
Above SQLite statement will list down only one entry as follows:
name
audit_log
If you want to list down triggers on a particular table, then use AND clause with table name as follows:
Above SQLite statement will also list down only one entry as follows:
name
audit_log
Droppi ミ g TRIGGERS
Following is the DROP command, which can be used to drop an existing trigger:
TUTORIALS POINT
Simply Easy Learning
CHAPTER
33
SQLite Indexes
I ndexes are special lookup tables that the database search engine can use to speed up data
retrieval. Simply put, an index is a pointer to data in a table. An index in a database is very similar
to an index in the back of a book.
For example, if you want to reference all pages in a book that discuss a certain topic, you first refer
to the index, which lists all topics alphabetically and are then referred to one or more specific page
numbers.
An index helps speed up SELECT queries and WHERE clauses, but it slows down data input, with
UPDATE and INSERT statements. Indexes can be created or dropped with no effect on the data.
Creating an index involves the CREATE INDEX statement, which allows you to name the index, to
specify the table and which column or columns to index, and to indicate whether the index is in
ascending or descending order.
Indexes can also be unique, similar to the UNIQUE constraint, in that the index prevents duplicate
entries in the column or combination of columns on which there's an index.
Si ミ gle-Colu マミ I ミ de┝es:
A single-column index is one that is created based on only one table column. The basic syntax is as follows:
U ミ i ケ ue I ミ de┝es:
Unique indexes are used not only for performance, but also for data integrity. A unique index does
not allow any duplicate values to be inserted into the table. The basic syntax is as follows:
TUTORIALS POINT
Simply Easy Learning
on table_name (column_name);
Co マ posite I ミ de┝es:
A composite index is an index on two or more columns of a table. The basic syntax is as follows:
Whether to create a single-column index or a composite index, take into consideration the
column(s) that you may use very frequently in a query's WHERE clause as filter conditions.
Should there be only one column used, a single-column index should be the choice. Should there be
two or more columns that are frequently used in the WHERE clause as filters, the composite index
would be the best choice.
I マ plicit I ミ de┝es:
Implicit indexes are indexes that are automatically created by the database server when an
object is created. Indexes are automatically created for primary key constraints and unique
constraints.
E┝a マ ple
Following is an example where we will create an index on COMPANY table for salary column:
Now, let's list down all the indices available on COMPANY table using .indices command as follows:
This will produce the following result, where sqlite_autoindex_COMPANY_1 is an implicit index,
which got created when table itself was created.
salary_index
sqlite_autoindex_COMPANY_1
You can list down all the indexes database wide as follows:
TUTORIALS POINT
Simply Easy Learning
Whe ミ should i ミ de┝es He a┗oided?
Although indexes are intended to enhance a database's performance, there are times when
they should be avoided. The following guidelines indicate when the use of an index should be
reconsidered:
Indexes should not be used on columns that contain a high number of NULL values.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
34
SQLite Indexed By
T he "INDEXED BY index-name" clause specifies that the named index must be used in order
If index-name does not exist or cannot be used for the query, then the preparation of the SQLite statement
fails.
The "NOT INDEXED" clause specifies that no index shall be used when accessing the preceding
table, including implied indices create by UNIQUE and PRIMARY KEY constraints.
However, the INTEGER PRIMARY KEY can still be used to look up entries even when "NOT
INDEXED" is specified.
S┞ミ ta┝
Following is the syntax for INDEXED BY clause and it can be used with DELETE, UPDATE or SELECT statement:
E┝a マ ple
COMPANY Table:
-- This is the file to create COMPANY table and to populate it with 7 records.
-- Just copy and past them on sqlite> prompt.
DROP TABLE COMPANY;
CREATE TABLE COMPANY(
NOT NULL,
ID INT PRIMARY KEY
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL
);
INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Paul', 32, 'California', 20000.00 );
TUTORIALS POINT
Simply Easy Learning
INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );
Now selecting the data from table COMPANY you can use INDEXED BY clause as follows:
sqlite> SELECT * FROM COMPANY INDEXED BY salary_index WHERE salary > 5000;
Kindly note that though SQLite specification talks about the above-mentioned Syntax forINDEXED BY
clause but I tried all the way to make INDEXED BY work on my installation but it did not work. If you
found a solution kindly share it at webmaster@tutorialspoint.com.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
35
SQLite Alter Command
T he SQLite ALTER TABLE command modifies an existing table without performing a full
dump and reload of the data. You can rename a table using ALTER TABLE statement and additional
columns can be added in an existing table using ALTER TABLE statement.
There is no other operation supported by ALTER TABLE command in SQLite except renaming a table
and adding a column in existing table.
S┞ミ ta┝:
The basic syntax of ALTER TABLE to RENAME an existing table is as follows:
The basic syntax of ALTER TABLE to add a new column in an existing table is as follows:
E┝a マ ple:
Consider our COMPANY table has the following records:
Now, let's try to rename this table using ALTER TABLE statement as follows:
TUTORIALS POINT
Simply Easy Learning
Above SQLite statement will rename COMPANY table to OLD_COMPANY. Now, let's try to add a new column
in OLD_COMPANY table as follows:
Now, COMPANY table is changed and following would be output from SELECT statement:
It should be noted that newly added column is filled with NULL values.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
36
SQLite Truncate Table
U nfortunately, we do not have TRUNCATE TABLE command in SQLite but you can use
SQLite DELETE command to delete complete data from an existing table, though it is
recommended to use DROP TABLE command to drop complete table and re-create it once again.
S┞ミ ta┝:
The basic syntax of DELETE command is as follows:
If you are using DELETE TABLE command to delete all the records, it is recommended
to useVACUUM command to clear unused space.
E┝a マ ple:
Consider COMPANY table is having the following records:
Now, COMPANY table is truncated completely and nothing would be output from SELECT statement:
TUTORIALS POINT
Simply Easy Learning
CHAPTER
37
SQLite Views
A view is nothing more than a SQLite statement that is stored in the database with an
associated name. A view is actually a composition of a table in the form of a predefined SQLite
query.
A view can contain all rows of a table or selected rows from one or more tables. A view can be
created from one or many tables which depends on the written SQLite query to create a view.
Views which are kind of virtual tables, allow users to do the following:
Structure data in a way that users or classes of users find natural or intuitive.
Restrict access to the data such that a user can only see limited data instead of complete table.
Summarize data from various tables which can be used to generate reports.
SQLite views are read-only and so you may not execute a DELETE, INSERT or UPDATE statement on
a view. But you can create a trigger on a view that fires on an attempt to DELETE, INSERT or
UPDATE a view and do what you need in the body of the trigger.
Creati ミ g Vie┘s:
The SQLite views are created using the CREATE VIEW statement. The SQLIte views can be created
from a single table, multiple tables, or another view.
The basic CREATE VIEW syntax is as follows:
You can include multiple tables in your SELECT statement in very similar way as you use them in
normal SQL SELECT query. If the optional TEMP or TEMPORARY keyword is present, the view will be
created in the temp database.
E┝a マ ple:
Consider COMPANY table is having the following records:
TUTORIALS POINT
Simply Easy Learning
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Now, following is an example to create a view from COMPANY table. This view would be used to
have only few columns from COMPANY table:
Now, you can query COMPANY_VIEW in similar way as you query an actual table. Following is the example:
ID NAME AGE
1 Paul 32
2 Allen 25
3 Teddy 23
4 Mark 25
5 David 27
6 Kim 22
7 James 24
Droppi ミ g Vie┘s:
To drop a view, simply use the DROP VIEW statement with the view_name. The basic DROP VIEW
syntax is as follows:
Following command will delete COMPANY_VIEW view, which we created in the last section:
TUTORIALS POINT
Simply Easy Learning
CHAPTER
38
SQLite TRANSACTIONS
A transaction is a unit of work that is performed against a database. Transactions are units
A transaction is the propagation of one or more changes to the database. For example, if you are
creating a record or updating a record or deleting a record from the table. then you are performing
transaction on the table. It is important to control transactions to ensure data integrity and to
handle database errors.
Practically, you will club many SQLite queries into a group and you will execute all of them together
as part of a transaction.
Atomicity: ensures that all operations within the work unit are completed successfully;
otherwise, the transaction is aborted at the point of failure and previous operations are rolled
back to their former state.
Consistency: ensures that the database properly changes states upon a successfully committed
transaction.
Isolation: enables transactions to operate independently of and transparent to each other.
Durability: ensures that the result or effect of a committed transaction persists in case of a system
failure.
Transactional control commands are only used with the DML commands INSERT, UPDATE and
DELETE. They can not be used while creating tables or dropping them because these operations are
automatically committed in the database.
TUTORIALS POINT
Simply Easy Learning
The BEGIN TRANSACTION Co ママ a ミ d:
Transactions can be started using BEGIN TRANSACTION or simply BEGIN command. Such
transactions usually persist until the next COMMIT or ROLLBACK command encountered. But a
transaction will also ROLLBACK if the database is closed or if an error occurs. Following is the
simple syntax to start a transaction:
BEGIN;
or
BEGIN TRANSACTION;
The COMMIT Co ママ a ミ d:
The COMMIT command is the transactional command used to save changes invoked by a
transaction to the database.
The COMMIT command saves all transactions to the database since the last COMMIT or ROLLBACK
COMMIT;
or
END TRANSACTION;
The ROLLBACK Co ママ a ミ d:
The ROLLBACK command is the transactional command used to undo transactions that have not
already been saved to the database.
The ROLLBACK command can only be used to undo transactions since the last COMMIT or
ROLLBACK command was issued.
ROLLBACK;
E┝a マ ple:
Consider COMPANY table is having the following records:
ID NAME AGE ADDRESS SALARY
Now, let's start a transaction and delete records from the table having age = 25 and finally we use
ROLLBACK command to undo all the changes.
TUTORIALS POINT
Simply Easy Learning
sqlite> BEGIN;
sqlite> DELETE FROM COMPANY WHERE AGE = 25;
sqlite> ROLLBACK;
If you will check, COMPANY table is still having the following records:
Now, let's start another transaction and delete records from the table having age = 25 and finally
we use COMMIT command to commit all the changes.
sqlite> BEGIN;
sqlite> DELETE FROM COMPANY WHERE AGE = 25;
sqlite> COMMIT;
If you will check, COMPANY table is still having the following records:
TUTORIALS POINT
Simply Easy Learning
CHAPTER
39
SQLite Sub Queries
A Subquery or Inner query or Nested query is a query within another SQLite query and
A subquery is used to return data that will be used in the main query as a condition to further
restrict the data to be retrieved.
Subqueries can be used with the SELECT, INSERT, UPDATE and DELETE statements along with the
operators like =, <, >, >=, <=, IN, BETWEEN etc.
A subquery can have only one column in the SELECT clause, unless multiple columns are in the
main query for the subquery to compare its selected columns.
An ORDER BY cannot be used in a subquery, although the main query can use an ORDER BY.
The GROUP BY can be used to perform the same function as the ORDER BY in a subquery.
Subqueries that return more than one row can only be used with multiple value operators,
such as the IN operator.
The BETWEEN operator cannot be used with a subquery; however, the BETWEEN can be used
within the subquery.
TUTORIALS POINT
Simply Easy Learning
E┝a マ ple:
Consider COMPANY table is having the following records:
sqlite> SELECT *
FROM COMPANY
WHERE ID IN (SELECT ID
FROM COMPANY
WHERE SALARY > 45000) ;
E┝a マ ple:
Consider a table COMPANY_BKP with similar structure as COMPANY table and can be created using
same CREATE TABLE using COMPANY_BKP as table name. Now to copy complete COMPANY table
into COMPANY_BKP, following is the syntax:
TUTORIALS POINT
Simply Easy Learning
SuH ケ ueries ┘ith the UPDATE State マ e ミ t:
The subquery can be used in conjunction with the UPDATE statement. Either single or multiple
columns in a table can be updated when using a subquery with the UPDATE statement.
UPDATE table
SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
E┝a マ ple:
Assuming, we have COMPANY_BKP table available which is backup of COMPANY table.
Following example updates SALARY by 0.50 times in COMPANY table for all the customers,
whose AGE is greater than or equal to 27:
This would impact two rows and finally COMPANY table would have the following records:
E┝a マ ple:
Assuming, we have COMPANY_BKP table available which is backup of COMPANY table.
TUTORIALS POINT
Simply Easy Learning
Following example deletes records from COMPANY table for all the customers whose AGE is
greater than or equal to 27:
This would impact two rows and finally COMPANY table would have the following records:
TUTORIALS POINT
Simply Easy Learning
CHAPTER
40
SQLite AUTOINCREMENT
S QLite AUTOINCREMENT is a keyword used for auto incrementing a value of a field in the
table. We can auto increment a field value by using AUTOINCREMENT keyword when creating a
table with specific column name to auto incrementing it.
The keyword AUTOINCREMENT can be used with INTEGER field only.
S┞ミ ta┝:
The basic usage of AUTOINCREMENT keyword is as follows:
E┝a マ ple:
Consider COMPANY table to be created as follows:
TUTORIALS POINT
Simply Easy Learning
INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)
VALUES ( 'Mark', 25, 'Rich-Mond ', 65000.00 );
TUTORIALS POINT
Simply Easy Learning
CHAPTER
41
SQLite Injection
I f you take user input through a webpage and insert it into a SQLite database, there's a chance
that you have left yourself wide open for a security issue known as SQL Injection. This lesson will
teach you how to help prevent this from happening and help you secure your scripts and SQLite
statements.
Injection usually occurs when you ask a user for input, like their name, and instead of a name they
give you a SQLite statement that you will unknowingly run on your database.
Never trust user provided data, process this data only after validation; as a rule, this is done by
pattern matching. In the example below, the username is restricted to alphanumerical chars plus
underscore and to a length between 8 and 20 chars - modify these rules as needed.
The function call is supposed to retrieve a record from the users table where the name column
matches the name specified by the user. Under normal circumstances, $name would only contain
alphanumeric characters and perhaps spaces, such as the string ilia. But here, by appending an
entirely new query to $name, the call to the database turns into disaster: the injected DELETE
query removes all records from users.
There are database's interfaces which do not permit query stacking or executing multiple queries in
a single function call. If you try to stack queries, the call fails but SQLite and PostgreSQL, happily
perform stacked queries, executing all of the queries provided in one string and creating a serious
security problem.
if (get_magic_quotes_gpc())
TUTORIALS POINT
{
Simply
$name Easy Learning
= sqlite_escape_string($name);
}
$result = @$db->query("SELECT * FROM users WHERE username='{$name}'");
Although the encoding makes it safe to insert the data, it will render simple text comparisons and
LIKEclauses in your queries unusable for the columns that contain the binary data.
Keep a note that addslashes() should NOT be used to quote your strings for SQLite queries; it will
lead to strange results when retrieving your data.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
42
SQLite Explain
A n SQLite statement can be preceded by the keyword "EXPLAIN" or by the phrase "EXPLAIN
Either modification causes the SQLite statement to behave as a query and to return information
about how the SQLite statement would have operated if the EXPLAIN keyword or phrase had been
omitted.
The output from EXPLAIN and EXPLAIN QUERY PLAN is intended for interactive
analysis and troubleshooting only.
The details of the output format are subject to change from one release of SQLite to the next.
Applications should not use EXPLAIN or EXPLAIN QUERY PLAN since their exact behavior is
variable and only partially documented.
S┞ミ ta┝:
Syntax for EXPLAIN is as follows:
E┝a マ ple:
This is the file to create COMPANY table and to populate it with 7 records.
-- Just copy and past them on sqlite> prompt.
TUTORIALS POINT
Simply Easy Learning
VALUES (1, 'Paul', 32, 'California', 20000.00 );
addr opcode p1 p2 p3
0 Goto 0 19
1 Integer 0 0
2 OpenRead 0 8
3 SetNumColu 0 5
4 Rewind 0 17
5 Column 0 4
6 RealAffini 0 0
7 Integer 20000 0
8 Lt 357 16 collseq(BI
9 Rowid 0 0
10 Column 0 1
11 Column 0 2
12 Column 0 3
13 Column 0 4
14 RealAffini 0 0
15 Callback 5 0
16 Next 0 5
17 Close 0 0
18 Halt 0 0
19 Transactio 0 0
TUTORIALS POINT
Simply Easy Learning
20 VerifyCook 0 38
21 Goto 0 1
22 Noop 0 0
Now, let us check following Explain Query Plan with SELECT statement:
SQLite> EXPLAIN QUERY PLAN SELECT * FROM COMPANY WHERE Salary >= 20000;
order from detail
0 0 TABLE COMPANY
TUTORIALS POINT
Simply Easy Learning
CHAPTER
43
SQLite Vacuum
T he VACUUM command cleans the main database by copying its contents to a temporary
database file and reloading the original database file from the copy. This eliminates free pages,
aligns table data to be contiguous, and otherwise cleans up the database file structure.
The VACUUM command may change the ROWID of entries in tables that do not have an explicit
INTEGER PRIMARY KEY. The VACUUM command only works on the main database. It is not possible
to VACUUM an attached database file.
The VACUUM command will fail if there is an active transaction. The VACUUM command is a no-op
for in- memory databases. As the VACUUM command rebuilds the database file from scratch,
VACUUM can also be used to modify many database-specific configuration parameters.
Ma ミ ual VACUUM
Following is simple syntax to issue a VACUUM command for the whole database from command prompt:
sqlite> VACUUM;
Auto-VACCUM
SQLite Auto-VACUUM does not do the same as VACUUM rather it only moves free pages to the end
of the database thereby reducing the database size. By doing so it can significantly fragment the
database while VACUUM ensures defragmentation. So Auto-VACUUM just keeps the database small.
You can enable/disable SQLite auto-vacuuming by the following pragmas running at SQLite prompt:
TUTORIALS POINT
Simply Easy Learning
You can run following command from command prompt to check the auto-vacuum setting:
TUTORIALS POINT
Simply Easy Learning
CHAPTER
44
SQLite Date & Time
strftime(timestring, This returns the date formatted according to the format string
5
modifiers...) specified as the first argument formatted as per formatters
explained below.
All the above five date and time functions take a time string as an argument. The time string is
followed by zero or more modifiers. The strftime() function also takes a format string as its first
argument. Following section will give you detail on different types of time strings and modifiers.
Ti マ e Stri ミ gs:
A time string can be in any of the following formats:
1 YYYY-MM-DD 2010-12-30
5 HH:MM 12:10
TUTORIALS POINT
Simply Easy Learning
7 HH:MM:SS 12:10:01
9 Now 2013-05-07
You can use the "T" as a literal character separating the date and the time.
Modifiers
The time string can be followed by zero or more modifiers that will alter date and/or time returned
by any of the above five functions. Modifiers are applied from left to right and following modifers
are available in SQLite:
NNN days
NNN hours
NNN minutes
NNN.NNNN seconds
NNN months
NNN years
start of month
start of year
start of day
weekday N
unixepoch
localtime
utc
For マ atters:
SQLite provides very handy function strftime() to format any date and time. You can use following
substitutions to format your date and time:
Substitution Description
%H Hour, 00-23
%m Month, 00-12
%M Minute, 00-59
TUTORIALS POINT
Simply Easy Learning
%s Seconds since 1970-01-01
%S Seconds, 00-59
%Y Year, YYYY
%% % symbol
E┝a マ ples
Let's try various examples now using SQLite prompt. Following computes the current date:
Following computes the date and time given a UNIX timestamp 1092941466:
Following computes the date and time given a UNIX timestamp 1092941466 and compensate
for your local timezone:
Following computes the number of days since the signing of the US Declaration of Independence:
Following computes the date of the first Tuesday in October for the current year:
TUTORIALS POINT
Simply Easy Learning
Following computes the time since the UNIX epoch in seconds (like strftime('%s','now') except
includes fractional part):
To convert between UTC and local time values when formatting a date, use the utc or localtime
modifiers as follows:
TUTORIALS POINT
Simply Easy Learning
CHAPTER
45
SQLite Useful Functions
S QLite has many built-in functions for performing processing on string or numeric data.
Following is the list of few useful SQLite built-in functions and all are case insensitive, which means
you can use these functions either in lower-case form or in upper-case or in mixed form. For more
details, you can check official documentation for SQLite:
TUTORIALS POINT
Simply Easy Learning
Before we start giving examples on the above mentioned functions, consider COMPANY table is
having the following records:
count(*)
max(salary)
85000.0
min(salary)
10000.0
TUTORIALS POINT
Simply Easy Learning
sqlite> SELECT avg(salary) FROM COMPANY;
avg(salary)
37142.8571428572
sum(salary)
260000.0
Random
5876796417670984050
5 15 0 0.0
upper(name)
TUTORIALS POINT
Simply Easy Learning
PAUL
ALLEN
TEDDY
MARK
DAVID
KIM
JAMES
lower(name)
paul
allen
teddy
mark
david
kim
james
NAME length(name)
Paul 4
Allen 5
Teddy 5
Mark 4
David 5
Kim 3
James 5
SQLite Version
3.6.20
TUTORIALS POINT
Simply Easy Learning
CHAPTER
46
SQLite C/C++ Tutorial
Installation
B efore we start using SQLite in our C/C++ programs, we need to make sure that we have
SQLite library set up on the machine. You can check SQLite Installation chapter to understand
installation process.
This routine opens a connection to an SQLite database file and returns a database
connection object to be used by other SQLite routines.
If filename is not NULL, sqlite3_open() attempts to open the database file by using its value.
If no file by that name exists, sqlite3_open() will open a new database file by that name.
This routine provides a quick, easy way to execute SQL commands provided by sql argument
which can consist of more than one SQL command.
2
Here, first argument sqlite3 is open database object, sqlite_callback is a call back for
whichdata is the 1st argument and errmsg will be return to capture any error raised by the
routine.
The sqlite3_exec() routine parses and executes every command given in the sql
argument until it reaches the end of the string or encounters an error.
sqlite3_close(sqlite3*)
3
This routine closes a database connection previously opened by a call to sqlite3_open().
TUTORIALS POINT
Simply Easy Learning
All prepared
statements associated with the connection should be finalized prior to closing the
connection.
If any queries remain that have not been finalized, sqlite3_close() will return
SQLITE_BUSY with the error message Unable to close due to unfinalized statements.
Co ミミ ecti ミ g To DataHase
Following C code segment shows how to connect to an existing database. If database does not
exist, then it will be created and finally a database object will be returned.
#include <stdio.h>
#include <sqlite3.h>
rc = sqlite3_open("test.db", &db);
if( rc ){
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
exit(0);
}else{
fprintf(stderr, "Opened database successfully\n");
}
sqlite3_close(db);
}
Now, let's compile and run above program to create our database test.db in the current
directory. You can change your path as per your requirement.
If you are going to use C++ source code, then you can compile your code as follows:
Here, we are linking our program with sqlite3 library to provide required functions to C program.
This will create a database file test.db in your directory and you will have the result something as
follows:
Create a TaHle
Following C code segment will be used to create a table in previously created database:
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
static int callback(void *NotUsed, int argc, char **argv, char **azColName){
TUTORIALS POINT
Simply Easy Learning
int i;
for(i=0; i<argc; i++){
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
/* Open database */
rc = sqlite3_open("test.db", &db);
if( rc ){
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
exit(0);
}else{
fprintf(stdout, "Opened database successfully\n");
}
When above program is compiled and executed, it will create COMPANY table in your test.db and
final listing of the file will be as follows:
INSERT Operatio ミ
Following C code segment shows how we can create records in our COMPANY table created in above
example:
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
TUTORIALS POINT
Simply Easy Learning
static int callback(void *NotUsed, int argc, char **argv, char **azColName){
int i;
for(i=0; i<argc; i++){
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
/* Open database */
rc = sqlite3_open("test.db", &db);
if( rc ){
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
exit(0);
}else{
fprintf(stderr, "Opened database successfully\n");
}
SELECT Operatio ミ
Before we proceed with actual example to fetch records, let me give a little detail about the
callback function, which we are using in our examples. This callback provides a way to obtain
results from SELECT statements. It has the following declaration:
TUTORIALS POINT
Simply Easy Learning
void*, /* Data provided in the 4th argument of sqlite3_exec() */
int, /* The number of columns in row */
char**, /* An array of strings representing fields in the row */
char** /* An array of strings representing column names */
);
If above callback is provided in sqlite_exec() routine as the third argument, SQLite will call the
this callback function for each record processed in each SELECT statement executed within the SQL
argument.
Following C code segment shows how we can fetch and display records from our COMPANY table
created in above example:
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
static int callback(void *data, int argc, char **argv, char **azColName){
int i;
fprintf(stderr, "%s: ", (const char*)data);
for(i=0; i<argc; i++){
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
/* Open database */
rc = sqlite3_open("test.db", &db);
if( rc ){
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
exit(0);
}else{
fprintf(stderr, "Opened database successfully\n");
}
TUTORIALS POINT
Simply Easy Learning
Opened database successfully
Callback function called: ID = 1
NAME = Paul
AGE = 32
ADDRESS = California
SALARY = 20000.0
UPDATE Operatio ミ
Following C code segment shows how we can use UPDATE statement to update any record and
then fetch and display updated records from our COMPANY table:
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
static int callback(void *data, int argc, char **argv, char **azColName){
int i;
fprintf(stderr, "%s: ", (const char*)data);
for(i=0; i<argc; i++){
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
/* Open database */
rc = sqlite3_open("test.db", &db);
if( rc ){
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
exit(0);
TUTORIALS POINT
Simply Easy Learning
fprintf(stderr, "Opened database successfully\n");
}
DELETE Operatio ミ
Following C code segment shows how we can use DELETE statement to delete any record and then
fetch and display remaining records from our COMPANY table:
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
static int callback(void *data, int argc, char **argv, char **azColName){
int i;
fprintf(stderr, "%s: ", (const char*)data);
TUTORIALS POINT
Simply Easy Learning
for(i=0; i<argc; i++){
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
/* Open database */
rc = sqlite3_open("test.db", &db);
if( rc ){
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
exit(0);
}else{
fprintf(stderr, "Opened database successfully\n");
}
TUTORIALS POINT
Simply Easy Learning
Operation done successfully
TUTORIALS POINT
Simply Easy Learning
CHAPTER
47
SQLite Java Tutorial
Installation
B efore we start using SQLite in our Java programs, we need to make sure that we have
SQLite JDBC Driver and Java set up on the machine. You can check Java tutorial for Java installation
on your machine. Now, let us check how to set up SQLite JDBC driver.
Co ミミ ecti ミ g To DataHase
Following Java programs shows how to connect to an existing database. If database does not exist,
then it will be created and finally a database object will be returned.
import java.sql.*;
TUTORIALS POINT
Simply Easy Learning
$javac SQLiteJDBC.java
$java -classpath ".:sqlite-jdbc-3.7.2.jar" SQLiteJDBC
Open database successfully
If you are going to use Windows machine, then you can compile and run your code as follows:
$javac SQLiteJDBC.java
$java -classpath ".;sqlite-jdbc-3.7.2.jar" SQLiteJDBC
Opened database successfully
Create a TaHle
Following Java program will be used to create a table in previously created database:
import java.sql.*;
stmt = c.createStatement();
String sql = "CREATE TABLE COMPANY " + NOT NULL," +
"(ID
" NAMEINT PRIMARY KEY
TEXT NOT NULL, " +
" AGE INT NOT NULL, " +
" ADDRESS CHAR(50), " +
" SALARY REAL)";
stmt.executeUpdate(sql);
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Table created successfully");
}
}
When above program is compiled and executed, it will create COMPANY table in your test.db and
final listing of the file will be as follows:
INSERT Operatio ミ
Following Java program shows how we can create records in our COMPANY table created in above example:
import java.sql.*;
TUTORIALS POINT
Simply Easy Learning
public class SQLiteJDBC
{
public static void main( String args[] )
{
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " +
"VALUES (1, 'Paul', 32, 'California', 20000.00 );";
stmt.executeUpdate(sql);
stmt.close();
c.commit();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Records created successfully");
}
When above program is compiled and executed, it will create given records in COMPANY table and
will display following two line:
SELECT Operatio ミ
Following Java program shows how we can fetch and display records from our COMPANY table
created in above example:
import java.sql.*;
TUTORIALS POINT
Simply Easy Learning
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery( "SELECT * FROM COMPANY;" );
while ( rs.next() ) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
String address = rs.getString("address");
float salary = rs.getFloat("salary");
System.out.println( "ID = " + id );
System.out.println( "NAME = " + name );
System.out.println( "AGE = " + age );
System.out.println( "ADDRESS = " + address );
System.out.println( "SALARY = " + salary );
System.out.println();
}
rs.close();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully");
}
When above program is compiled and executed, it will produce the following result:
ID = 2
NAME = Allen
AGE = 25
ADDRESS = Texas
SALARY = 15000.0
ID = 3
NAME = Teddy
AGE = 23
ADDRESS = Norway
SALARY = 20000.0
ID = 4
NAME = Mark
AGE = 25
ADDRESS = Rich-Mond
SALARY = 65000.0
TUTORIALS POINT
Simply Easy Learning
UPDATE Operatio ミ
Following Java code shows how we can use UPDATE statement to update any record and then fetch
and display updated records from our COMPANY table:
import java.sql.*;
stmt = c.createStatement();
String sql = "UPDATE COMPANY set SALARY = 25000.00 where ID=1;";
stmt.executeUpdate(sql);
c.commit();
ID = 2
NAME = Allen
TUTORIALS POINT
Simply Easy Learning
AGE = 25
ADDRESS = Texas
SALARY = 15000.0
ID = 3
NAME = Teddy
AGE = 23
ADDRESS = Norway
SALARY = 20000.0
ID = 4
NAME = Mark
AGE = 25
ADDRESS = Rich-Mond
SALARY = 65000.0
import java.sql.*;
stmt = c.createStatement();
String sql = "DELETE from COMPANY where ID=2;";
stmt.executeUpdate(sql);
c.commit();
TUTORIALS POINT
Simply Easy Learning
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully");
}
}
When above program is compiled and executed, it will produce the following result:
ID = 3
NAME = Teddy
AGE = 23
ADDRESS = Norway
SALARY = 20000.0
ID = 4
NAME = Mark
AGE = 25
ADDRESS = Rich-Mond
SALARY = 65000.0
TUTORIALS POINT
Simply Easy Learning
CHAPTER
48
SQLite PHP Tutorial
Installation
Windows users must enable php_sqlite3.dll in order to use this extension. This DLL is included with
Windows distributions of PHP as of PHP 5.3.0.
For detailed installation instructions, kindly check our PHP tutorial and its official website.
Opens an SQLite 3 Database. If the build includes encryption, then it will attempt to use the
key.
If filename is actual device file name, SQLite3::open() attempts to open the database file
by using its value. If no file by that name exists then a new database file by that name gets
created.
Optional flags used to determine how to open the SQLite database. By default,
open uses SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE.
public bool SQLite3::exec ( string $query )
This routine provides a quick, easy way to execute SQL commands provided by sql
2 argument which can consist of more than one SQL command. This routine is used to
execute a result-less query against a given database.
TUTORIALS POINT
Simply Easy Learning
public SQLite3Result SQLite3::query ( string $query )
3
This routine executes an SQL query, returning an SQLite3Result object if the query returns
results.
public int SQLite3::lastErrorCode ( void )
4 This routine returns the numeric result code of the most recent failed SQLite request
6 This routine returns the number of database rows that were updated or inserted or deleted
by the most recent SQL statement
Co ミミ ecti ミ g To DataHase
Following PHP code shows how to connect to an existing database. If database does not exist,
then it will be created and finally a database object will be returned.
<?php
class MyDB extends SQLite3
{
function construct()
{
$this->open('test.db');
}
}
$db = new MyDB(); if(!
$db){
echo $db->lastErrorMsg();
} else {
echo "Opened database successfully\n";
}
?>
Now, let's run above program to create our database test.db in the current directory. You can
change your path as per your requirement. If database is successfully created, then it will give the
following message:
Create a TaHle
Following PHP program will be used to create a table in previously created database:
TUTORIALS POINT
Simply Easy Learning
<?php
class MyDB extends SQLite3
{
function construct()
{
$this->open('test.db');
}
}
$db = new MyDB(); if(!$db)
{
echo $db->lastErrorMsg();
} else {
echo "Opened database successfully\n";
}
$sql =<<<EOF
CREATE TABLE COMPANY
NOT NULL,
(ID
NAMEINT PRIMARY TEXT
KEY
NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL);
EOF;
When above program is executed, it will create COMPANY table in your test.db and it will display the
following messages:
INSERT Operatio ミ
Following PHP program shows how we can create records in our COMPANY table created in above example:
<?php
class MyDB extends SQLite3
{
function construct()
{
$this->open('test.db');
}
}
$db = new MyDB(); if(!
$db){
echo $db->lastErrorMsg();
} else {
echo "Opened database successfully\n";
}
$sql =<<<EOF
TUTORIALS POINT
Simply Easy Learning
INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Paul', 32, 'California', 20000.00 );
SELECT Operatio ミ
Following PHP program shows how we can fetch and display records from our COMPANY table
created in above example:
<?php
class MyDB extends SQLite3
{
function construct()
{
$this->open('test.db');
}
}
$db = new MyDB(); if(!
$db){
echo $db->lastErrorMsg();
} else {
echo "Opened database successfully\n";
}
$sql =<<<EOF
SELECT * from COMPANY;
EOF;
$ret = $db->query($sql);
while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
echo "ID = ". $row['ID'] . "\n";
echo "NAME = ". $row['NAME'] ."\n";
echo "ADDRESS = ". $row['ADDRESS'] ."\n";
echo "SALARY = ".$row['SALARY'] ."\n\n";
}
echo "Operation done successfully\n";
TUTORIALS POINT
Simply Easy Learning
$db->close();
?>
ID = 2
NAME = Allen
ADDRESS = Texas
SALARY = 15000
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000
UPDATE Operatio ミ
Following PHP code shows how we can use UPDATE statement to update any record and then fetch
and display updated records from our COMPANY table:
<?php
class MyDB extends SQLite3
{
function construct()
{
$this->open('test.db');
}
}
$db = new MyDB(); if(!
$db){
echo $db->lastErrorMsg();
} else {
echo "Opened database successfully\n";
}
$sql =<<<EOF
UPDATE COMPANY set SALARY = 25000.00 where ID=1;
EOF;
$ret = $db->exec($sql); if(!
$ret){
echo $db->lastErrorMsg();
} else {
echo $db->changes(), " Record updated successfully\n";
}
$sql =<<<EOF
SELECT * from COMPANY;
EOF;
TUTORIALS POINT
Simply Easy Learning
$ret = $db->query($sql);
while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
echo "ID = ". $row['ID'] . "\n";
echo "NAME = ". $row['NAME'] ."\n";
echo "ADDRESS = ". $row['ADDRESS'] ."\n";
echo "SALARY = ".$row['SALARY'] ."\n\n";
}
echo "Operation done successfully\n";
$db->close();
?>
When above program is executed, it will produce the following result:
ID = 2
NAME = Allen
ADDRESS = Texas
SALARY = 15000
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000
DELETE Operatio ミ
Following PHP code shows how we can use DELETE statement to delete any record and then fetch
and display remaining records from our COMPANY table:
<?php
class MyDB extends SQLite3
{
function construct()
{
$this->open('test.db');
}
}
$db = new MyDB(); if(!
$db){
echo $db->lastErrorMsg();
} else {
echo "Opened database successfully\n";
}
$sql =<<<EOF
DELETE from COMPANY where ID=2;
EOF;
$ret = $db->exec($sql);
TUTORIALS POINT
Simply Easy Learning
if(!$ret){
echo $db->lastErrorMsg();
} else {
echo $db->changes(), " Record deleted successfully\n";
}
$sql =<<<EOF
SELECT * from COMPANY;
EOF;
$ret = $db->query($sql);
while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
echo "ID = ". $row['ID'] . "\n";
echo "NAME = ". $row['NAME'] ."\n";
echo "ADDRESS = ". $row['ADDRESS'] ."\n";
echo "SALARY = ".$row['SALARY'] ."\n\n";
}
echo "Operation done successfully\n";
$db->close();
?>
When above program is executed, it will produce the following result:
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000
TUTORIALS POINT
Simply Easy Learning
CHAPTER
49
SQLite Perl Tutorial
Installation
T he SQLite3 can be integrated with Perl using Perl DBI module, which is a database access
module for the Perl programming language. It defines a set of methods, variables and conventions
that provide a standard database interface.
Here are simple steps to install DBI module on your Linux/UNIX machine:
$ wget http://search.cpan.org/CPAN/authors/id/T/TI/TIMB/DBI-1.625.tar.gz
$ tar xvfz DBI-1.625.tar.gz
$ cd DBI-1.625
$ perl Makefile.PL
$ make
$ make install
If you need to install SQLite driver for DBI, then it can be installed as follows:
$ wget http://search.cpan.org/CPAN/authors/id/M/MS/MSERGEANT/DBD-SQLite-1.11.tar.gz
$ tar xvfz DBD-SQLite-1.11.tar.gz
$ cd DBD-SQLite-1.11
$ perl Makefile.PL
$ make
$ make install
TUTORIALS POINT
Simply Easy Learning
test.db is the name of SQLite database file. If the filename is given as ':memory:', it
will create an in-memory database in RAM that lasts only for the duration of the
session.
If filename is actual device file name, then it attempts to open the database file by
using its value. If no file by that name exists then a new database file by that name
gets created.
You keep second and third paramter as blank strings and last parameter is to
pass various attributes as shown below in the example.
$dbh->do($sql)
This routine prepares and executes a single SQL statement. Returns the number of
2 rows affected or undef on error. A return value of -1 means the number of rows is
not known, not applicable, or not available. Here $dbh is a handle returned by DBI-
>connect() call.
$dbh->prepare($sql)
3 This routine prepares a statement for later execution by the database engine and
returns a reference to a statement handle object.
$sth->execute()
$sth->fetchrow_array()
5 This routine fetches the next row of data and returns it as a list containing the field
values. Null fields are returned as undef values in the list.
$DBI::err
6 This is equivalent to $h->err, where $h is any of the handle types like $dbh, $sth, or
$drh. This returns native database engine error code from the last driver method
called.
$DBI::errstr
7 This is equivalent to $h->errstr, where $h is any of the handle types like $dbh, $sth,
or $drh. This returns the native database engine error message from the last DBI
method called.
$dbh->disconnect()
8 This routine closes a database connection previously opened by a call to DBI-
>connect().
Co ミミ ecti ミ g To DataHase
Following Perl code shows how to connect to an existing database. If database does not exist,
then it will be created and finally a database object will be returned.
#!/usr/bin/perl
TUTORIALS POINT
Simply Easy Learning
use DBI;
use strict;
my $driver = "SQLite";
my $database = "test.db";
my $dsn = "DBI:$driver:dbname=$database";
my $userid = "";
my $password = "";
my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
or die $DBI::errstr;
$ chmod +x sqlite.pl
$ ./sqlite.pl
Open database successfully
Create a TaHle
Following Perl program will be used to create a table in previously created database:
#!/usr/bin/perl
use DBI;
use strict;
my $driver = "SQLite";
my $database = "test.db";
my $dsn = "DBI:$driver:dbname=$database";
my $userid = "";
my $password = "";
my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
or die $DBI::errstr;
print "Opened database successfully\n";
TUTORIALS POINT
Simply Easy Learning
NOTE: in case you see following error in any of the operation:
In this case you will have open dbdimp.c file available in DBD-SQLite installation and find out
sqlite3_prepare() function and change its third argument to -1 instead of 0. Finally install
DBD::SQLite using make and do make install to resolve the problem.
INSERT Operatio ミ
Following Perl program shows how we can create records in our COMPANY table created in above example:
#!/usr/bin/perl
use DBI;
use strict;
my $driver = "SQLite";
my $database = "test.db";
my $dsn = "DBI:$driver:dbname=$database";
my $userid = "";
my $password = "";
my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
or die $DBI::errstr;
print "Opened database successfully\n";
SELECT Operatio ミ
Following Perl program shows how we can fetch and display records from our COMPANY table
created in above example:
#!/usr/bin/perl
use DBI;
use strict;
TUTORIALS POINT
Simply Easy Learning
my $driver = "SQLite";
my $database = "test.db";
my $dsn = "DBI:$driver:dbname=$database";
my $userid = "";
my $password = "";
my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
or die $DBI::errstr;
print "Opened database successfully\n";
ID = 2
NAME = Allen
ADDRESS = Texas
SALARY = 15000
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000
UPDATE Operatio ミ
Following Perl code shows how we can use UPDATE statement to update any record and then fetch
and display updated records from our COMPANY table:
#!/usr/bin/perl
use DBI;
use strict;
TUTORIALS POINT
Simply Easy Learning
my $driver = "SQLite";
my $database = "test.db";
my $dsn = "DBI:$driver:dbname=$database";
my $userid = "";
my $password = "";
my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
or die $DBI::errstr;
print "Opened database successfully\n";
ID = 2
NAME = Allen
ADDRESS = Texas
SALARY = 15000
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000
TUTORIALS POINT
Simply Easy Learning
DELETE Operatio ミ
Following Perl code shows how we can use DELETE statement to delete any record and then fetch
and display remaining records from our COMPANY table:
#!/usr/bin/perl
use DBI;
use strict;
my $driver = "SQLite";
my $database = "test.db";
my $dsn = "DBI:$driver:dbname=$database";
my $userid = "";
my $password = "";
my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
or die $DBI::errstr;
print "Opened database successfully\n";
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000
TUTORIALS POINT
Simply Easy Learning
CHAPTER
50
SQLite Python
Installation
T he SQLite3 can be integrated with Python using sqlite3 module, which was written by
Gerhard Haring. It provides an SQL interface compliant with the DB-API 2.0 specification described
by PEP 249. You do not need to install this module separately because its being shipped by default
along with Python version 2.5.x onwards.
To use sqlite3 module, you must first create a connection object that represents the database and
then optionally you can create cursor object, which will help you in executing all the SQL
statements.
This API opens a connection to the SQLite database file database. You can use ":memory:"
to open a database connection to a database that resides in RAM instead of on disk. If
database is opened successfully, it returns a connection object.
When a database is accessed by multiple connections, and one of the processes modifies
1 the database, the SQLite database is locked until that transaction is committed. The timeout
parameter specifies how long the connection should wait for the lock to go away until
raising an exception. The default for the timeout parameter is 5.0 (five seconds).
If given database name does not exist then this call will create the database. You can
specify filename with required path as well if you want to create database anywhere else
except in current directory.
connection.cursor([cursorClass])
This routine creates a cursor which will be used throughout of your database programming
2
with Python. This method accepts a single optional parameter cursorClass. If supplied, this
must be a custom cursor class that extends sqlite3.Cursor.
TUTORIALS POINT
Simply Easy Learning
This routine executes an SQL statement. The SQL statement may be parameterized (i. e.
placeholders instead of SQL literals). The sqlite3 module supports two kinds of placeholders:
question marks and named placeholders (named style).
TUTORIALS POINT
Simply Easy Learning
connection.execute(sql [, optional parameters])
This routine is a shortcut of the above execute method provided by cursor object and it
4 creates an intermediate cursor object by calling the cursor method, then calls the cursor's
execute method with the parameters given.
cursor.executemany(sql, seq_of_parameters)
5 This routine executes an SQL command against all parameter sequences or mappings
found in the sequence sql.
connection.executemany(sql[, parameters])
6 This routine is a shortcut that creates an intermediate cursor object by calling the cursor
method, then calls the cursor.s executemany method with the parameters given.
cursor.executescript(sql_script)
This routine executes multiple SQL statements at once provided in the form of script. It
7 issues a COMMIT statement first, then executes the SQL script it gets as a parameter. All
the SQL statements should be separated by semi colon (;).
connection.executescript(sql_script)
8 This routine is a shortcut that creates an intermediate cursor object by calling the cursor
method, then calls the cursor's executescript method with the parameters given.
connection.total_changes()
9 This routine returns the total number of database rows that have been modified,
inserted, or deleted since the database connection was opened.
connection.commit()
10 This method commits the current transaction. If you don.t call this method, anything you did
since the last call to commit() is not visible from other database connections.
connection.rollback()
11 This method rolls back any changes to the database since the last call to commit().
connection.close()
12
This method closes the database connection. Note that this does not automatically call
commit(). If you
just close your database connection without calling commit() first, your changes will be lost!
cursor.fetchone()
13 This method fetches the next row of a query result set, returning a single sequence, or None
when no more data is available.
TUTORIALS POINT
Simply Easy Learning
cursor.fetchmany([size=cursor.arraysize])
14 This routine fetches the next set of rows of a query result, returning a list. An empty list is
returned when no more rows are available. The method tries to fetch as many rows as
indicated by the size parameter.
cursor.fetchall()
15 This routine fetches all (remaining) rows of a query result, returning a list. An empty list is
returned when no rows are available.
Co ミミ ecti ミ g To DataHase
Following Python code shows how to connect to an existing database. If database does not exist,
then it will be created and finally a database object will be returned.
#!/usr/bin/python
import sqlite3
conn = sqlite3.connect('test.db')
$chmod +x sqlite.py
$./sqlite.py
Open database successfully
Create a TaHle
Following Python program will be used to create a table in previously created database:
#!/usr/bin/python
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";
TUTORIALS POINT
Simply Easy Learning
ADDRESS CHAR(50),
SALARY REAL);''')
print "Table created successfully";
conn.close()
When above program is executed, it will create COMPANY table in your test.db and it will display the
following messages:
INSERT Operatio ミ
Following Python program shows how we can create records in our COMPANY table created in above
example:
#!/usr/bin/python
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";
conn.commit()
print "Records created successfully";
conn.close()
When above program is executed, it will create given records in COMPANY table and will display
the following two lines:
SELECT Operatio ミ
Following Python program shows how we can fetch and display records from our COMPANY table
created in above example:
#!/usr/bin/python
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";
ID = 2
NAME = Allen
ADDRESS = Texas
SALARY = 15000.0
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000.0
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000.0
UPDATE Operatio ミ
Following Python code shows how we can use UPDATE statement to update any record and
then fetch and display updated records from our COMPANY table:
#!/usr/bin/python
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";
TUTORIALS POINT
Simply Easy Learning
Opened database successfully
Total number of rows updated : 1
ID = 1
NAME = Paul
ADDRESS = California
SALARY = 25000.0
ID = 2
NAME = Allen
ADDRESS = Texas
SALARY = 15000.0
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000.0
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000.0
DELETE Operatio ミ
Following Python code shows how we can use DELETE statement to delete any record and
then fetch and display remaining records from our COMPANY table:
#!/usr/bin/python
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";
TUTORIALS POINT
Simply Easy Learning
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000.0
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000.0
TUTORIALS POINT
Simply Easy Learning