0% found this document useful (0 votes)
8 views

Unit 1

Uploaded by

figafa2979
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Unit 1

Uploaded by

figafa2979
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

DATABSE: UNIT 1

Unit-1: Introduction to SQLite:

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.

Unit 1.1 SQLite advantages, features and Fundamentals:

Explain SQLite Features. OR Why to use SQLite?


Following is a list of features which makes SQLite popular among other lightweight databases:
• SQLite is totally free: SQLite is open-source. So, no license is required to work with it.
• SQLite is serverless: SQLite doesn't require a different server process or system to operate.
• SQLite is very flexible: It facilitates you to work on multiple databases on the same session on the same time.
• Configuration Not Required: SQLite doesn't require configuration. No setup or administration required.
• SQLite is a cross-platform DBMS: You don't need a large range of different platforms like Windows, Mac
OS, Linux, and Unix. It can also be used on a lot of embedded operating systems like Symbian, and Windows
CE.
• Storing data is easy: SQLite provides an efficient way to store data.
• Variable length of columns: The length of the columns is variable and is not fixed. It facilitates you to
allocate only the space a field needs. For example, if you have a varchar(200) column, and you put a 10
characters' length value on it, then SQLite will allocate only 20 characters' space for that value not the whole
200 space.
• Provide large number of API's: SQLite provides API for a large range of programming languages. For
example: .Net languages (Visual Basic, C#), PHP, Java, Objective C, Python and a lot of other programming
language.
• 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).
Write SQLite Limitations.
• Only LEFT OUTER JOIN is implemented.
• The RENAME TABLE and ADD COLUMN variants of the ALTER TABLE command are supported.
The DROP COLUMN, ALTER COLUMN, ADD CONSTRAINT are not supported.
• 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 statement on
a view.
• The only access permissions that can be applied are the normal file access permissions of the
underlying operating system.

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.

Explain SQLite data types.

• 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.

Data Type 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

Now, let’s understand different data types in detail.

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.

SQLite assigns a column’s affinity according to the following rules.

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 Boolean Data Type

SQLite does not support data types like Boolean. Instead, Boolean values are stored as integers 0 (false) and 1
(true).

SQLite Date and Time Data Type

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.

TEXT: A date in a format like "YYYY-MM-DD HH:MM:SS.SSS"


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

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.

SELECT CURRENT_TIME, typeof(CURRENT_TIME);

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.

SELECT CURRENT_DATE, typeof(CURRENT_DATE);

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.

PREPARED BY: SHREYA PATEL, CBPCC


DATABSE: UNIT 1

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.

Unit 1.1.2: Transaction, Rollback, Commit

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.

1. BEGIN – It starts the transaction.


2. COMMIT – It will commit the transaction that means all the changes saved to the database.
3. ROLLBACK – It will rollback the complete transaction.
We can use these commands only when we are performing INSERT, UPDATE, and DELETE operations. It’s
not possible for us to use these commands to CREATE and DROP tables operations because those are auto-
commit in the database.

SQLite BEGIN Command

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];

We can start the transaction using BEGIN or BEGIN TRANSACTION commands.

Here, the keyword TRANSACTION is optional.

SQLite COMMIT Command

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.

Following is the syntax of COMMIT command in SQLite.

COMMIT [TRANSACTION]

or

PREPARED BY: SHREYA PATEL, CBPCC


DATABSE: UNIT 1

END [TRANSACTION]

Here TRANSACTION keyword is optional.

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.

SQLite ROLLBACK Command

By using ROLLBACK command we can cancel the transaction and roll back all the proposed changes.

Following is the syntax of the ROLLBACK command.

ROLLBACK

or
ROLLBACK [TRANSACTION]

Here also TRANSACTION keyword is optional.

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.

We can create a save-points in SQLite with SAVEPOINT command.

Syntax of SQLite Save Points

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.

Following is the syntax to release savepoint.

RELEASE [SAVEPOINT] savepoint_name

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

point was set.

Following is the syntax to rollback transactions using the ROLLBACK command.

ROLLBACK [TRANSACTION] TO [SAVEPOINT] savepoint_name

Unit 1.2.1 Filtering: Distinct, where, between, in, like, Union, intersect, Except, Limit, IS NULL

SQLite DISTINCT Clause

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:

SELECT DISTINCT COLUMN…


FROM TABLE
WHERE CONDITION;

Example:

SELECT NAME FROM STUDENT;


SELECT DISTINCT NAME FROM STUDENT;

SQLite WHERE Clause

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:

SELECT * FROM STUDENT


WHERE AGE >= 25 AND FEES >= 10000;

SQLite BETWEEN operator

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

Column_exp = column name or expression


Val1 = starting value of the range
Val2 = last value of the range

Example:

SELECT * FROM STUDENT


WHERE AGE BETWEEN 18 AND 21;

We can also use between operator with dates to get records within particular date range.

SELECT * FROM STUDENT


WHERE BDATE BETWEEN ‘2001-01-01’ AND ‘2003-01-01;

We can also use NOT operator with BETWEEN operator, then it will return the records that does not fall
within the given range.

Example:

SELECT * FROM STUDENT


WHERE AGE NOT BETWEEN 18 AND 21;

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.

Col_exp: A column value to test.


value1, value2, ... value_n: The values to test against expression.
subquery: The expression value will text against the result set of subquery.

Example:

SELECT * FROM STUDENT


WHERE S_ID IN (10, 20, 30);

SELECT * FROM STUDENT


WHERE CITY IN (‘SURAT’, ‘BARODA’);

SELECT NAME FROM STUDENT


PREPARED BY: SHREYA PATEL, CBPCC
DATABSE: UNIT 1

WHERE D_ID IN (SELECT D_ID FROM DEPARTMENTS WHERE DNAME = ‘CBPCC’);

SQLite LIKE operator

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.

• % allows you to match any string of any length (including zero-length).


• _ allows you to match on a single character.

SQLite LIKE Operator with % Wildcard

SELECT * FROM student WHERE name LIKE 's%';

The above SQLite LIKE operator example returns employees whose first name starts with ‘s’ or ‘S’ character.

SELECT * FROM emp_master WHERE last_name LIKE '%n%';

The above SQLite LIKE operator example return employees who’s last_name contains ‘n’ or ‘N’ character.

SQLite Union Operator

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.

SELECT expression1, expression2,... expression_n


FROM tables
[WHERE conditions]

UNION

SELECT expression1, expression2,... expression_n


FROM tables
[WHERE conditions];
If you observe above SQLite UNION syntax we are combing multiple select statements using UNION operator and
we used some properties those are

• 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;

SQLite UNION ALL Operator

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

SELECT expression1, expression2,... expression_n


FROM tables
[WHERE conditions]
UNION ALL
SELECT expression1, expression2,... expression_n
FROM tables
[WHERE conditions];

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.

SQLite Intersect Operator

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.

SELECT expression1, expression2,... expression_n


FROM tables
[WHERE conditions]

INTERSECT

SELECT expression1, expression2,... expression_n


FROM tables
[WHERE conditions];

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

• columns - It may be no. of column or expression that you want as a result.


• table-list - It may be a list of the table from which you want results.
• Where Condition - Its optional. We can use this condition based on our requirements in Select statements.

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;

SQLite Except Operator


In SQLite, the Except operator is useful to exclude some rows while returning from a select statement. Suppose if we
use Except operator with two SQLite Select statements then it will return all the records from a first select statement
except the records which exist in the second Select statement. Generally, we use SQLite Except operator with Select
statements and all the Select statements which are using with Except operator must have the same number of fields.
SELECT column1, column2,..., columnn
PREPARED BY: SHREYA PATEL, CBPCC
DATABSE: UNIT 1

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

• columns - It may be no. of column or expression that you want as a result.


• table-list - It may be a list of a table from which you want results.
• Where Condition - Its optional. We can use this condition based on our requirements in Select statements.

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.

SQLite Limit Clause

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

• expressions - It may be no. of columns or expression that you want as a result.


• tables-list - It maybe list of the table from which you want result.
• WHERE conditions - It is optional. It is one or more conditions to retrieve the result.
• LIMIT number_rows - It controls the maximum number of records to retrieve. At most, the number of records
specified by number_rows will be returned in the result set.
• OFFSET offset_value - It's optional and it defines how many rows to skip at the beginning of the result set based on
offset_value.

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.

SELECT first_name, last_name


FROM emp_master
LIMIT 5;

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.

SELECT first_name, last_name


FROM emp_master
LIMIT 4
OFFSET 1;

It will skip first record and after only 4 records are displayed.

Following are the some of SQLite Limit clause Offset examples.

LIMIT 10 -- returns the first 10 rows (rows 1 - 10)


LIMIT 10 OFFSET 5 -- returns rows 6 - 15
LIMIT 3 OFFSET 20 -- returns rows 21 - 23

Notice that the OFFSET value defines how many rows are skipped, not the position of the first row.

SQLite Null Values

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.

sqlite>SELECT * FROM Person;

SSID first_name last_name email phone_no city


---------- ---------- ---------- --------------- ---------- ------
1 Vinay Jariwala [email protected] 898545 Vapi
2 Shweta Jariwala [email protected] Vapi
3 Sonal Menpara [email protected] 84697 Surat
4 Jagruti Viras [email protected] 656454 Daman
5 Yamini Patel [email protected] 98788 Mumbai
6 Yamini Shah [email protected] Baroda

Now, we will try to get persons whose phone number is NULL from the Person table. So we will execute the
following SQLite query.

sqlite> SELECT * FROM Person WHERE phone_no = NULL;

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:

sqlite> SELECT * FROM Person WHERE phone_no IS NULL;

SSID first_name last_name email phone_no city


---------- ---------- ---------- ---------------- ---------- ------
2 Shweta Jariwala [email protected] Vapi
6 Yamini Shah [email protected] Baroda

In SQLite, the IS operator properly checks for a NULL and returns true records if it finds.

PREPARED BY: SHREYA PATEL, CBPCC


DATABSE: UNIT 1

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.

sqlite> SELECT * FROM Person WHERE phone_no IS NOT NULL;

SSID first_name last_name email phone_no city


---------- ---------- ---------- --------------- ---------- ------
1 Vinay Jariwala [email protected] 898545 Vapi
3 Sonal Menpara [email protected] 84697 Surat
4 Jagruti Viras [email protected] 656454 Daman
5 Yamini Patel [email protected] 98788 Mumbai

Unit 1.2.2 Having, Group by, Order by, Conditional Logic (CASE)

SQLite GROUP BY Clause

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

• result - It's no. of column or expression that you want as a result.


• table-list - Its list of a table from which you want results.
• expr-list - It causes one or more rows of the result to be combined into a single row of output. This is especially
useful when the result contains aggregate functions.

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.

Group By with Sum

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;

emp_id first_name last_name salary dept_id


---------- ---------- ---------- ---------- ----------
1 Honey Patel 10100 1
2 Shweta Jariwala 19300 2
3 Vinay Jariwala 35100 3
4 Jagruti Viras 9500 2

Now, If you want to know the total amount of salary on each employee, then GROUP BY query would be like as
shown below.

sqlite> SELECT first_name, SUM(salary)


FROM emp_master
GROUP BY first_name;

PREPARED BY: SHREYA PATEL, CBPCC


DATABSE: UNIT 1

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;

emp_id first_name last_name salary dept_id


---------- ---------- ---------- ---------- ----------
1 Honey Patel 10100 1
2 Shweta Jariwala 19300 2
3 Vinay Jariwala 35100 3
4 Jagruti Viras 9500 2
5 Shweta Rana 12000 3

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:

sqlite> SELECT first_name, SUM(salary)


FROM emp_master
GROUP BY first_name;

first_name SUM(salary)
---------- -----------
Honey 10100
Jagruti 9500
Shweta 31300
Vinay 3510

Group By with count, count(*)

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.

sqlite> SELECT first_name, SUM(salary), count(first_name)


FROM emp_master
GROUP BY first_name;

When we run above query we will get result like as shown below.

first_name SUM(salary) count(first_name)


---------- ----------- -----------------
Honey 10100 1
Jagruti 9500 1
Shweta 31300 2
Vinay 35100 1

PREPARED BY: SHREYA PATEL, CBPCC


DATABSE: UNIT 1

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.

sqlite>SELECT * FROM Person;

SSID first_name last_name email phone_no city


---------- ---------- ---------- --------------- ---------- ------
1 Vinay Jariwala [email protected] 898545 Vapi
2 Shweta Jariwala [email protected] Vapi
3 Sonal Menpara [email protected] 84697 Surat
4 Jagruti Viras [email protected] 656454 Daman
5 Yamini Patel [email protected] 98788 Mumbai
6 Yamini Shah [email protected] Baroda

As you can see 2 person has null in their phone_no. now if I execute the following query-

sqlite> select count(phone_no) from person;

I will get following output.

Count(phone_no)
----------------------
4

But on the same data if I execute count(*)-

sqlite> select count(*) from person;

I will get following output.

Count(*)
----------------------
6

This is because count() ignores NULL values but count(*) does not.

Group By with Min / Max

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.

sqlite> SELECT * FROM emp_master;

emp_id first_name last_name salary dept_id


---------- ---------- ---------- ---------- ----------
1 Honey Patel 10100 1
2 Shweta Jariwala 19300 2
3 Vinay Jariwala 35100 3
4 Jagruti Viras 9500 2
5 Shweta Rana 12000 3
6 Sonal Menpara 13000 1
7 Yamini Patel 10000 2
8 Khyati Shah 50000 3

PREPARED BY: SHREYA PATEL, CBPCC


DATABSE: UNIT 1

Now write the following query to get the minimum and maximum salary of the department by using SQLite Group By
clause

SELECT min(salary), max(salary)


FROM emp
GROUP BY dept_id;

min(e.salary) max(e.salary)
------------- ------------- ------------
10100 13000
9500 19300
12000 50000

SQLite HAVING Clause

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

• result - It may be no. of column or expression that you want as a result.


• table-list - It may be the list of a table from which you want results.
• expr - This is similar to WHERE except that HAVING applies after grouping has occurred.

Let ‘s see the example for having clause using emp table data.

emp_id first_name last_name salary dept_id


---------- ---------- ---------- ---------- ----------
1 Honey Patel 10100 1
2 Shweta Jariwala 19300 2
3 Vinay Jariwala 35100 3
4 Jagruti Viras 9500 2
5 Shweta Rana 12000 3
6 Sonal Menpara 13000 1
7 Yamini Patel 10000 2
8 Khyati Shah 50000 3

sqlite> SELECT first_name, count(first_name)


FROM emp
GROUP BY first_name
HAVING count(*) >1;

The result of the above query will be-

PREPARED BY: SHREYA PATEL, CBPCC


DATABSE: UNIT 1

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.

SELECT first_name, dept_id


FROM emp
GROUP BYdept_id
HAVING count(*) > 2

This will display

First_name dept_id
Shweta 2
Jagruti 2
Yamini 2
Vinay 3
Shweta 3
Khyati 3

As department 1 has only 2 employees it will not be a part of the output.

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

• expressions - It may be no. of columns or expressions that you want as a result.


• tables-list - It may be the list of the table from which you want results.
• WHERE conditions - It is optional. It is one or more conditions to retrieve the result.
• ASC - It is an optional parameter. It sorts the result set in ascending order by expression. ASC is the default if no
modifier is provided.
• DESC - It is an optional parameter. It sorts the result set in descending order by expression.

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;

emp_id first_name last_name salary dept_id


---------- ---------- ---------- ---------- ----------
PREPARED BY: SHREYA PATEL, CBPCC
DATABSE: UNIT 1

1 Honey Patel 10100 1


2 Shweta Jariwala 19300 2
3 Vinay Jariwala 35100 3
4 Jagruti Viras 9500 2
5 Shweta Rana 12000 3
6 Sonal Menpara 13000 1
7 Yamini Patel 10000 2
8 Khyati Shah 50000 3

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.

emp_id first_name last_name salary dept_id


---------- ---------- ---------- ---------- ----------
8 Khyati Shah 50000 3
3 Vinay Jariwala 35100 3
2 Shweta Jariwala 19300 2
6 Sonal Menpara 13000 1
5 Shweta Rana 12000 3
1 Honey Patel 10100 1
7 Yamini Patel 10000 2
4 Jagruti Viras 9500 2

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.

SELECT last_name, first_name


FROM emp_master
ORDER BY 2 DESC;

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.

emp_id first_name last_name salary dept_id


---------- ---------- ---------- ---------- ----------
8 Khyati Shah 50000 3
3 Vinay Jariwala 35100 3
2 Shweta Jariwala 19300 2
6 Sonal Menpara 13000 1
5 Shweta Rana 12000 3
1 Honey Patel 10100 1
7 Yamini Patel 10000 2
4 Jagruti Viras 9500 2

This is how we can use SQLite Order By clause to sort table records either in ascending or descending based on our
requirements.

SQLite Case Statement

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.

Following is the syntax of the SQLite CASE statement.

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;

ID NAME EMAIL MARKS


---------- ---------- ---------------- ----------
1 Shweta [email protected] 80
2 Yamini [email protected] 60
3 Sonal [email protected] 50
4 Jagruti [email protected] 30

PREPARED BY: SHREYA PATEL, CBPCC


DATABSE: UNIT 1

Following is the example of using the SQLite Case Statement with Select query.

SELECT ID, NAME, MARKS,


CASE
WHEN MARKS >=80 THEN 'A+'
WHEN MARKS >=70 THEN 'A'
WHEN MARKS >=60 THEN 'B'
WHEN MARKS >=50 THEN 'C'
ELSE 'Sorry!! Failed'
END as 'Grade'
FROM STUDENT;

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.

ID NAME MARKS Grade


---------- ---------- ---------- ----------
1 Shweta 80.0 A+
2 Yamini 60.0 B
3 Sonal 50.0 C
4 Jagruti 30.0 Sorry!! Failed

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.

In SQLite, we have different types of JOINS available those are

• 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

SQLite INNER JOIN

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.

Following is the syntax of using SQLite inner join in Select statements.

SELECT t1.col1, t2.col2, ...


FROM table1 t1
[INNER] JOIN
table2 t2
ON t1.col3=t2.col5;

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.

sqlite> SELECT * FROM dep_master;

dept_id dept_name
---------- ----------
1 Admin
2 Sales
3 Quality Control
4 Marketing

sqlite> SELECT * FROM emp_master;

emp_id first_name last_name salary dept_id


---------- ---------- ---------- ---------- ----------
1 Honey Patel 10100 1

PREPARED BY: SHREYA PATEL, CBPCC


DATABSE: UNIT 1

2 Shweta Jariwala 19300 2


3 Vinay Jariwala 35100 3
4 Jagruti Viras 9500 2
5 Shweta Rana 12000 3
6 Sonal Menpara 13000 1
7 Yamini Patel 10000 2
8 Khyati Shah 50000 3

Now write SQLite query like as shown following to use INNER JOIN with a select statement.

SELECT d.dept_id, dept_name, emp_id, first_name


FROM dept_master d JOIN emp_master e
ON d.dept_id = e.dept_id;

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.

dept_id dept_name emp_id first_name


---------- ---------- ---------- ----------
1 Admin 1 Honey
2 Sales 2 Shweta
3 Quality Co 3 Vinay
2 Sales 4 Jagruti
3 Quality Co 5 Shweta
1 Admin 6 Sonal
2 Sales 7 Yamini
3 Quality Co 8 Khyati

Here in above example, there is no employee from Marketing department that's the reason marketing department
records are not included in the result.

SQLite Cross Join

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.

syntax of using SQLite Cross Join with Select statement.

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.

sqlite> SELECT * FROM dep_master;


PREPARED BY: SHREYA PATEL, CBPCC
DATABSE: UNIT 1

dept_id dept_name
---------- ----------
1 Admin
2 Sales
3 Quality Control
4 Marketing

sqlite> SELECT * FROM emp_master;

emp_id first_name last_name salary dept_id


---------- ---------- ---------- ---------- ----------
1 Honey Patel 10100 1
2 Shweta Jariwala 19300 2
3 Vinay Jariwala 35100 3
4 Jagruti Viras 9500 2
5 Shweta Rana 12000 3
6 Sonal Menpara 13000 1
7 Yamini Patel 10000 2
8 Khyati Shah 50000 3

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.

dept_name emp_id first_na


---------- ---------- --------
Admin 2 Shweta
Admin 3 Vinay
Admin 4 Jagruti
Admin 5 Shweta
Admin 6 Sonal
Admin 7 Yamini
Admin 8 Khyati
Admin 9 Shwets
Sales 2 Shweta
Sales 3 Vinay
Sales 4 Jagruti
Sales 5 Shweta
Sales 6 Sonal
Sales 7 Yamini
Sales 8 Khyati
Sales 9 Shwets
Quality Co 2 Shweta
Quality Co 3 Vinay
Quality Co 4 Jagruti
Quality Co 5 Shweta
Quality Co 6 Sonal
Quality Co 7 Yamini
Quality Co 8 Khyati
Quality Co 9 Shweta
Marketing 2 Shweta
Marketing 3 Vinay
PREPARED BY: SHREYA PATEL, CBPCC
DATABSE: UNIT 1

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.

SQLite Left Outer Join

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.

sqlite> SELECT * FROM dep_master;

dept_id dept_name
---------- ----------
1 Admin
2 Sales
3 Quality Control
4 Marketing

sqlite> SELECT * FROM emp_master;

emp_id first_name last_name salary dept_id


---------- ---------- ---------- ---------- ----------
1 Honey Patel 10100 1
2 Shweta Jariwala 19300 2
3 Vinay Jariwala 35100 3
4 Jagruti Viras 9500 2
5 Shweta Rana 12000 3
6 Sonal Menpara 13000 1
7 Yamini Patel 10000 2
8 Khyati Shah 50000 3
PREPARED BY: SHREYA PATEL, CBPCC
DATABSE: UNIT 1

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.

dept_id dept_name emp_id first_name


---------- ---------- ---------- ----------
1 Admin 6 Sonal
2 Sales 4 Jagruti
2 Sales 2 Shweta
2 Sales 9 Shwets
2 Sales 7 Yamini
3 Quality Co 8 Khyati
3 Quality Co 5 Shweta
3 Quality Co 3 Vinay
4 Marketing

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.

SQLite Self Join

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.

SELECT x.column_name, y.column_name...


FROM table1 x, table1 y
WHERE x.column_name1 = y.column_name1;

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.

We will understand this with the following emp_master table example.

sqlite> SELECT * FROM emp_master;

emp_id first_name last_name salary dept_id manager_id


---------- ---------- ---------- ------- ------- ----------
2 Shweta Jariwala 19300 2 7
3 Vinay Jariwala 35000 3 2
4 Jagruti Viras 9500 2 7
5 Shweta Rana 12000 3 2
6 Sonal Menpara 13000 1 3
PREPARED BY: SHREYA PATEL, CBPCC
DATABSE: UNIT 1

7 Yamini Patel 10000 2 7


8 Khyati Shah 49900 3 2
9 Shweta Jariwala 19400 2 7

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.

emp_id Employee Manager ID Manager Name


---------- ---------- ---------- ------------
2 Shweta 7 Yamini
3 Vinay 2 Shweta
4 Jagruti 7 Yamini
5 Shweta 2 Shweta
6 Sonal 3 Vinay
7 Yamini 7 Yamini
8 Khyati 2 Shweta
9 Shwets 7 Yamini

This is how we can use SQLite self join query to get details based on our requirements

SQL FULL OUTER JOIN clause

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 SQLite Trigger

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.

Benefits of Trigger in SQLite

• It will help us to prevent invalid transactions by imposing business rules


• Maintain data integrity
• We can enable event logging for the changes in table data.
PREPARED BY: SHREYA PATEL, CBPCC
DATABSE: UNIT 1

Unit 1.4.2 Create, Drop trigger, Disable and Enable trigger

Following is the syntax of creating a trigger in SQLite using CREATE TRIGGER.

CREATE TRIGGER [IF NOT EXISTS] trigger_name


[BEFORE|AFTER|INSTEAD OF] [INSERT|UPDATE|DELETE]
ON table_name
[FOR EACH ROW]
[WHEN condition]
BEGIN Trigger_action_body
END;

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.

CREATE TABLE Product


(pid INTEGER PRIMARY KEY,
pname TEXT NOT NULL,
amount REAL,
quantity INTEGER);

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.

CREATE TRIGGER trg_validate_products_before_insert


BEFORE INSERT
ON Product
BEGIN
SELECT
CASE
WHEN NEW.quantity < 0 THEN
RAISE(ABORT, 'Invalid Quantity')
END;
SELECT CASE WHEN NEW.amount<=0 THEN
RAISE(ABORT, 'Invalid Amount')
END;
END;

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.

PREPARED BY: SHREYA PATEL, CBPCC


DATABSE: UNIT 1

Now we will try to insert invalid amount value in Product table using following statements.

INSERT INTO Product(pid,pname,amount,quantity) VALUES(1,'Marbles',-5,20); Error: Invalid Amount

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.

INSERT INTO Product(pid,pname,amount,quantity) VALUES(1,'Marbles',100,-3); Error: Invalid Quantity

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

INSERT INTO Product(pid,pname,amount,quantity) VALUES(1,'Marbles',100,3);

sqlite> SELECT * FROM product;

pid pname amount quantity


---------- ---------- ---------- ----------
1 Marbles 100.0 3

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.

SQLite AFTER UPDATE Trigger

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.

CREATE TABLE Product_log


(pid INTEGER,
operation TEXT,
old_amount REAL,
new_amount REAL,
old_pname TEXT,
new_pname TEXT);

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.

CREATE TRIGGER trg_product_after_update AFTER UPDATE


on Product
WHEN OLD.amount <> NEW.amount
OR OLD.pname <> NEW.pname
BEGIN
INSERT INTO Product_log
(pid,operation,old_amount,new_amount,old_pname,new_pname)
VALUES(OLD.pid,'UPDATE', OLD.amount,NEW.amount,OLD.pname,NEW.pname);
PREPARED BY: SHREYA PATEL, CBPCC
DATABSE: UNIT 1

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.

sqlite> SELECT * FROM product_log;

pid operation old_amount new_amount old_pname new_pname


---------- ---------- ---------- ---------- ---------- ----------
1 UPDATE 100.0 20.0 Marbles Marbles

Now, we will try to update pname to “pencil” in the Product table where pid is 1.

UPDATE Product SET pname ='Pencil' WHERE pid = 1;

Once we update let’s check the records of product_log table using following statement.

sqlite> SELECT * FROM product_log;

pid operation old_amount new_amount old_pname new_pname


---------- ---------- ---------- ---------- ---------- ----------
1 UPDATE 100.0 20.0 Marbles Marbles
1 UPDATE 20.0 20.0 Marbles Pencil

SQLite AFTER DELETE Trigger

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.

CREATE TRIGGER trg_product_after_delete


AFTER DELETE
on Product
BEGIN
INSERT into product_log
(pid,operation,old_pname,old_amount)
VALUES(OLD.pid,'DELETE ' || date('now'),OLD.pname,OLD.amount);
END;

Now, let’s delete one record from Product table using following query.

sqlite> DELETE FROM product WHERE pid=1;

Once we delete now check records of product_log table using following statement.

sqlite> SELECT * FROM product_log;

pid operation old_amount new_amount old_pname new_pname


---------- ---------- ---------- ---------- ---------- ----------
1 UPDATE 100.0 20.0 Marbles Marbles
1 UPDATE 20.0 20.0 Marbles Pencil
1 DELETE 20.0 Pencil
PREPARED BY: SHREYA PATEL, CBPCC
DATABSE: UNIT 1

This is how we can use AFTER DELETE statement to raise trigger after deleting table data.

SQLite AFTER INSERT Trigger

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.

CREATE TRIGGER trg_product_after_insert


AFTER INSERT
on Product
BEGIN
INSERT into product_log
(pid,operation,old_pname,old_amount)
VALUES(NEW.pid,'INSERT ' || date('now'),NEW.pname,NEW.amount);
END;

Now, let’s insert one record into Product table using following statement.

INSERT INTO product (pid,pname,quantity,amount) VALUES(2,'ERASER', 200,5);

Now we will check the records of product_log table using following statement

sqlite> SELECT * FROM product_log;

pid operation old_amount new_amount old_pname new_pname


---------- ---------- ---------- ---------- ---------- ----------
1 UPDATE 100.0 20.0 Marbles Marbles
1 UPDATE 20.0 20.0 Marbles Pencil
1 DELETE 20.0 Pencil
2 INSERT 5.0 ERASER

This is how we can use AFTER INSERT statement to raise trigger after insertion of data in tables based on our
requirements.

SQLite BEFORE UPDATE Trigger

Let’s create a trigger with the BEFORE UPDATE statement using the following statements on the Product table.

CREATE TRIGGER trg_validate_products_before_update


BEFORE UPDATE
ON Product
BEGIN
SELECT
CASE
WHEN NEW.quantity < 0 THEN
RAISE(ABORT,'Invalid Quantity')
END;
SELECT
CASE
WHEN NEW.amount<=0 THEN
RAISE(ABORT,'Invalid Amount')
END;
PREPARED BY: SHREYA PATEL, CBPCC
DATABSE: UNIT 1

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.

UPDATE Product SET Amount = -3 WHERE pid = 2;


Error: Invalid Amount

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.

UPDATE Product SET quanity = -10 WHERE pid = 2;


Error: Invalid Quantity

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.

SQLite BEFORE DELETE 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.

sqlite> SELECT * FROM book;

Book_id Book_name Price pub_id


---------- ---------- ---------- ----------
1 RAMAYANA 100 1
2 MAHABHARAT 300 2
3 Akbar birbal 150 1
4 SHIVA PURAN 200 1

sqlite> SELECT * FROM publisher;

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

CREATE TRIGGER trg_product_before_delete


BEFORE DELETE
on Publisher
BEGIN
SELECT
CASE
PREPARED BY: SHREYA PATEL, CBPCC
DATABSE: UNIT 1

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.

sqlite>DELETE FROM publisher WHERE pub_id=1;


Error: Child table having data

This is how we can use BEFORE DELETE trigger to raise before deleting the records from table based on our
requirements.

SQLite Delete / Remove Trigger

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.

DROP TRIGGER [IF EXISTS] trigger_name

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.

DROP TRIGGER trg_product_after_insert;

PREPARED BY: SHREYA PATEL, CBPCC

You might also like