D02c+ +Writing+SQL+Statements
D02c+ +Writing+SQL+Statements
Database
Recall that a database is a set of data stored on one or more computers or servers.
Take as an example, a librarian has keyed in the book and borrower details given in
the previous lessons.
The book details are stored in Book table, with the publisher details stored in Publisher
table, the borrower’s details in Borrower table and the loans made in Loan table. The
intention is to be able to retrieve, edit or delete the data easily.
This can be done through Data Manipulation Language (DML) statements like
SELECT, INSERT, UPDATE and DELETE.
In this lesson, we will learn the SQL syntax to run the various queries in the database.
To enter SQL into DB Browser, after loading the database, click on the Execute SQL
tab. There is a text area for you to type in your SQL commands.
You can also click on the buttons above the text area.
After executing SQL commands or making changes, you can click the following:
Let us now look at the SQL statements that you can enter.
The SELECT statement allows the user to retrieve data from the database.
You can also find NULL values, for example books with no publishers (no value on the
PublisherID field), using the IS operator.
SELECT * from Book WHERE PublisherID IS NULL
You can also search for terms which are not NULL, for example:
SELECT * from Book WHERE PublisherID IS NOT NULL
This statement returns all records where there is a publisher.
You can insert more than one condition using AND and OR binary operators.
For example,
SELECT * FROM Book WHERE Title = 'Life of Pie' AND Damaged = 0
This statement returns the books with Title ‘Life of Pie’ and are not damaged.
This statement will give you all the Title of the books in the Book table.
Title
The Lone Gatsby Do you know?
A Winter’s Slumber You can execute multiple SQL
Life of Pie statements, but each statement must end
A Brief History Of Primates with a colon ;
To Praise a Mocking Bird
The Catcher in the Eye
H2 Computing Ten Year Series
Quiz
1. Which of the following SQL statements show all data inside the Publisher table?
(Tick the statements)
2. Write down the SQL statement to show all the Names of the publishers inside
the Publisher table.
…………………………………………………………………………………………
…………………………………………………………………………………………
…………………………………………………………………………………………
4. Write down the SQL statement to show all the Titles of the books which have
PublisherID 1 or 2.
…………………………………………………………………………………………
…………………………………………………………………………………………
To list all loans, the SQL statement SELECT * FROM Loan is used.
ID BorrowerID BookID Date Borrowed
1 3 2 20180220
2 3 1 20171215
3 2 3 20171231
4 1 5 20180111
The list can be ordered by the BookID (in ascending order) instead by using the SQL
statement SELECT * FROM Loan ORDER BY BookID ASC
The list can be ordered by the BookID (in descending order) by using the SQL
statement SELECT * FROM Loan ORDER BY BookID DESC
Quiz
5. Write down the SQL statement to select all the records in Loan table arranged
in ascending order of BookID with BorrowerID = 3.
…………………………………………………………………………………………
You can use function COUNT to get the answer. The SQL can be the following:
SELECT COUNT(*) FROM Loan
SQL JOIN
A SQL JOIN allows the combination of data from two sets of data (i.e. two tables).
There are different types of joins. We look at three: cross join, inner join and left
outer join.
Cross join returns the Cartesian product of rows from the tables in the join. It combines
each row in the first table with each row in the second table.
Notice that there are two columns of ID. The first ID column is from Book table, while
the second ID column is from the Publisher table.
Think:
How can the attribute names in Book and Publisher be renamed to remove the
confusion over the ID columns?
The table above is a big table, with a lot of necessary rows. It is more useful to have
the publisher of the title of each book. To do that, we can add a condition.
This table is more meaningful as it links the titles to the publishers. However, notice
that the title ‘H2 Computing Ten Year Series’ is not included as it has no PublisherID.
This is an example of inner join. Inner join can also be explicitly defined, like left outer
join, which we will learn next.
For example, the SQL statement above gives the following results:
ID Title PublisherID Damaged ID Name
1 The Lone Gatsby 5 0 5 Yellow Flame
2 A Winter's Slumber 4 1 4 Squirrel
3 Life of Pie 4 0 4 Squirrel
4 A Brief History Of Primates 3 0 3 Appleson
5 To Praise a Mocking Bird 2 0 2 Unpop
6 The Catcher in the Eye 1 1 1 NPH
Notice that there are two columns of ID. The first ID column is from Book table, while
the second ID column is from the Publisher table.
The results are different. This is because all records in Book are included in the left
outer join, even books who have no publishers, unlike the inner join.
…………………………………………………………………………………………
…………………………………………………………………………………………
UPDATE
The UPDATE command allows the editing of data values in a database. One or more
records may be updated at the same time.
For example, all the books borrowed by Kumara (BorrowerID 3) should have been
borrowed by Sarah (BorrowerID 2). Then, the following SQL statement can be carried
out to update the Loan table.
UPDATE Loan Set BorrowerID = 2 WHERE BorrowerID = 3
Quiz
7. All the books borrowed by Sarah (BorrowerID 2) should have been borrowed
by Kumara (BorrowerID 3). Write down the SQL statement to update the Loan
table.
…………………………………………………………………………………………
…………………………………………………………………………………………
INSERT INTO
For example, to insert a new publisher, we can use the following SQL:
INSERT INTO Publisher(Name) VALUES ('BigBooks')
This will insert the publisher ‘BigBooks’ from the Publisher table.
You can check by selecting Publisher table under ‘Browse Data’ tab.
Notice that the ID is automatically given! Do you know how the database does it?
(Hint: Answer is found later…)
DELETE
For example,
DELETE FROM Book WHERE Title = 'Life of Pie'
This will delete the book ‘Life of Pie’ from the Book table.
Please note that the text is case-sensitive, which means that the following 2 SQL
statements are different.
DELETE FROM Book WHERE Title = 'Life of Pie'
DELETE FROM Book WHERE Title = 'Life of pie'.
Quiz
8. Which of the following SQL statements are valid? (Tick the statements)
CREATE TABLE
The CREATE TABLE command allows you to a table. You can see the SQL code for
the various tables under Database Structure in DB Browser.
For example, to create the Borrower table, you can key in:
CREATE TABLE 'Borrower' (
'ID' INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
'FirstName' TEXT NOT NULL,
'Surname' TEXT NOT NULL,
'Contact' INTEGER NOT NULL
)
This table is used by SQLite so as to keep track of the next number to give for tables
with AUTOINCREMENT. It is generated automatically when you have an
AUTOINCREMENT field used in SQLite.
Let us look at the Book table next. The SQL code to create the table is:
Notice the line starting with FOREIGN KEY. It defines the foreign key, which is the
field linking to the primary key of another table. For this example, it is linking the
PublisherID field in the Book table to the ID field in the Publisher table.
Quiz
9. Key in SQL statement to create a table Testing with fields name, tag_no and
remarks. The fields name and remarks should accept text, while tag_no is an
integer automatically incremented. The primary key is tag_no. Name field
should not be NULL.
…………………………………………………………………………………………
…………………………………………………………………………………………
…………………………………………………………………………………………
…………………………………………………………………………………………
Tip!
You can click ‘Revert Changes’ in DB Browser to remove the recent changes made.
What is the difference between DELETE FROM Loan and DROP TABLE Loan?
With DELETE FROM Loan, you delete all entries from the Loan table, but the Loan
table remains there. With DROP TABLE Loan, the Loan table will be removed. You
cannot insert any entries into Loan table anymore.
Quiz
10. Try keying DROP TABLE Publisher to remove the table containing the
publishers. Is it possible? Why?
…………………………………………………………………………………………
…………………………………………………………………………………………
Operators
You have seen some operators being used in the examples earlier. These operators
are often used in SELECT statements, but can be used in other statements (like the
UPDATE statement example shown earlier). The following are comparison
operators, logical operators and arithmetic operators that you need to know.
A. Comparison Operators
Comparison Description
Operator
= Checks if the values of two operands are equal or not, if yes
then the condition becomes true.
!= Checks if the values of two operands are equal or not, if the
values are not equal, then the condition becomes true.
<> Checks if the values of two operands are equal or not, if the
values are not equal, then the condition becomes true.
> Checks if the values of the left operand is greater than the
value of the right operand, if yes then the condition becomes
true.
< Checks if the values of the left operand is less than the value
of the right operand, if yes then the condition becomes true.
>= Checks if the value of the left operand is greater than or equal
to the value of the right operand, if yes then the condition
becomes true.
<= Checks if the value of the left operand is less than or equal to
the value of the right operand, if yes then the condition
becomes true.
|| String concatenation
C. Arithmetic Operators
Arithmetic Name Description
Operator
+ Addition Adds values on either side of the operator
- Subtraction Subtracts the right-hand operand from the left-
hand operand
* Multiplication Multiplies values on either side of the operator
/ Division Divides the left-hand operand by the right-hand
operand
% Modulus Divides the left-hand operand by the right-hand
operand and returns the remainder
Functions
Function Description
MIN Minimum value
MAX Maximum value
SUM Sum of all values
COUNT Number of values
1. List the courses in TP that has more than 250 males in 2017.
…………………………………………………………………………………………
…………………………………………………………………………………………
…………………………………………………………………………………………
…………………………………………………………………………………………
3. List out all fields in the table for courses not in School of Informatics & IT in
2016.
…………………………………………………………………………………………
…………………………………………………………………………………………
…………………………………………………………………………………………
…………………………………………………………………………………………
…………………………………………………………………………………………
…………………………………………………………………………………………
6. Rename the all diplomas called ‘Diploma in Cyber & Digital Security’ to
‘Diploma in Cyber and Digital Security’.
…………………………………………………………………………………………
…………………………………………………………………………………………
7. Update the table to add 5 students to each gender and each course in School
of Design in 2017.
…………………………………………………………………………………………
…………………………………………………………………………………………
References
Content Links
SQL https://www.webucator.com/tutorial/learn-sql/simple-selects.cfm
https://www.tutorialspoint.com/sql/sql-and-or-clauses.htm
https://www.bbc.com/education/guides/z37tb9q/revision/5
https://www.w3schools.com/sql/default.asp