Unit 1 1
Unit 1 1
SQLite does NOT work this way. SQLite does NOT require a server to run.
SQLite database is integrated with the application that access the database. The
applications interact with the SQLite database read and write directly from the database
files stored on disk.
The following diagram illustrates the SQLite server-less architecture:
Self-Contained:
SQLite is self-contained means it requires minimal support from the operating system or
external library. This makes SQLite usable in any environment especially in embedded
devices like iPhones, Android phones, game consoles, handheld media players, etc.
SQLite is developed using ANSI-C. The source code is available as a big sqlite3.c and its
header file sqlite3.h. If you want to develop an application that uses SQLite, you just need
to drop these files into your project and compile it with your code.
Zero-configuration:
Because of the serverless architecture, you don’t need to “install” SQLite before using it.
There is no server process that needs to be configured, started, and stopped. In addition,
SQLite does not use any configuration files.
Transactional:
All transactions in SQLite are fully ACID-compliant. It means all queries and changes are
Atomic, Consistent, Isolated, and Durable. In other words, all changes within a transaction
take place completely or not at all even when an unexpected situation like application crash,
power failure, or operating system crash occurs.
SQLite History
SQLite was designed originally on August 2000. It is named SQLite because it is very light
weight (less than 500Kb size) unlike other database management systems like SQL Server
or Oracle.
Year Happenings
2000 SQLite was designed by D. Richard Hipp for the purpose of no administration
required for operating a program.
2000 In August SQLite 1.0 released with GNU database manager.
2011 Hipp announced to add UNQl interface to SQLite db and to develop UNQLite
(Document oriented database).
SQLite Advantages
SQLite is a very popular database which has been successfully used with on disk file format
for desktop applications like version control systems, financial analysis tools, media
cataloging and editing suites, CAD packages, record keeping programs etc.
There are a lot of advantages to use SQLite as an application file format:
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
memory.
If you edit small parts, it only overwrite the parts of the file which was changed.
3) No Installation Needed
SQLite is very easy to learn. You do not 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.
SQLite queries are smaller than equivalent procedural codes so, chances of bugs are
minimal.
5) Portable
SQLite is portable across all 32-bit and 64-bit operating systems and big- and little-
endian architectures.
Multiple processes can be attached with same application file and can read and write
without interfering each other.
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.
SQLite database's content is more likely to be recoverable if it has been lost. Data lives
longer than code.
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 can be easily extended in in future releases just by adding new tables and/or
columns. It also preserve the backwards compatibility.
SQLite Disadvantages
SQLite is used to handle low to medium traffic HTTP requests.
Database size is restricted to 2GB in most cases.
1.1.1 SQLite datatype( Dynamic type, SQLite manifest typing & type affinity)
(NULL, INTEGER, REAL,TEXT, BLOB)
If you use other database systems such as MySQL and PostgreSQL, you notice that they
use static typing. It means when you declare a column with a specific data type, that
column can store only data of the declared data type.
Different from other database systems, SQLite uses dynamic type system. In other
words, a value stored in a column determines its data type, not the column’s data type.
In addition, 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.
SQLite provides five primitive data types which are referred to as storage classes.
Storage classes describe the formats that SQLite uses to store data on disk. A storage
class is more general than a data type e.g., INTEGER storage class includes 6 different
types of integers. In most cases, you can use storage classes and data types
interchangeably.
First, create the accounts and account_changes tables by using the following CREATE TABLE
statements:
CREATE TABLE accounts (
account_no INTEGER NOT NULL,
balance DECIMAL NOT NULL DEFAULT 0,
PRIMARY KEY(account_no),
CHECK(balance >= 0)
);
CREATE TABLE account_changes (
change_no INT NOT NULL PRIMARY KEY,
account_no INTEGER NOT NULL,
flag TEXT NOT NULL,
amount DECIMAL NOT NULL,
changed_at TEXT NOT NULL
);
Fourth, transfer 1000 from account 100 to 200, and log the changes to the table
account_changes in a single transaction.
BEGIN TRANSACTION;
UPDATE accounts
SET balance=balance - 1000
WHERE account_no=100;
UPDATE accounts
SET balance=balance + 1000
WHERE account_no=200;
COMMIT;
BEGIN TRANSACTION;
UPDATE accounts
SET balance=balance-20000
WHERE account_no=100;
Finally, query data from the account_changes table, you will see that the change no #3 is
not there anymore:
SELECT * FROM account_changes;
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 records in the table.
Syntax:
SELECT DISTINCT Column1, Column2,….ColumnN
FROM table_name
WHERE [condition]
Example:
We have a table named “STUDENT”, having the following data:
First Select NAME from “STUDENT” without using DISTINCT keyword. It will show the duplicate
records:
SELECT NAME FROM STUDENT;
If the condition is satisfied or true, it returns specific value from the table. You would use
WHERE clause to filter the records and fetching only necessary records.
WHERE clause is also used to filter the records and fetch only specific data.
Syntax:
SELECT column1, column2, columnN
FROM table_name
WHERE [condition]
Example:
In this example, we are using WHERE clause with several comparison and logical operators.
like >, <, =, LIKE, NOT, etc.
We have a table student having the following data:
Example1:
Select students WHERE age is greater than or equal to 25 and fees is greater than or equal
to 10000.00
SELECT * FROM STUDENT WHERE AGE >= 25 AND FEES >= 10000.00;
Example2:
Select students form STUDENT table where name starts with 'A' doesn't matter what come
after 'A'.
SELECT * FROM STUDENT WHERE NAME LIKE 'A%';
Example3:
Select all students from STUDENT table where age is either 25 or 27.
SELECT * FROM STUDENT WHERE AGE IN ( 25, 27 );
Example4:
Select all students from STUDENT table where age is neither 25 nor 27.
SELECT * FROM STUDENT WHERE AGE NOT IN (25,27);
OR
SELECT FROM table_name
WHERE column LIKE '%XXXX%';
OR
SELECT FROM table_name
WHERE column LIKE 'XXXX_';
OR
SELECT FROM table_name
WHERE column LIKE '_XXXX';
OR
SELECT FROM table_name
WHERE column LIKE '_XXXX_';
Here, XXXX could be any numeric or string value.
Example:
We have a table named 'STUDENT' having following data:
In these examples the WHERE statement having different LIKE clause with '%' and '_'
operators and operation is done on 'FEES':
Statement Description
Where FEES like It will find any values that start with 200.
'200%'
Where FEES like It will find any values that have 200 in any position.
'%200%'
Where FEES like It will find any values that have 00 in the second and third positions.
'_00%'
Where FEES like It will find any values that start with 2 and are at least 3 characters
'2_%_%' in length.
Where FEES like It will find any values that end with 2
'%2'
Where FEES like It will find any values that have a 2 in the second position and end
'_2%3' with a 3
Where FEES like It will find any values in a five-digit number that start with 2 and
'2 3' end with 3
Example1: Select all records from STUDENT table WHERE age start with 2.
SELECT * FROM STUDENT WHERE AGE LIKE '2%';
Example2:
Select all records from the STUDENT table WHERE ADDRESS will have "a" (a) inside the
text:
SELECT * FROM STUDENT WHERE ADDRESS LIKE '%a%';
While using UNION operator, each SELECT statement must have the same number of fields
in the result set.
Syntax:
SELECT expression1, expression2,….expression_n
FROM tables
[WHERE conditions]
UNION
SELECT expression1, expression2,….expression_n
FROM tables
[WHERE conditions];
Example:
We have two tables “STUDENT” and “DEPARTMENT”.
Let’s take the above two tables “STUDENT” and “DEPARTMENT” and select id from both table to
make UNION.
Output:
The basic rules for combining the result sets of two queries are as follows:
First, the number and the order of the columns in all queries must be the same.
Second, the data types must be comparable.
For the demonstration, we will create two tables t1 and t2 and insert some data into both:
CREATE TABLE t1(
v1 INT
);
INSERT INTO t1(v1)
VALUES(1),(2),(3);
The following statement illustrates how to use the INTERSECT operator to compare result
sets of two queries:
SELECT v1
FROM t1
INTERSECT
SELECT v2
FROM t2;
OUTPUT:
The following statements create two tables t1 and t2 and insert some data into both tables:
CREATE TABLE t1( v1 INT);
INSERT INTO t1(v1) VALUES(1),(2),(3);
CREATE TABLE t2(v2 INT );
INSERT INTO t2(v2) VALUES(2),(3),(4);
The following statement illustrates how to use the EXCEPT operator to compare
result sets of two queries:
SELECT v1
FROM t1
EXCEPT
SELECT v2
FROM t2;
The output is 1.
The LIMIT clause can also be used along with OFFSET clause.
SELECT column1, column2, columnN
FROM table_name
LIMIT [no of rows] OFFSET [row num]
Example:
We have a table named 'STUDENT' having following data:
Example 1:
Fetch the record from the “STUDENT” table by using LIMIT according to your need of number
of rows.
SELECT * FROM STUDENT LIMIT 5;
Output:
Example 2:
OFFSET is used to not retrieve the offset records from the table. IT is used in some cases
where we have to retrieve the records starting from a certain point:
Select 3 records from the table “STUDENT” starting from 3 rdposition(Start with 0)
SELECT * FROM STUDENT LIMIT 3 OFFSET 2;
Output:
SQLite IS NULL
The SQLite IS NULL Condition is used to test for a NULL value in a SELECT, INSERT,
UPDATE, or DELETE statement.
Syntax:
expression IS NULL
Note
If expression is a NULL value, the condition evaluates to TRUE.
If expression is not a NULL value, the condition evaluates to FALSE.
You can use one or more columns in ORDER BY clause. Your used column must be
presented in column-list.
Example1:
Select all records from "STUDENT" where FEES is in ascending order:
SELECT * FROM STUDENT ORDER BY FEES ASC;
Output:
Example2:
Fetch all data from the table "STUDENT" and sort the result in descending order by NAME
and FEES:
SELECT * FROM STUDENT ORDER BY NAME, FEES DESC;
Output:
The GROUP BY clause is used with WHERE clause in SELECT statement and precedes the
ORDER BY clause.
Syntax:
SELECT column-list
FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2 .... columnN
ORDER BY column1, column2 .... columnN
Let's take an example to demonstrate the GROUP BY clause. We have a table named
"STUDENT", having the following data:
Use the GROUP BY query to know the total amount of FEES of each student:
SELECT NAME, SUM(FEES) FROM STUDENT GROUP BY NAME;
Output:
Now, create some more records in "STUDENT" table using the following INSERT statement:
INSERT INTO STUDENT VALUES (7, 'Ajeet', 27, 'Delhi', 10000.00 );
INSERT INTO STUDENT VALUES (8, 'Mark', 23, 'USA', 5000.00 );
INSERT INTO STUDENT VALUES (9, 'Mark', 23, 'USA', 9000.00 );
The new updated table has the inserted entries. Now, use the same GROUP BY statement to
group-by all the records using NAME column:
You can use ORDER BY clause along with GROUP BY to arrange the data in ascending or
descending order.
SELECT NAME, SUM(FEES)
FROM STUDENT GROUP BY NAME ORDER BY NAME DESC;
Syntax:
SELECT column1, column2
FROM table1, table2
WHERE [ conditions ]
GROUP BY column1, column2
HAVING [ conditions ]
ORDER BY column1, column2
Example:
Let's take an example to demonstrate HAVING Clause. We have a table named "STUDENT",
having the following data:
Example1:
Display all records where name count is less than 2:
SELECT * FROM STUDENT GROUP BY NAME HAVING COUNT(NAME) < 2;
Output:
Example2:
Display all records where name count is greater than 2:
SELECT * FROM STUDENT GROUP BY NAME HAVING COUNT(NAME) > 2;
Output:
CASE test_expression
...
ELSE [Expression]
END
Here in SQLite Case statement each WHEN... THEN clauses evaluated in an orderly manner.
First it evaluated conditon 1 in case if it statisfied the nit returns expression 1 otherwise it will
execute condition 2 and so on. If no condition is satisfied, the nfinally execution goes to ELSE
block, and expression under ELSE is evaluated.
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'
END as 'Grade'
FROM STUDENT;
Output:
1.3 SQLite joins: Inner, left, cross, self, Full outer joins.
SQLite 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 - 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.
Example: We need to create two tables dept_master and emp_master and need to insert
some data for that use following queries:
CREATE TABLE dept_master
(dept_id INTEGER PRIMARY KEY AUTOINCREMENT,
dept_name TEXT);
INSERT INTO dept_master(dept_name)
VALUES('Admin'),
("Sales'),
('Quality Control'),
('Marketing');
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.
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 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.
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.
Example: Consider above tables dep_master and emp_master for 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;
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.
Example: Consider above tables dep_master and emp_master for Cross JOIN with
a select statement.
SELECT dept_name,emp_id,first_name
FROM dept_master CROSS JOIN emp_master;
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.
If you observe above SQLite Self join syntax we given alias name to table1 as x and y and
used same field of table1 table for comparison.
(5,'Shweta','Rana',12000,3,2),
(6,'Sonal','Menpara',13000,3,3),
(7,'Yamini','Patel',10000,2,7),
(8,'Khyati','Shah',49900,3,2),
(9,'Shwets','JAriwala',19400,2,7));
Example: to use Self Join with a select statement to get employees manager details.
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.
Usage of Triggers:
Triggers are used for enforcing business rules.
Validating input data.
Generating a unique value for a newly-inserted row in a different file.
Write to other files for audit trail purposes.
Query from other files for cross-referencing purposes.
Used to access system functions.
Replicate data to different files to achieve data consistency.
Advantages of using triggers:
1. Triggers make the application development faster. Because the database stores triggers,
you do not have to code the trigger actions into each database application.
2. Define a trigger once and you can reuse it for many applications that use the database.
3. Maintenance is easy. If the business policy changes, you have to change only the
corresponding trigger program instead of each application program.
Disadvantages of using triggers:
1. It is hard to follow their logic as it they can be fired before or after the database
insert/update happens.
2. It is easy to forget about triggers and if there is no documentation it will be difficult to
figure out for new developers for their existence.
3. Triggers run every time when the database fields are updated and it is overhead on
system. It makes system run slower.
1.4.1 Concepts of Trigger, Before and After trigger (on Insert, Update, Delete)
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.
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 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.
Now, let's delete one record from Product table using the following query.
sqlite> DELETE FROM Product WHERE pid=1;
Once we delete now check records of product_log table using following statement.
Now, let's insert one record into product table using the following statement.
INERT INTO product(pid,pname,quantity,amount) VALUES(2,'eraser',200,5);
Now, we will check the records of product_log table using the following statement.
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;
VALUES (1,'Oreilly'),
(2,'Tata Mcgraw Hill'),
(3,'Indian Express'),
(4,'Packt');
Now we will create a trigger on Publisher table using BEFORE DELETE statement.
CREATE TRIGGER trg_publisher_before_delete BEFORE DELETE
on Publisher
BEGIN
SELECT
CASE
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;
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.
Example to Delete Trigger
DROP TRIGGER trg_product_after_insert;
Note : Note that triggers are automatically dropped when the associated table is dropped.