0% found this document useful (0 votes)
122 views20 pages

Introduction to SQLite and SQL Basics

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)
122 views20 pages

Introduction to SQLite and SQL Basics

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

Database Systems Lecture notes

By Wycliffe Mwebi

Lecture 5:
Getting Started with SQL -using SQLite

What is SQLite
SQLite is a software library that provides a relational database management system. The lite in SQLite
means lightweight in terms of setup, database administration, and required resources.

SQLite has the following noticeable features: self-contained, serverless, zero-configuration,


transactional.

Server-less

Normally, an RDBMS such as MySQL, PostgreSQL, etc., requires a separate server process to operate.
The applications that want to access the database server use TCP/IP protocol to send and receive
requests. This is called client/server architecture.

The following diagram illustrates the RDBMS client/server architecture:


Database Systems Lecture notes
By Wycliffe Mwebi

SQLite does NOT work this way.

SQLite does NOT require a server to run.

SQLite database is integrated with the application that accesses 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 distinctive features


SQLite uses dynamic types for tables. It means you can store any value in any column, regardless of the
data type.

SQLite allows a single database connection to access multiple database files simultaneously. This brings
many nice features like joining tables in different databases or copying data between databases in a
single command.

SQLite is capable of creating in-memory databases that are very fast to work with.
Database Systems Lecture notes
By Wycliffe Mwebi

How to Download & Install SQLite Tools


Download SQLite tools
To download SQLite, you open the download page of the SQlite official website.

1. First, go to the [Link] website.

2. Second, open the download page [Link]

SQLite provides various tools for working across platforms e.g., Windows, Linux, and Mac. You need to
select an appropriate version to download.

For example, to work with SQLite on Windows, you download the command-line shell program as
shown in the screenshot below.

The downloaded file is in the ZIP format and its size is quite small.

Run SQLite tools


Installing SQLite is simple and straightforward.

1. First, create a new folder e.g., C:\sqlite.

2. Second, extract the content of the file that you downloaded in the previous section to
the C:\sqlite folder. You should see three programs in the C:\sqlite folder as shown below:

First, open the command line window:


Database Systems Lecture notes
By Wycliffe Mwebi

and navigate to the C:\sqlite folder.

Second, type sqlite3 and press enter, you should see the following output:

Third, you can type the .help command from the sqlite> prompt to see all available commands in sqlite3.

Fourth, to quit the sqlite>, you use .quit command as follows:


Database Systems Lecture notes
By Wycliffe Mwebi

Install SQLite GUI tool


The sqlite3 shell is excellent…

However, sometimes, you may want to work with the SQLite databases using an intuitive GUI tool.

There are many GUI tools for managing SQLite databases available ranging from freeware to commercial
licenses.

SQLiteStudio
The SQLiteStudio tool is a free GUI tool for managing SQLite databases. It is free, portable, intuitive, and
cross-platform. SQLite tool also provides some of the most important features to work with SQLite
databases such as importing, exporting data in various formats including CSV, XML, and JSON.

You can download the SQLiteStudio installer or its portable version by visiting the download page. Then,
you can extract (or install) the download file to a folder e.g., C:\sqlite\gui\ and launch it.

The following picture illustrates how to launch the SQLiteStudio:


Database Systems Lecture notes
By Wycliffe Mwebi

Other SQLite GUI tools


Besides the SQLite Studio, you can use the following free SQLite GUI tools:

 DBeaver is another free multi-platform database tool. It supports all popular major relational
database systems MySQL, PostgreSQL, Oracle, DB2, SQL Server, Sybase.. including SQLite.

 DB Browser for SQLite – is an open-source tool to manage database files compatible with
SQLite.

SQLite Sample Database


I will first introduce you to an SQLite sample database. Then, I will give you the links to download the
sample database and its diagram. At the end of the lecture, I will show you how to connect to the
sample database using the sqlite3 tool.

Introduction to chinook SQLite sample database


I provide you with the SQLite sample database named chinook. The chinook sample database is a good
database for practicing with SQL, especially SQLite.

The following database diagram illustrates the chinook database tables and their relationships.
Database Systems Lecture notes
By Wycliffe Mwebi

Chinook sample database tables


There are 11 tables in the chinook sample database.

Download SQLite sample database


You can download the SQLite sample database using the following link.

1. Download SQLite sample database


2. Extract the downloaded file from the zip file to C:\sqlite
Database Systems Lecture notes
By Wycliffe Mwebi

How to connect to SQLite sample database -Using SQLite Studio


1. Navigate to C:\sqlite\GUI\SQLiteStudio and launch SQLiteStudio

2. SQLiteStudio will launch as shown below;


Database Systems Lecture notes
By Wycliffe Mwebi

3. Click on Database > Add Database menu

4. On the File input textbox, click on the green (+) sign and select the chinook database you
downloaded.

5. Click on Test connection


6. If connection is successful, click OK.
Database Systems Lecture notes
By Wycliffe Mwebi

7. You should now see your chinook database on SQLite Studio as shown below;

8. Double click on the database name –Chinook to reveal all the tables within

How to write SQL Commands on SQLite


First open the SQL editor on SQLite studio as shown below;
Database Systems Lecture notes
By Wycliffe Mwebi

The SQL editor will open up as shown below;

Let’s say for example, you want to views all the records in the employees table.

SELECT *
FROM employees
Hit the execute query button
Database Systems Lecture notes
By Wycliffe Mwebi

Practice SQL exercises on Chinook database


Assignment 1
1. Write an SQL command that will print Name from the table Artist (for all the database entries)

SELECT name
FROM artists

2. Print all data from the table Invoice where BillingCountry is Germany

SELECT *
FROM invoices
WHERE BillingCountry = 'Germany'

3. Count how many albums are in the database. Hint: look for Min&Max and Count, Avg, Sum.

SELECT COUNT(*)
FROM albums

4. How many customers are from France?

SELECT COUNT(*)
FROM Customers
WHERE Country = 'France'

5. Which tracks are more expensive than $0.99?

SELECT *
FROM tracks WHERE UnitPrice > 0.99;

6. Which tracks are less expensive than $0.99? (Are there any?)

SELECT *
FROM tracks WHERE UnitPrice < 0.99;

7. Which tracks have the word "love" in the title?

SELECT *
FROM tracks WHERE Name like "%love%";

8. Which track titles begin with the word "love"?

select *
FROM tracks WHERE Name like "love%";

9. Which tracks were composed by Jimi Hendrix?


Database Systems Lecture notes
By Wycliffe Mwebi

10. Provide a query showing Customers (just their full names, customer ID and country) who are not in
the US
SELECT customerid, firstname, lastname, country
FROM customers
WHERE not country = 'USA'

11. Provide a query only showing the Customers from Brazil.


SELECT * from customers
WHERE country = 'Brazil';

12. Provide a query showing the Invoices of customers who are from Brazil. The resultant table should
show the customer's full name, Invoice ID, Date of the invoice and billing country.

SELECT [Link], [Link], [Link], [Link],[Link]


FROM customers as c, invoices as i
WHERE [Link] = 'Brazil' and
[Link] = [Link];

13. Provide a query showing only the Employees who are Sales Agents.
SELECT * from employees
WHERE [Link] = 'Sales Support Agent';

14. Provide a query showing a unique list of billing countries from the Invoice table.
SELECT distinct billingcountry
FROM invoices;

15. Provide a query showing the invoices of customers who are from Brazil.
SELECT *
FROM customers as c, invoices as i
WHERE [Link] = 'Brazil' and
[Link] = [Link];

16. Provide a query that shows the invoices associated with each sales agent. The resultant table should
include the Sales Agent's full name.
SELECT
[Link],
[Link],
[Link],
i.*
FROM Invoices i
JOIN Customers c ON [Link] = [Link]
Database Systems Lecture notes
By Wycliffe Mwebi

JOIN Employees e ON [Link] = [Link]


Where [Link] LIKE "Sales%Agent"
ORDER BY [Link];

17. Provide a query that shows the Invoice Total, Customer name, Country and Sale Agent name for all
invoices and customers.
SELECT [Link] as 'employee first',
[Link] as 'employee last',
[Link] as 'customer first',
[Link] as 'customer last',
[Link],
[Link]
FROM employees as e
join customers as c on [Link] = [Link]
join invoices as i on [Link] = [Link]

18. How many Invoices were there in 2009 and 2011? What are the respective total sales for each of
those years?
SELECT count([Link]), sum([Link])
FROM invoices as i
WHERE [Link] between datetime('2011-01-01 [Link]') and datetime('2011-12-31
[Link]');

19. Looking at the Invoice_items table, provide a query that COUNTs the number of line items for
Invoice ID 37.
SELECT count([Link])
FROM invoice_items as i
WHERE [Link] = 37

20. Looking at the Invoice_items table, provide a query that COUNTs the number of line items for each
Invoice. HINT: [GROUP BY]
SELECT invoiceid, count(invoice_items)
FROM invoice_items
GROUP by invoiceid

21. Provide a query that includes the track name with each invoice line item.
SELECT i.*, [Link]
FROM invoice_items as i, tracks as t
on [Link] = [Link]
Database Systems Lecture notes
By Wycliffe Mwebi

22. Provide a query that includes the purchased track name AND artist name with each invoice line
item.
SELECT i.*, [Link] as 'track', [Link] as 'artist'
from invoice_items as i
join tracks as t on [Link] = [Link]
join albums as al on [Link] = [Link]
join artists as ar on [Link] = [Link]

23. Provide a query that shows the # of invoices per country. HINT: [GROUP BY]
SELECT billingcountry, count(billingcountry) as '# of invoices'
FROM invoices
GROUP by billingcountry

24. Provide a query that shows the total number of tracks in each playlist. The Playlist name should be
included on the resultant table.
SELECT *, count(trackid) as '# of tracks'
FROM playlist_track, playlists
on playlist_track.playlistid = [Link]
GROUP BY [Link]

25. Provide a query that shows all the Tracks, but displays no IDs. The resultant table should include the
Album name, Media type and Genre.
SELECT [Link] as 'track', [Link], [Link], [Link], [Link], [Link] as 'album',
[Link] as 'genre', [Link] as 'media type'
FROM tracks as t
join albums as a on [Link] = [Link]
join genres as g on [Link] = [Link]
join media_types as m on [Link] = [Link]

26. Provide a query that shows all Invoices but includes the # of invoice items.

SELECT InvoiceId, (InvoiceId) as NumberInvoiceLineItem


FROM Invoice_items
GROUP BY InvoiceId

27. Provide a query that shows total sales made by each sales agent.
SELECT e.*, count([Link]) as 'Total Number of Sales'
FROM employees as e
JOIN customers as c on [Link] = [Link]
join invoices as i on [Link] = [Link]
GROUP BY [Link]
Database Systems Lecture notes
By Wycliffe Mwebi

28. Which sales agent made the most in sales in 2009?

SELECT *, max(total) from

(select e.*, sum(total) as 'Total'


FROM employees as e
JOIN customers as c on [Link] = [Link]
JOIN invoices as i on [Link] = [Link]
WHERE [Link] between '2009-01-00' and '2009-12-31'
GROUP BY [Link])

29. Which sales agent made the most in sales in 2010?

SELECT *, max(total)
FROM
(select e.*, sum(total) as 'Total'
FROM employees as e

JOIN customers as c on [Link] = [Link]


JOIN invoices as i on [Link] = [Link]
WHERE [Link] between '2010-01-00' and '2010-12-31'
GROUP BY [Link])

30. Which sales agent made the most in sales over all?

SELECT *, max(total) from


(select e.*, sum(total) as 'Total'
FROM employees as e
JOIN customers as c on [Link] = [Link]
JOIN invoices as i on [Link] = [Link]
GROUP BY [Link])

31. Provide a query that shows the # of customers assigned to each sales agent.

SELECT e.*, count([Link]) as 'TotalCustomers'


FROM employees as e
JOIN customers as c on [Link] = [Link]
GROUP BY [Link]

32. Provide a query that shows the total sales per country. Which country's customers spent the most?

SELECT [Link], sum(total) as 'TotalSales'


FROM invoices as i
GROUP BY billingcountry
ORDER BY totalsales desc
Database Systems Lecture notes
By Wycliffe Mwebi

33. Provide a query that shows the most purchased track of 2013.

SELECT *, count([Link]) as count


FROM invoice_items as il
JOIN invoices as i on [Link] = [Link]
JOIN tracks as t on [Link] = [Link]
WHERE [Link] between '2013-01-01' and '2013-12-31'
GROUP BY [Link]
ORDER BY count desc

34. Provide a query that shows the top 5 most purchased tracks over all.
35. Provide a query that shows the top 3 bestselling artists.
36. Which albums are by Aerosmith?

SELECT name, title


FROM artists
JOIN albums on [Link] = [Link]
WHERE Name = "Aerosmith";

37. Who is the album "Facelift" by?

SELECT Name
FROM Artists
JOIN Albums on [Link] = [Link]
WHERE Title = "Facelift";

38. Which albums are by Amy Winehouse?

SELECT Name, Title


FROM Artists
JOIN Albums on [Link] = [Link]
WHERE Name = "Amy Winehouse";

39. Which tracks are on the album "Frank"?

SELECT Name
FROM Tracks
JOIN Albums on [Link] = [Link]
WHERE [Link] = "Frank";

40. Which album is the track "Daughter" on?

SELECT Title, Name


FROM Albums
JOIN Tracks on [Link] = [Link]
WHERE Name = "Daughter";
Database Systems Lecture notes
By Wycliffe Mwebi

41. Which tracks are by Amy Winehouse?

SELECT [Link], [Link], [Link]


FROM Artists
JOIN Albums on [Link] = [Link]
JOIN Tracks on [Link] = [Link]
WHERE [Link] = "Amy Winehouse";

42. Which tracks are on the playlist "Brazilian Music"?

SELECT [Link], [Link]


FROM Playlists
JOIN Playlist_Track on Playlist_Track.PlaylistId = [Link]
JOIN Tracks on Playlist_Track.TrackId = [Link]
WHERE [Link] = "Brazilian Music";

43. Which tracks are on the playlist "Brazilian Music" and who are they by?

SELECT [Link], [Link], [Link], [Link]


FROM Playlists
JOIN Playlist_Track on Playlist_Track.PlaylistId = [Link]
JOIN Tracks on Playlist_Track.TrackId = [Link]
JOIN Albums on [Link] = [Link]
JOIN Artists on [Link] = [Link]
WHERE [Link] = "Brazilian Music";

44. How many tracks are there on the album "Facelift"?

SELECT count(*)
FROM Tracks
JOIN Albums on [Link] = [Link]
WHERE Title = "Facelift";

45. How many albums are there by Amy Winehouse?

SELECT count(*)
FROM Artists
JOIN Albums on [Link] = [Link]
WHERE Name = "Amy Winehouse";

46. How much would it cost to buy all the tracks?

SELECT SUM(UnitPrice)
FROM Tracks;

47. What's the longest track?

SELECT Name, max(Milliseconds)


FROM Tracks;
Database Systems Lecture notes
By Wycliffe Mwebi

48. What's the shortest track?

SELECT Name, min(Milliseconds)


FROM Tracks;

49. How many tracks are there by each of Amy Winehouse's albums?

SELECT [Link], [Link], count(*)


FROM Artists
JOIN Albums on [Link] = [Link]
JOIN tracks on [Link] = [Link]
WHERE [Link] = "Amy Winehouse"
GROUP BY title;

50. How expensive would it be to buy each of Amy Winehouse's albums?

SELECT [Link], [Link], SUM([Link])


FROM Artists
JOIN Albums on [Link] = [Link]
JOIN Tracks on [Link] = [Link]
WHERE [Link] = "Amy Winehouse"
GROUP BY title;

51. How many songs are on each playlist? Order by the number of songs on each playlist, most to least.

SELECT [Link], count(*)


FROM Playlist_Track
JOIN Playlists on [Link] = Playlist_Track.PlaylistId
GROUP BY Playlist_Track.PlaylistId
ORDER BY count(*) desc;

52. How many albums are there for each artist? Arrange by number of albums in descending order and I
only want the top 5.
SELECT [Link], count(*)
FROM Artists
JOIN Albums on [Link] = [Link]
GROUP BY [Link]
ORDER BY count(*) desc
limit 10;

53. What are the top 5 longest albums and who are they by?
SELECT [Link], [Link], sum(Milliseconds)
FROM Tracks
JOIN Albums on [Link] = [Link]
JOIN Artists on [Link] = [Link]
GROUP BY [Link]
ORDER BY sum(Milliseconds) desc
limit 5;
Database Systems Lecture notes
By Wycliffe Mwebi

Exercises
Attempt the following exercises;

 SQLite Basic SELECT statement [18 Exercises]

 SQLite Restricting and Sorting Data [9 Exercises with Solutions]

 SQLite Aggregate Functions and Group by [14 Exercises with Solutions]

 SQLite Subqueries [18 Exercises with Solution ]

 SQLite JOINS [11 Exercises with Solution]

You might also like