Unit 1
Unit 1
What is SQLite ?
SQLite is a software library that implements a self-contained, serverless, zero-configuration, transactional SQL
database engine.
It is self-contained, which means no external dependencies.
It is serverless, means SQLite does not require a separate server process or system to operate
It is zero-configured, which means like other databases you do not need to configure it in your system. SQLite is very
small and light weight, less than 400KB fully configured or less than 250KB with optional features omitted.
It is transactional means, SQLite transactions are fully ACID-compliant, allowing safe access from multiple
processes or threads
• SQLite supports most of the query language features found in SQL92 (SQL2) standard.
• SQLite is written in ANSI-C and provides simple and easy-to-use API.
• SQLite is available on UNIX (Linux, Mac OS-X, Android, iOS) and Windows (Win32, WinCE, WinRT).
• The source code for SQLite is in the public domain.
SQLite Advantages
1) Lightweight: SQLite is a very light weighted database so, it is easy to use it as an embedded software with
devices like televisions, Mobile phones, cameras, home electronic devices, etc.
2) Better Performance: Reading and writing operations are very fast for SQLite database. It is almost 35%
faster than File system. It only loads the data which is needed, rather than reading the entire file and hold it in
PREPARED BY: SHREYA PATEL, CBPCC
DATABSE: UNIT 1
memory.
3) No Installation Needed: You don’t need to install and configure it. Just download SQLite libraries in your
computer and it is ready for creating the database.
4) Reliable: It updates your content continuously so, little or no work is lost in a case of power failure or crash.
SQLite is less bugs prone rather than custom written file I/O codes.
5) Portable: SQLite is portable across all 32-bit and 64-bit operating systems and big- and little-endian
architectures. It can be used with all programming languages without any compatibility issue
6) Accessible: SQLite database is accessible through a wide variety of third-party tools.
7) Reduce Cost and Complexity: It reduces application cost because content can be accessed and updated
using concise SQL queries instead of lengthy and error-prone procedural queries.
SQLite Disadvantages
o SQLite is used to handle low to medium traffic HTTP requests.
o Database size is restricted to 2GB in most cases.
• When you declare a column with a specific data type, that column can store only data of the declared
data type. It is called static typing.
• SQLite uses dynamic type system. SQLite uses a dynamic typing technique also known as Manifest
Typing.
• Manifest typing means that a data type is a property of a value stored in a column, not the property of
the column in which the value is stored.
• SQLite uses manifest typing to store values of any type in a column.
• You don’t have to declare a specific data type for a column when you create a table.
• In case you declare a column with the integer data type, you can store any kind of data types such as
text and BLOB, SQLite will not complain about this.
• Type affinity determines the storage class.
• In SQLite, type affinity is used to store the values within a column, and the declared type of column
determines the type affinity of a column.
• However, you still can store any type of data as you wish; these types are recommended but not
required.
• SQLite provides five primitive data types which are referred to as storage classes.
Following table lists down various data type names which can be used while creating SQLite3 tables with the
corresponding applied affinity.
• INT
• INTEGER
• TINYINT
• SMALLINT
INTEGER
• MEDIUMINT
• BIGINT
• UNSIGNED BIG INT
• INT2
• INT8
• CHARACTER(20)
VARCHAR(255)
• VARYING CHARACTER(255)
• NCHAR(55) TEXT
• NATIVE CHARACTER(70)
• NVARCHAR(100)
• TEXT
• CLOB
PREPARED BY: SHREYA PATEL, CBPCC
DATABSE: UNIT 1
• BLOB NONE
• no datatype specified
• REAL
• DOUBLE REAL
• DOUBLE PRECISION
• FLOAT
• NUMERIC
• DECIMAL(10,5)
NUMERIC
• BOOLEAN
• DATE
• DATETIME
NULL: A NULL is considered its own distinct type. A NULL type does not hold a value. It is represented by
the NULL keyword and it only holds NULL.
INTEGER: The value is a signed integer numbers (8-byte length). Integer values are whole numbers i.e. it
may be positive or negative. They can vary in size: 1, 2, 3, 4, 6, or 8 bytes. We can store a number roughly up
to 19 digits long.
REAL: A floating-point number, stored as an 8-byte value that contains a decimal point or exponent.
Text: Text values are variable-length character data. Text values are represented as characters enclosed within
single quotes. The maximum string value in SQLite is unlimited.
BLOB: A BLOB value is variable-length raw bytes. BLOB (Binary Large Object) data is any kind of data.
The maximum BLOB value in SQLite is unlimited.
In SQLite, each table column must have one of five type affinities.
Text: A column with this affinity can only store TEXT, NULL or BLOB value. If you store INTEGER in this
affinity, then it is converted to text value type.
Numeric: A column with a numeric affinity will store any of the five types. Values with integer and float
types, along with NULL and BLOB types, are stored without conversion.
Integer: A column with an integer affinity works essentially the same as a numeric affinity. If you store float
value, then it is converted to an integer type.
Float: A column with a floating-point affinity also works essentially the same as a numeric affinity. The only
difference is if you store integer value then it is converted to floating value.
None: A column with none affinity has no preference over storage class. It is called as BLOB affinity.
1. By default, a column’s default affinity is NUMERIC. That is, if a column is not INTEGER, TEXT, or
NONE, then it is automatically assigned NUMERIC affinity.
2. If a column’s declared type contains the string 'INT' or ‘int’, then the column is assigned INTEGER affinity.
3. If a column’s declared type contains any of the strings 'CHAR', 'BLOB', or ‘TEXT’, then that column is
assigned TEXT affinity. Note that 'VARCHAR' contains the string 'CHAR' and thus will give TEXT affinity.
4. If a column’s declared type contains the string 'BLOB', or if it has no declared type, then it is assigned
NONE affinity.
Each affinity influences how values are stored in its associated column. The rules of principal storage are as
follows.
1. A NUMERIC column may contain all five storage classes. If you try to insert TEXT value in a NUMERIC
column, it will first attempt to convert it into an INTEGER storage class. If it fails to convert, then it stores this
using the TEXT storage class.
2. An INTEGER column tries to behave much like a NUMERIC column. If you try to insert REAL value in
PREPARED BY: SHREYA PATEL, CBPCC
DATABSE: UNIT 1
the INTEGER column, then it will store it as REAL only. However, if REAL does not have a fractional part
then it will be stored as an INTEGER. INTEGER column tries to store TEXT as REAL if possible. If not, then
try to store as INTEGER. If it fails, then it will store it as TEXT.
3. A TEXT column will convert all INTEGER or REAL values to TEXT.
4. A NONE column does not attempt to convert any values.
5. No column will ever try to convert NULL or BLOB values not considering affinity. NULL and BLOB
values are always stored as is in every column.
SQLite does not support data types like Boolean. Instead, Boolean values are stored as integers 0 (false) and 1
(true).
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.
You can choose to store dates and times in any of these formats and freely convert between formats using the
built-in date and time functions. SQLite does not support data type for storing DATE/TIME. For that SQLite
provide a small set of date & time conversion function that will store it as either TEXT or INTEGER.
SQLite includes three special keywords that may be used as a default value: CURRENT_TIME,
CURRENT_DATE, and CURRENT_TIMESTAMP.
We will see how to use these keywords with examples. Following is the example of using the
CURRENT_TIME keyword.
When we run the above SQLite statement we will get a result like as shown below.
CURRENT_TIME typeof(CURRENT_TIME)
------------ --------------------
07:35:04 text
Now we will see how to use the CURRENT_DATE keyword with example.
When we run the above SQLite query we will get a result like as shown below
CURRENT_DATE typeof(CURRENT_DATE)
------------ --------------------
2016-08-05 text
Now we will see how to use the CURRENT_TIMESTAMP keyword with example.
SELECT CURRENT_TIMESTAMP,typeof(CURRENT_TIMESTAMP);
When we run the above SQLite query we will get a result like as shown below.
CURRENT_TIMESTAMP typeof(CURRENT_TIMESTAMP)
------------------- -------------------------
2016-08-05 07:35:37 text
This is how we can use data types in SQLite queries based on our requirements.
Generally, in SQLite transaction means it’s a set of T-SQL statements that will execute together as a unit like a
single T-SQL statement. If all these T-SQL statements executed successfully without having any errors then
the transaction will be committed and all the changes made by the transaction will be saved to the database
permanently. In case, if any error occurred while executing these SQLite statements then the complete
transaction will be rollbacked.
Generally, the SQLite is in an auto-commit mode that means SQLite automatically starts a transaction for each
command, process, and commit the transaction changes automatically to the database.
In case if we want to control these transactions to maintain data consistency and to handle database errors then
by using following commands we can disable auto-commit mode and explicitly start the transactions based on
our requirements.
The BEGIN command is used to start or open a transaction. Once an explicit transaction has been opened, it
will remain open until it is committed or rolled back.
Following is the syntax of the SQLite BEGIN command.
BEGIN;
or
BEGIN [TRANSACTION];
The COMMIT command is used to close out the current transaction and commit the changes to the database.
We can also use the alias END.
COMMIT [TRANSACTION]
or
END [TRANSACTION]
Once the COMMIT command executed successfully then all the changes are saved to the database and
become visible to other clients.
The data in the database will contain all the changes made during the transaction even if there are power
problems or the system failure once COMMIT commands executed successfully.
By using ROLLBACK command we can cancel the transaction and roll back all the proposed changes.
ROLLBACK
or
ROLLBACK [TRANSACTION]
The ROLLBACK command will revert all the proposed changes made by the current transaction and then
close the transaction
Both COMMIT and ROLLBACK will end the current transaction, putting SQLite back into Autocommit mode
Save Points:
In SQLite, savepoints are useful to mark specific points in the transaction. By using these savepoints we can
rollback or accept the changes to particular save-points in transaction based on our requirements.
We can create more than one save-point in transaction based on our requirements and sometimes we will call
savepoints are the nested transactions because we will create savepoints within the transaction to rollback or
commit changes to particular savepoint within the transaction.
Generally, these savepoints are useful with large or multi-step transactions because we can rollback
transactions to particular step or savepoint based on our requirements.
Following is the SQLite SAVEPOINT syntax to create a new savepoint with new name.
SAVEPOINT savepoint_name
By using SQLite RELEASE command we can release a save-point and accept all the changes made since the
savepoint was set.
By using the ROLLBACK command we can cancel the transaction and undo everything back to where save-
PREPARED BY: SHREYA PATEL, CBPCC
DATABSE: UNIT 1
Unit 1.2.1 Filtering: Distinct, where, between, in, like, Union, intersect, Except, Limit, IS NULL
The SQLite DISTINCT clause is used with SELECT statement to eliminate all the duplicate records and
fetching only unique records. It is used when you have multiple duplicate rows in a table.
Syntax:
Example:
The SQLite WHERE clause is generally used with SELECT, UPDATE and DELETE statements to specify
condition while you fetch the data from tables. If condition is satisfied it returns specific value from the table.
WHERE clause is used to filter the records and fetching only necessary records.
Syntax:
SELECT COLUMN…
FROM TABLE
WHERE CONDITION;
We can use where clause with different logical and comparison operators such as <, >, <=, >=, =, IN, LIKE,
BETWEEN, NOT etc.
Example:
It is used to get the records that falls within the specified range. BETWEEN operator can be used
with SELECT, UPDATE and DELETE statements.
Syntax:
SELECT COLUMN…
FROM TABLE
WHERE column_exp BETWEEN val1 and val2;
Here,
PREPARED BY: SHREYA PATEL, CBPCC
DATABSE: UNIT 1
Example:
We can also use between operator with dates to get records within particular date range.
We can also use NOT operator with BETWEEN operator, then it will return the records that does not fall
within the given range.
Example:
SQLite IN operator
In SQLite IN operator is used to determine whether the given value matching with subquery returned
result set values or list of given values.
Syntax:
SELECT COLUMN…
FROM TABLE
WHERE column_exp IN (val1, val2, …., valn);
OR
SELECT COLUMN…
FROM TABLE
WHERE column_exp IN (subquery);
The above sqlite in operator syntax will check whether the given expression value matching with the list of
values (val1, val2, etc.) or not.
Example:
In SQLite, LIKE operator is used to check whether the given string value matches with specific
pattern or not. In case if string value matches with pattern value then it will return true. In SQLite
LIKE operator is a case insensitive, so 'a' LIKE 'A' is true and all non-NULL parameter expressions
will be converted to text values.
Syntax:
SELECT COLUMN…
FROM TABLE
WHERE column_exp LIKE pattern;
In above SQLite LIKE syntax, we defined few properties with a LIKE operator in a select statement those are
expression - A character expression such as a column or field.
pattern - A character expression that contains pattern matching.
In SQLite LIKE operator pattern syntax supports two wildcards.
The above SQLite LIKE operator example returns employees whose first name starts with ‘s’ or ‘S’ character.
The above SQLite LIKE operator example return employees who’s last_name contains ‘n’ or ‘N’ character.
In SQLite UNION operator is used to combine the result sets of 2 or more SELECT statements and it removes
duplicate rows between the various SELECT statements. The SELECT statements which we used with the UNION
operator must have the same number of fields in the result sets with similar data types. Syntax of SQLite Union
Operator Following is the syntax of SQLite UNION operator to combine multiple select statement result sets and
return unique records.
UNION
• expression1, expression2, ... expression_n - The columns or calculations that you wish to retrieve.
• tables - The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause.
• WHERE conditions - Optional. The conditions that must be met for the records to be selected
PREPARED BY: SHREYA PATEL, CBPCC
DATABSE: UNIT 1
While using SQLite UNION operator its important to note that all the SELECT statements must contain the same
number of columns or expressions with the same data type and that columns order also must be the same.
The SQLite UNION operator by default removes all duplicate rows from the result set and the column names from the
first SELECT statement in the UNION operator are used as the column names for the result set.
Example
SELECT dept_id
FROM dept_master
UNION
SELECT dept_id
FROM emp_master;
If you observe the above example SQLite UNION operator removed duplicate rows from the result set.
Generally, the SQLite UNION operator will combine multiple select statement result sets and return unique records.
So, if we want to use Order By clause with UNION operator we need to define Order By at the end of last Select
statement.
SELECT dept_id
FROM dept_master
UNION
SELECT dept_id
FROM emp_master
Order by dept_id;
In SQLite UNION ALL operator is used to combine the result sets of 2 or more SELECT statements and it will return
all the rows including duplicates. The SELECT statements which we used with UNION ALL operator must have the
same number of fields in the result sets with similar data types. Syntax of SQLite Union ALL Operator Following is
the syntax of SQLite UNION ALL operator to combine multiple select statement result sets and return all records
including duplicates.
Syntax
While using SQLite UNION ALL operator it’s important to note that all the SELECT statements must contain the
same number of columns or expressions with the same data type and that columns order also must be the same. The
SQLite UNION ALL operator will use column names from the first SELECT statement as the column names for the
result set.
Example
SELECT dept_id
FROM dept_master
UNION ALL
PREPARED BY: SHREYA PATEL, CBPCC
DATABSE: UNIT 1
SELECT dept_id
FROM emp_master;
If you observe the above example SQLite UNION ALL operator returned all the records from both the select
statements including duplicate records.
In SQLite, an Intersect operator is useful to get only matching rows from two or more select statements. Suppose if we
use Intersect operator with two SQLite Select statements then it will return only the records which exist in both Select
statement result sets. Generally, we use SQLite Intersect operator with Select statements and all the Select statements
which are using with Intersect operator must have the same number of fields.
INTERSECT
If you observe above SQLite Intersect operator syntax we defined two Select statements with Intersect operator. Here
SQLite Intersect operator will return only matching rows from both Select statements. In the above Intersect operator
syntax, we defined some of the properties that are
SELECT dept_id
FROM dept_master
INTERSECT
SELECT dept_id
FROM emp_master;
In case if we have multiple columns in SQLite Select statement then the Intersect operator will use all the columns of
the first Select statement to compare values with the second Select statement. Following is the example of using
SQLite Intersect operator with multiple columns in Select statement.
SELECT dept_id, dept_name
FROM table1
INTERSECT
SELECT dept_id, dept_name
FROM table2;
FROM table-list
[WHERE condition]
EXCEPT
SELECT column1, column2,..., columnn
FROM table-list
[WHERE condition];
If you observe above SQLite Except operator syntax we defined two Select statements with Except operator. Here
SQLite Except operator will return rows from first Select statement which does not exist in the second Select
statement. In above Except operator syntax, we defined some of the properties that are
SELECT dept_id
FROM dept_master
EXCEPT
SELECT dept_id
FROM emp_master ;
When we run above sqlite Except operator query it will return dept_id from dept_master table which are not exists in
emp_master table.
In SQLite LIMIT clause is used to set a limit to the records returned by select statement. Generally, the SQLite LIMIT
clause is used with SELECT statement to retrieve rows from one or more tables in SQLite and limit the number of
records returned based on a limit value. In SQLite LIMIT clause will define the maximum number of rows returned by
select statement.
Following is the syntax of using SQLite LIMIT clause with SELECT Statement.
SELECT expressions
FROM tables-list
[WHERE conditions]
LIMIT number_rows
OFFSET offset_value;
The above SQLite LIMIT clause syntax is having few properties those are
Suppose if you want to get 5 records starting from 5th row of result set then we need to define offset_value as 5 then
our LIMIT clause start picking rows from 5th position.
The above SQLite LIMIT clause in a select statement will return the first five records of the emp_master table.
PREPARED BY: SHREYA PATEL, CBPCC
DATABSE: UNIT 1
In SQLite Limit clause the optional OFFSET specifies how many rows to skip at the beginning of the result set.
Following is the example of the SQLite LIMIT clause with OFFSET in Select statement.
It will skip first record and after only 4 records are displayed.
Notice that the OFFSET value defines how many rows are skipped, not the position of the first row.
Generally, all relational databases will support a special value called NULL and it is used to represent missing
information. If table has Null value, then it will display as blank. The Null value represents represent the absence of a
value or empty or no value. By using the NULL keyword, we can represent NULL or empty string values.
For illustrating NULL value in SQLite, we take the example of a Person table which is having records like as shown
below.
Now, we will try to get persons whose phone number is NULL from the Person table. So we will execute the
following SQLite query.
When we run above SQLite query it won’t return any rows because here we are comparing phone_no = NULL. Here
NULL is not TRUE or FALSE so no rows will be returned by the query in its current form. So, to get records of a
person whose phone number is NULL then we have to use IS operator with NULL as follows:
In SQLite, the IS operator properly checks for a NULL and returns true records if it finds.
In SQLite, if you want to get values that are not NULL, then use IS NOT NULL. Following is the example of using
SQLite Is Not NULL to get rows which are not containing any NULL values.
Unit 1.2.2 Having, Group by, Order by, Conditional Logic (CASE)
In SQLite GROUP BY clause is used to aggregate data into a single row where the value of one or more specified
columns is repeated. This feature can be used to reduce the number of records to only find unique values of a column.
Following is the syntax of using GROUP BY in the SELECT statement.
SELECT result
FROM [table-list]
GROUP BY [expr-list]
If you observe above SQLite Group By syntax it contains few properties those are
In SQLite GROUP BY clause takes a list of expressions usually column names from the result.
The grouping process has two steps. First, the GROUP BY expression list is used to arrange table rows into different
groups. Once the groups are defined, the SELECT defines how those groups are flattened down into a single row.
The sum function is used to add particular data values. We can say that it is used to perform summation. We will
understand this concept using the example of emp_master table.
sqlite> SELECT * FROM emp_master;
Now, If you want to know the total amount of salary on each employee, then GROUP BY query would be like as
shown below.
When we run above SQLite Group By query we will get a result like as shown below.
first_name SUM(salary)
---------- -----------
Honey 10100
Jagruti 9500
Shweta 19300
Vinay 35100
Now, consider that emp_master table contains two employees with the same name as follows:
sqlite> SELECT *
FROM emp_master;
If you observe the above result we have two users having the same first_name (shweta). Now, if we fire SQLite Group
By query then the result would be different because it takes two employees who are having the same name as one
group. So, we will fire the same query and examine the result that would be like as shown below:
first_name SUM(salary)
---------- -----------
Honey 10100
Jagruti 9500
Shweta 31300
Vinay 3510
Count is used to count the total number of rows in a select query. We will see how to use SQLite Group By with count
function for that just change the above query a little bit and add count(first_name) in SELECT like as shown below.
When we run above query we will get result like as shown below.
If you observe the above result, it counts how many employees are having the same first_name in the emp_master
table. The only difference between count and count(*) is that count(col_name) ignores NULL values but count(*) does
not. Let us take the same example that we discussed while understating the NULL value concept.
As you can see 2 person has null in their phone_no. now if I execute the following query-
Count(phone_no)
----------------------
4
Count(*)
----------------------
6
This is because count() ignores NULL values but count(*) does not.
Min and Max are used to find minimum and maximum data value respectively, in the table. Now, we will get a
minimum and maximum salary for all the departments by using SQLite Group By statement.
Now write the following query to get the minimum and maximum salary of the department by using SQLite Group By
clause
min(e.salary) max(e.salary)
------------- ------------- ------------
10100 13000
9500 19300
12000 50000
Functionally in SQLite HAVING clause is identical to the WHERE clause. The SQLite HAVING clause is a further
condition applied after aggregation takes place along with a group by in select statement. Generally, in the SQLite
WHERE clause, which applies a condition to individual elements in a table and HAVING clause is used to add filter
conditions based on the groups created by Group By clause. Always we need to use SQLite HAVING clause with
GROUP BY otherwise, it will act as a WHERE clause. In SQLite, the GROUP BY clause will group rows into a set of
groups and the HAVING clause will apply filters on groups based on specified conditions.
Following is the syntax of using the SQLite HAVING clause with a select statement.
SELECT result
FROM [table-list]
HAVING [expr]
If you observe above SQLite Having statement, we defined multiple properties those are
Let ‘s see the example for having clause using emp table data.
first_name, count(first_name)
------------- ---------------------
Shweta 2
This will display only those employees whose name appear in table more than once.
Suppose if I want to find out the dept_id where there are more then 2 employees, then we have to execute following
query.
First_name dept_id
Shweta 2
Jagruti 2
Yamini 2
Vinay 3
Shweta 3
Khyati 3
Order By Clause
In SQLite ORDER BY clause is used to sort column records either in ascending or descending order. Generally, the
SQLite tables will store data in unspecified order and it will return records in the same unspecified order while
fetching data using SQLite select statement. In SQLite, by using Order By clause we can sort SQLite select statement
result set either in ascending or descending order based on our requirement. Following is the syntax of using the
ORDER BY clause with a select statement to sort column records.
SELECT expressions
FROM tables-list
[WHERE conditions]
ORDER BY column1, column2,... [ ASC | DESC ];
In above SQLite Order By clause syntax, we defined few properties those are
If no modifier is provided with the ORDER BY clause, then by default it will sort the result set in ascending order.
Now let us take an example to understand this.
sqlite> SELECT *
FROM emp_master;
Now, let’s look at the example of the SQLite ORDER BY clause in Select statement to sort employees based on their
salary in descending order.
SELECT * FROM
emp_master
ORDER BY SALARY DESC;
If you observe above SQLite Order By clause we added ORDER BY SALARY DESC to sort emp_master table
records based on salary in descending order. When we run the above query, we will get result set in which employees
whose salary is highest will display on top like as shown below.
Now let’s look at the example of sorting with relative position. You can also use ORDER BY clause to sort the result
set by relative position in which the first field in the result set is 1. The next field is 2, and so on.
In the above SQLite Select Order By statement we defined ORDER BY 2 DESC so it will sort table records based on
the second field (first_name) in descending order. The following is the result of the above query.
last_name first_name
---------- ----------
Patel Yamini
Jariwala Vinay
Menpara Sonal
Jariwala Shweta
Rana Shweta
Shah Khyati
Viras Jagruti
Patel Honey
Now let’s look at the example of SQLite Order by multiple columns in the select statement. Suppose if you want to
sort one column in ascending order and another column in descending order then by using SQLite Order By clause in
a select statement we can achieve this functionality. We need to write the query like as shown below.
PREPARED BY: SHREYA PATEL, CBPCC
DATABSE: UNIT 1
SELECT *
FROM emp_master
ORDER BY SALARY DESC, dept_id ASC;
The above SQLite Order By query will sort records based on SALARY and dept_id columns and the result will be
like as shown below.
This is how we can use SQLite Order By clause to sort table records either in ascending or descending based on our
requirements.
In SQLite CASE statement is like an if...then...else condition in other programming languages or like C Language
switch statements. Generally, the SQLite Case statement contains an optional expression followed by one or more
WHEN ... THEN clauses and it is finished with an optional ELSE clause and a required END keyword. In SQLite we
can use Case statement with Select, Update, Delete, Where, Order By, Having clauses to get required values by
defining multiple conditions based on our requirement.
CASE test_expression
WHEN [condition.1] THEN [expression.1]
WHEN [condition.2] THEN [expression.2]
...
WHEN [condition.n] THEN [expression.n]
ELSE [expression]
END
In the above SQLite Case Statement syntax, we defined multiple conditions to get the required values. Here in SQLite
Case statement each WHEN. .. THEN clauses evaluated in an orderly manner. First, it evaluated condition 1 in case if
it satisfied then it returns expression 1 otherwise it will execute condition 2 and so on. If no condition is satisfied, then
finally execution goes to ELSE block, and expression under ELSE is evaluated. Let’s understand this with an example
of student table.
sqlite> SELECT *
FROM STUDENT;
Following is the example of using the SQLite Case Statement with Select query.
In the above SQLite Case statement example, we added multiple conditions using a case statement to get Grade of the
student based on the marks. In this example first, it checks that marks greater than 80 if so then it will print grade
“A+”, if not it will check whether marks greater than 70 if so then it will print grade “A”, if not then it checks for
marks greater than 60 if so then it will print grade “B” and not then it checks for marks greater than 50 if so then it
will print grade “C” and if no condition satisfy then it will print “Sorry!! Failed”. Now we will run and check the
result of the above query that will be like as shown below.
This is how we can use the SQLite Case statement in our Select or Update statements based on our requirements.
Unit 1.3 SQLite joins: Inner, left, cross, self, Full outer joins
In SQLite, joins are used to get result set by combining or joining two or more tables. By using the JOIN clause, we
can join multiple tables together and get records based on our requirements. Suppose in SQLite we have two tables
(Employees, Departments) and both tables is having common column called DepartmentId and if we want to get
Employee details who are mapped to department then by using Joins in SQLite we can easily get it.
In SQLite, Joins are the best way to combine and get records from multiple tables. Generally, in SQLite each JOIN
operator will combine two tables into another table. In case if we have three or more tables then those tables can be
joined by using multiple JOIN operators in SQLite statements.
• Inner Join
• Outer Join
• Cross Join
• Self Join
Inner Join - In SQLite inner joins are used to return only matching records from tables based on the defined
conditions.
Outer Join - In SQLite outer joins are used to return records from tables even if defined conditions not satisfying.
Generally, we have three types of outer joins available those are Left Outer Joins, Right Outer Joins and Full Outer
Joins but SQLite will support only Left Outer Joins.
Cross Join - In SQLite cross joins are used to get the Cartesian product of tables.
PREPARED BY: SHREYA PATEL, CBPCC
DATABSE: UNIT 1
Self Join - In SQLite self join is used to join the same table. SQLite Inner Join In
It is used to combine and return only matching records from multiples tables based on the conditions defined in
SQLite statements. Generally, the SQLite Inner Join will return intersection elements of multiple sets i.e, only the
common matching elements from multiple sets. Suppose if we have two sets {6, 4, 2, 3} and {8, 2, 5, 6} for these sets’
intersection will return {2, 6} because only {2,6} are common elements in both sets. Following is the pictorial
representation of two sets {6, 4, 2, 3} and {8, 2, 5, 6} intersection operation.
If you observe the above diagram, we got only common elements in intersection same way SQLite inner join will
return only common or matching rows from multiple tables. In SQLite, Inner Join is the most common and default
type of JOIN. If we define JOIN in sqlite query automatically it will consider as an Inner Join.
Here INNER keyword is optional to use and it returns only the rows which are common or matched in both tables.
Now we will see the example of SQLite INNER JOIN with the database table. We need two tables dept_master and
emp_master.
dept_id dept_name
---------- ----------
1 Admin
2 Sales
3 Quality Control
4 Marketing
Now write SQLite query like as shown following to use INNER JOIN with a select statement.
If you observe above SQLite INNER JOIN query we are joining dept_master and emp_master tables and applied Inner
Join on dept_id column to get only employees whose dep_id equals with dept_id in department table. Now we will run
and see the result of SQLite Inner Join example. Following is the result of SQLite INNER JOIN example.
Here in above example, there is no employee from Marketing department that's the reason marketing department
records are not included in the result.
In SQLite, CROSS JOIN is used to get the Cartesian product of rows by matching each row of the first table with
every row of the second table.
By using the CROSS JOIN keyword in SQLite statements we can get the result which contains a combination of all
the rows from the first table with all the rows of the second table.
In SQLite Cross join resultant table will contain multiplication number of rows in input tables. Suppose if table1
contains 10 rows and table2 contains 5 rows then if we apply Cross Join on these two tables we will get a resultant
table that contains 50 rows.
SELECT *
FROM table1 CROSS JOIN table2
If you observe above SQLite Cross Join syntax we used CROSS JOIN keyword with tables table1, table2 to get
Cartesian product result.
Lets understand this with the same emp_master and dept table example.
dept_id dept_name
---------- ----------
1 Admin
2 Sales
3 Quality Control
4 Marketing
This is the data from both the tables. Now lets apply cross join on these data.
SELECT dept_name,emp_id,first_name
FROM dept_master CROSS JOIN emp_master;
When we run above SQLite Cross Join query we will get a result like as shown below.
Marketing 4 Jagruti
Marketing 5 Shweta
Marketing 6 Sonal
Marketing 7 Yamini
Marketing 8 Khyati
Marketing 9 Shwets
If you observe above result all the rows of dept_master table matched with all the row of emp_master and returned
Cartesian product of dept_master and emp_master tables.
In SQLite, by using Inner Join we can get only matching rows from multiple tables based on the conditions defined in
select statements. If we use SQLite Outer Join it will select matching rows from multiple tables same as Inner Join and
some other rows outside of the relationship.
In simple terms we can say SQLite OUTER JOIN is an addition of INNER JOIN. Generally we have three types of
Outer Joins in SQL standard those are LEFT, RIGHT and FULL Outer Joins but SQLite supports only LEFT OUTER
JOIN
Following is the syntax of using SQLite Left Outer Join with Select statement.
SELECT t1.col1,t2.col2,...
FROM table1 t1 LEFT OUTER JOIN table2 t2
ON t1.col3=t2.col5 ;
In the above SQLite Left Outer Join, table1 is a left-hand table, and table2 is a right-hand table. Here the left outer join
tries to match every row of table1 table with every row in table2 table based on the join condition (t1.col3 = t2.col5)
and it returns matching rows from both the tables and remaining rows of table1 table that doesn't match with table2
table are also included in the result.
Lets understand this with the same emp_master and dept table example.
dept_id dept_name
---------- ----------
1 Admin
2 Sales
3 Quality Control
4 Marketing
This is the data from both the tables. Now lets apply LEFT OUTER join on these data.
Now write SQLite query like as shown following to use Left Outer JOIN with a select statement.
SELECT d.dept_id,dept_name,emp_id,first_name
FROM dept_master d LEFT OUTER JOIN emp_master e
ON d.dept_id=e.dept_id;
If you observe above SQLite Left Outer Join example, we defined Left Join condition on the dept_id column of tables.
Now we will run and check the output that will be like as shown following.
Here dept_master is a left-hand table so all the rows of the dept_master table included in the result even though rows
are unmatched and it included only matched rows of emp_master table. In emp_master table, we don't have any
employee for the marketing department so in result emp_id and first_name are null.
In SQLite Self Join is used to join the same table with itself. To use SQLite Self Join we need to create different alias
names for the same table to perform operations based on our requirements. Suppose if we need to compare columns in
same table then Self Join will help us to achieve our functionality.
For example, we have a table called Employees with three columns Employee Id, Employee Name, Manager Id and
we want to get the Employees who are managers in this situation we need to join Employees table with itself.
Following is the syntax of using SQLite Self Join with Select statement.
If you observe above SQLite Self join syntax, we have given alias to table1 as x and y and used same field of table1
table for comparison.
Here, the manager_id column is a self-reference to emp_id in the emp_master table. Now write SQLite query like as
shown following to use Self Join with a select statement to get employees manager details.
SELECT x.emp_id, x.first_name as Employee, y.emp_id as 'Manager ID', y.first_name as 'Manager Name'
FROM emp_master x, emp_master y
WHERE x.manager_id = y.emp_id;
If you observe the above example, we used the emp_master table twice with different alias names (x, y) to get a list of
employees with their manager’s details. Result of SQLite Self Join Query Following is the result of the above SQLite
self-join query.
This is how we can use SQLite self join query to get details based on our requirements
In theory, the result of the FULL OUTER JOIN is a combination of a LEFT JOIN and a RIGHT JOIN. The result set
of the full outer join has NULL values for every column of the table that does not have a matching row in the other
table. For the matching rows, the FULL OUTER JOIN produces a single row with values from columns of the rows in
both tables. The following picture illustrates the result of the FULL OUTER JOIN clause. Unfortunately, SQLite does
not support the RIGHT JOIN clause and also the FULL OUTER JOIN clause. However, you can easily emulate the
FULL OUTER JOIN by using the LEFT JOIN clause.
Unit 1.4.1 Concepts of Trigger, Before and After trigger (on Insert , Update, Delete)
In SQLite trigger is a database object and it will raise automatically whenever an insert, update and delete operations
performed on a particular table or view in the database. Generally, in SQLite triggers are specific to the particular
table so those triggers will raise automatically whenever we perform any operations like insert, update or delete on
that particular table.
The triggers in SQLite will help us to maintain the data integrity on the database and these triggers will raise
automatically to perform defined rules to prevent invalid transactions BEFORE or AFTER INSERT, UPDATE, or
DELETE operations. In SQLite triggers are specific to a particular table so the triggers are dropped automatically
when the associated table dropped.
If you observe the above syntax we defined multiple parameters to create trigger we will learn all the parameters in
detail.
• IF NOT EXISTS – It’s Optional and it will prevent throwing error in case if we try to create an existing
• trigger. Trigger_name – Its name of the trigger which we are going to create.
• [BEFORE|AFTER|INSTEAD OF] – It will determine when the trigger action can be performed is it BEFORE
or AFTER or INSTEAD OF the event.
• [INSERT|UPDATE|DELETE] – It will determine in which action triggers can be invoked such as INSERT,
UPDATE or DELETE.
• table_name – Its name of the table on which we are going to create trigger.
• [FOR EACH ROW] – will check the trigger condition for each row.
• Trigger_action_body – It contains SQLite statements which will execute whenever the trigger action
performed.
Now we will see how to use triggers with examples for that create new tabled called “Product” using the following
statements.
Now we will create a trigger (trg_validate_products_before_insert) on the “Product” table to raise before insert of any
data using the following statements.
In above statement, we used a NEW reference to access quantity and amount columns and added validation to check
quantity and amount values while inserting a new row.
Now we will try to insert invalid amount value in Product table using following statements.
The above statement returns Invalid Amount because we added validation to allow new row insertion only when
quantity and amount column values are greater than zero.
Now we will see what will happen when we try to insert invalid quantity value in the Product table using the
following statements.
The above statement also returns Invalid Quantity because we tried to insert value which is less than zero.
Now we will try to insert valid data in the Product table using the following statements
The data inserted successfully without having any error. This is how we can use triggers to raise BEFORE or AFTER
execution of operations on tables.
Now we will see how to raise triggers after updating the table records using AFTER UPDATE statement with
example.
By using AFTER UPDATE we can raise the trigger immediately after completion of query execution.
To see how to raise the trigger immediately after completion of query execution first, we will create a new table called
products_log using following statements.
Now, create an AFTER UPDATE trigger to log the data into the Product_logs table whenever there is an update in the
Product table amount or pname columns. By this, we can keep track of product prices in the future also.
END;
In above trigger statement we defined condition in WHEN clause to invoke trigger only when there is a change in
pname or amount columns of Product table
Now we will update amount for pid 1 to 20rs using following statement.
UPDATE product SET amount = 20 WHERE pid = 1; Now we will check the records of the product_log table using
following statement.
Now, we will try to update pname to “pencil” in the Product table where pid is 1.
Once we update let’s check the records of product_log table using following statement.
We will create a trigger to log data in the product_log table whenever we delete any records from the product table
using following statements.
Now, let’s delete one record from Product table using following query.
Once we delete now check records of product_log table using following statement.
This is how we can use AFTER DELETE statement to raise trigger after deleting table data.
Now we will see how to raise triggers after insertion of data in the table using AFTER INSERT statement with
example.
Create a trigger using the following statements to raise the trigger and log the data in the product_log table whenever
we insert new records in the Product table.
Now, let’s insert one record into Product table using following statement.
Now we will check the records of product_log table using following statement
This is how we can use AFTER INSERT statement to raise trigger after insertion of data in tables based on our
requirements.
Let’s create a trigger with the BEFORE UPDATE statement using the following statements on the Product table.
END;
If you observe above statements we added validation that amount of product and quantity must be greater than zero
and we used a NEW reference to access quantity and amount columns of row that is going to be updated in the
Product table.
Now we will try to update invalid amount to Product table using following statements.
When we try to update invalid value in the Amount column of Product table it throws error like as shown.
Now we will try to update invalid quantity to Product table using following statement.
In both cases when we try to update invalid values in amount and quantity columns we got validation errors because
of our BEFORE UPDATE trigger.
Now we will see how to raise trigger before deleting the table records using BEFORE DELETE statement with
example.
Consider we have two tables called publisher and book like as shown following.
Pub_id Pub_name
---------- ----------
1 JBL
2 Cyberwit
3 Indian Exp
4 Economics
Here the pub_id column in book table is a foreign key references to publisher table
Now we will create a trigger on Publisher table using BEFORE DELETE statement
WHEN
(SELECT count(pub_id)
FROM book
WHERE pub_id=OLD.pub_id)>0
THEN
RAISE(ABORT,"Child table having data")
END;
END;
Here if we try to delete data from the Publisher table based on pub_id then first it will check that same pub_id
available in a book table or not. In case if it available then it will raise exceptions like “Child table having data”
otherwise it will delete the data.
Let’s try to delete record from the publisher table where pub_id is 1 using following statements.
This is how we can use BEFORE DELETE trigger to raise before deleting the records from table based on our
requirements.
In SQLite by using the DROP TRIGGER command we can easily remove or delete triggers which are associated with
tables.
Following is the syntax to delete or drop or remove triggers in SQLite.
In the above syntax IF EXISTS will help us to prevent throwing errors in case if we are trying to delete triggers that do
not exist in database.
Following is the example to delete or drop trigger in SQLite using DROP TRIGGER statement.