Updated SQL Practical Guide Book
Updated SQL Practical Guide Book
The SQL Command Testing App was created by the department of computer science. This app is
designed as an easy-to-use tool for students to practice SQL. It provides an opportunity to become
familiar with all SQL commands effortlessly. During day school SQL lessons and practical sessions,
the lecturer explains how to use this app and demonstrates how to execute commands through it.
This application simplifies the process of learning SQL and helps students gain practical experience.
Such software tools facilitate the development of technical skills for students. By providing a user-
friendly platform for SQL practice, it enhances the learning experience and allows students to apply
theoretical knowledge in a practical setting.
1. XAMPP: Provides a local environment with MySQL and phpMyAdmin for easy setup.
2. Online platforms:
o SQLZoo
o LeetCode
o HackerRank These offer interactive tutorials and challenges for SQL practice.
3. Local installations:
o MySQL Workbench
o DBeaver
o PostgreSQL with pgAdmin These provide robust environments for various database
systems.
4. SQL simulators:
o Oracle Live SQL
o Microsoft SQL Server with SSMS (SQL Server Management Studio) These cater to
specific database technologies.
The choice of platform depends on individual needs, preferred database system, and whether a local or
online setup is desired. Many developers use multiple tools to broaden their SQL expertise across
different systems.
While the SQL Command Testing App is a valuable resource for day school students, these additional
tools offer a wide range of options for comprehensive SQL learning and practice. This diversity allows
learners to gain experience with different database environments and challenges, ultimately enhancing
their overall database management skills.
1/62
SQL Commands Testing App
You can access the online SQL application directly via http://labs.ou.ac.lk. There is no
need to use internal or external IP addresses for access.
Then, click Login SQL App button. Enter your registration number for both user name
and password.
2/62
To create the database, type in the command line. Example:
MY_DB
Or
Click on 'Create New Database' tab. A dialog box will appear, allowing you to enter the
database name in the designated area.
Select the database. Then, type the commands and execute commands.
MY_DB
You can get all the typed commands by selecting the Previous SQL option.
3/62
Semicolon after SQL Statements?
Some database systems require a semicolon at the end of each SQL statement. Semicolon is the
standard way to separate each SQL statement in database systems that allow more than one SQL
statement to be executed in the same call to the server. We are using MySQL and we have put a
semicolon after each SQL statement, but some database programs force you to use it.
4/62
1. DATA DESIGN LANGUAGE (DDL)
a) Create a Database.
Now we want to create a database called “my_db”. We use following CREATE DATABASE statement:
5/62
b) Use Database
Before create table, we have to select the relevant database by using USE command.
c) Create a Table
The data type specifies what type of data the column can hold. For a complete reference of all
the data types available in MS Access, MySQL Server, go to last in this note you can complete
Data Types reference.
Primary Key
The PRIMARY KEY constraint uniquely identifies each record in a table. Primary keys must contain
UNIQUE values, and cannot contain NULL values.
Foreign Key
A FOREIGN KEY is a key used to link two tables together. A FOREIGN KEY is a field (or
collection of fields) in one table that refers to the PRIMARY KEY in another table.
The table containing the foreign key is called the child table, and the table containing the
candidate key is called the referenced or parent table.
Now we want to create three tables called “Employee”, “Product” and “Category” in the my_db database.
6/62
Field Name Field type
E_no Int Field Name Field type
FirstName Varchar(255) P_no Int Field Name Field type
LastName Varchar(255) P_name Varchar(255) C_id Int
City Varchar(255) P_category Int C_name Varchar(255)
BirthYear Int E_no Int
Salary int Product table
Category table
Bonus int
Employee table
We use the following CREATE TABLE statements with including both primary keys and foreign keys:
CREATE TABLE Product ( P_no INT,P_name VARCHAR(255), P_category INT, E_no INT
);
The E_no,P_id,C_id columns are of type int and will hold a number. The LastName, FirstName,
City,C_name,P_name coloumns are of type varcher with a maximum length of 255 characters.
The empty tables will now look like this:
Data can be inserted by using SQL INSERT INTO statement. It will be discussed later in brief.
INSERT INTO employee VALUES
(536,'Sarath','Perera','matara',1988,25500,2500);
Inserting data to the table will be discussed under Data Manipulation language.
7/62
d) Alter Table
The ALTER TABLE statement enables to add, delete, or modify columns in an existing table.
8/62
e) Drop Table
The DROP TABLE command to completely remove a table from a database and it deletes table
along with all its associated constraints and indexes.
f) Drop Database
The DROP DATABASE statement is used to delete a database.
9/62
2. DATA MANIPULATION LANGUAGE (DML)
The INSERT INTO statement is used to insert new records in to a table. It is possible to write the
INSERT INTO statement on two forms. The first form doesn‟t specify the column names where
the data will be inserted, only their values.
The second form specifies both the column names and the values to be inserted.
According to the given two methods try to insert the data to EMPLOYEE, PRODUCT and
CATEGORY tables as shown below.
10/62
b) The UPDATE command.
Now we want to update the person “Kasun, Munasinghe” in the “Employee” table. We use the
following SQL statement.
Be careful when updating records. If we had omitted the WHERE clause in the
example above, like this:
UPDATE employee SET City=’Kandy’,Salary =50000;
The values of whole two columns will be the values which we give in the above code.
11/62
c) The SELECT statement
The SELECT statement is used to select date from a database. The result is stored in a result
Table, called the result-set.
And
SELECT * FROM table_name;
SQL is not case sensitive. SELECT is the same as select. An SQL SELECT Example.
We want to select the content of the columns named “FirstName” and “LastName” from the table
above. We use the following SELECT statement.
Now we want to select all column from the “Employee” table. We use the following SELECT statement:
Tip: The asterisk (*) is a quick way of selecting all columns! The result-set will look like this.
12/62
d. SELECT DISTICT Statement
In a table, some of the columns may contain duplicate values. This is not a problem, however, sometimes
you will want to list only the different (distinct) values in a table. The DISTINCT keywords can be used
to return only distinct (different) values.
The WHERE clause is used to extract only those records that fulfill a specified criterion.
We want to select only the products that belongs to “p_category no 3” from the Product table. We use the
following SELECT statement.
13/62
f. Qotes around Text Fields
SQL uses single quotes around text values (most database systems will also accept double quotes).
Although, numeric values should not be enclosed in quotes. For text values.
Operator Description
= Equal
<> Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
IN If you know the exact value you want to return for at least one of the columns
Now we want to select only the persons with the first name equal to “Kamal” AND the last name equal to
“Silva” from Employee Table: We use the following SELECT statement:
14/62
OR Operator Example
Now we want to select only the persons with the first name equal to “Nihal” OR the first name
equal to “Kamal” from Employee Table. We use the following SELECT statement.
Example: Select * from Employee where FirstName='Kamal' or
FirstName='Nihal';
15/62
k. ODER BY Keyword
The ORDER BY Keyword is used to sort a result-set. The ORDER BY keyword is used to sort the result-
set by a specified column. The ORDER BY keyword sort the records in ascending order by default. If you
want to sort the records in a descending order, you can use the DESC keyword.
Not e: SQL key words ASC and DESC refer Ascending order and Descending order respectively.
16/62
l. The TOP Clause
The TOP clause is used to specify the number of records to return. The TOP clause can be very useful on
large table with thousands of records. Returning a large number of records can impact on performance.
17/62
m. The LIKE Operator
The LIKE operator is used to search for a specified pattern in a column.
Now we want to select the employee first name that starts with “s” from the “EMPLOYEE” table. We
use the following SELECT statement
Now we want to select the employees living in a city that starts with “ma” from the “EMPLOYEE”
table. We use the following SELECT statement.
Note: The “%” sign can be used to define wildcards (missing letters in the pattern) both before and after
the pattern.
18/62
Next, we want to select the Last Name of the employees that contains the pattern “sin” from the
“EMPLOYEE” table. We use the following SELECT statement.
It is also possible to select the Last Name of the employees that NOT contains the pattern “sin” from
the “EMPLOYEE” table, by using the NOT keyword. We use the following SELECT Statement.
19/62
Now we want to delete the category “Hand Made” in the “CATEGORY” table. We use the following
SQL Statement.
20/62
q. Selecting Data from Another User’s Table.
Permission must be granted to a user to access another user‟s table. If no permission has been granted,
access is not allowed. Data can be selected from another user‟s table in a SELECT statement.
In the following example, it selects data from the table call “Item” which is in the database “database2”.
Therefore before you do this practical you should have created database2. Following are the syntax to
create the database2.
21/62
3. USING OPERATORS TO CATEGORIZE DATA
Comparison Operators
Comparison operators are used to test single values in a SQL statement. The comparison operators
consists of =, <>, <, > and these operators are used to test equality, non-equality, less than values, greater
than values respectively.
a. Equality
When testing for equality, the compared values must exactly or no data is returned. The following
example shows that salary equal to 15000 and 35000.
b. Non-equality
The condition returns TRUE if it the condition find non-equality, FALSE is returned if equality is found.
The following example shows all details of persons that salary not equal to 35000.
22/62
c. Less than and greater than
The symbols < (less than) and > (greater than) can be used by themselves or in combination with each
other or other operators.
23/62
e. Logical Operators
Is NULL operator
The NULL operator is used to compare a value with a null value. Consider the following table.
f. BETWEEN Operator
The between operator is used to search for values, given the minimum value and maximum value. The
following example shows that salary between 20000 and 30000.
24/62
g. IN operator
The IN operator is used to compare a value to a list of literal values that have been specified. The
following example shows using the IN operator to match all of the persons that have a salary within a
certain range of values.
h. LIKE operator
The LIKE operator is used to search for a specified pattern in a column.
Now we want to select the employee first name that starts with “s” from the “EMPLOYEE” table. We
use the following SELECT statement
i. Exit operator
Exists operator is used to search for the presence of a row in a specified table that meets certain criteria.
Syntax: SELECT column_name1, column_name2, ... FROM table_name WHERE EXISTS (SELECT
column_name FROM table_name WHERE condition);
Example: SELECT * FROM Employee WHERE EXISTS (SELECT E_no FROM Employee WHERE
E_no = '537');
25/62
j. ALL, SOME AND ANY operators
The ALL operator compares a value to all values in a subquery or list, ensuring the condition is true for each value.
Conversely, SOME and ANY are functionally the same, both checking if the condition is true for at least one value
in the subquery or list.
Syntax: SELECT column_name1, column_name2, ... FROM table_name WHERE expression operator
ANY (subquery);
Example: SELECT * FROM Employee WHERE Salary > ANY (SELECT Salary FROM Employee
WHERE City = 'Matara');
26/62
Conjunctive Operators
conjunctive operators in SQL with examples, focusing on their use in the WHERE clause. Conjunctive operators
allow us to combine multiple conditions in a single SQL statement, making our queries more specific and
powerful. We have already discussed about conjunctive operators under the WHERE Clause.
1. AND
2. OR
a. AND Operator
And Operator allows the existence of multiple condition in a SQL statements’ WHERE clause
Syntax: SELECT column1, column2, FROM Employee WHERE condition1 AND condition2 AND;
Example: SELECT FirstName, LastName, City, Salary FROM Employee WHERE City = 'Matara' AND
Salary > 30000;
b. OR Operator
The OR operator is used to combine multiple conditions in a SQL Statement’s WHERE clause
Syntax: SELECT column1, column2, ... FROM table_name WHERE condition1 OR condition2 OR
condition3 ...;
Example: SELECT C_id, C_name FROM Category WHERE C_name = 'Chocolate Collection' OR C_name
= 'Gift packs';
27/62
Negative Operators
a. Not equal.
The following example shows that salary not equal to 35000.
28/62
b. NOT BETWEEN
The following example shows that salary not between 20000 and 30000.
c. NOT IN
The following example shows using the NOT IN operator.
d. NOT LIKE
29/62
Following example shows that salary not ends with 5000.
e. IS NOT NULL
30/62
Arithmetic Operators
Arithmetic operators are used to perform mathematical function in SQL, the same as in other
languages
a. Addition
b. Subtraction
31/62
c. Multiplication
d. Division
32/62
4. SUMMARIZING DATA
Consider the EMPLOYEE table.
33/62
Example: SELECT COUNT(*)FROM employee;
The SUM function is used to return a total on the values of a column for a group of rows.
Syntax: SUM ([DISTINCT] COLUMN NAME)
Example: SELECT SUM(Salary) FROM Employee;
The AVG function is used to find the average value for a given group rows,
Syntax: AVG ([DISTINCT]COLUMN NAME);
Example: SELECT AVG(Salary) FROM Employee;
34/62
The MIN function
The MIN function is used to return the minimum value from the values of a column in a group of rows.
Syntax: MIN ((DISTINCT] COLUMN NAME);
Example: SELECT MIN(Salary) FROM Employee;
35/62
The HAVING Clause
Syntax: SELECT COLUMN 1, COLUMN 2 FROM TABLE1, TABLE 2 WHERE
CONDITIONS GROUP BY COLUMN1, COLUMN2 HAVING CONDITIONS
ORDER BY COLUMNI, COLUMN2;
Example: SELECT Salary, Bonus FROM Employee WHERE Bonus > 4000
GROUP BY Salary, Bonus HAVING Salary > 25000 ORDER BY
Salary;
CONCATINATION Function
SELECT column1+column2;
36/62
REPLACE Function
Syntax: REPLACE('VALUE','VALUE',[NULL]'VALUE');
Example: select C_Name,replace(C_Name,'c','k')from Category;
UPPER Function
Syntax: UPPER (character string);
Example: SELECT City,UPPER(City) FROM Employee;
37/62
LOWER Function
Syntax: LOWER (character string);
Example: SELECT City,LOWER(City) FROM Employee;
SUBSTRING Function
Syntax: SUBSTRING(COLUMN NAME,STARTING POSITION,LENGTH);
Example: SELECT SUBSTRING(City,1,3) FROM Employee;
38/62
INSTR function
Syntax: INSTR(COLUMN_NAME,'SET',[START POSITION ,[OCCURRENCE]]);
Example: SELECT FirstName,INSTR(FirstName,'a') FROM Employee;
LTRIM Function
RTRIM Function
39/62
LENGTH Function
LPAD Function
Syntax: LPAD (CHARACTER SET);
Example: SELECT LPAD(FirstName,30,'.') First_Name FROM employee;
40/62
RPAD Function
Syntax: RPAD(CHARACTER SET);
Example: SELECT RPAD(FirstName, 30,'.') First_Name FROM employee;
ASCII Function
Syntax: ASCII(CHARACTER SET);
Example: SELECT FirstName,ASCII(FirstName) ASCII FROM employee;
41/62
Mathematical Functions
Absolute Value
Returns the absolute value of a number
Rounding
Rounds the number to 'n' decimal places.
42/62
Square root
Finds the square root of the number argument.
Example : select sqrt(4);
Both SQL CEIL(or CEILING) and FLOOR functions are round the numbers. SQL CEIL roundup to me
nearest integer value while FLOOR round down to the next least integer value.
43/62
7. DATE AND TIME
This is to understand the nature of dates and time in SQL , how some implementation use dates, how to extract the
date and time in a desired format , and some of the common rules.
44/62
Format a date
Date arithmetic
Compare dates
Syntax: SELECT CASE WHEN CURRENT_DATE < '2024-12-31' THEN 'Future' WHEN CURRENT_DATE =
'2024-12-31' THEN 'Today' ELSE 'Past' END AS new_years_eve_status;
Command SELECT CASE WHEN CURRENT_DATE < '2024-12-31' THEN 'Future' WHEN CURRENT_DATE =
'2024-12-31' THEN 'Today' ELSE 'Past' END AS new_years_eve_status;
45/62
Convert string to date
46/62
8. JOINING TABLES IN QUERIES
The equijoin joins two tables with a common column in which each is usually the primary key.
Method 01
Now, Select the employee name and the products that each of them going to be purchases.
Method 02
47/62
ii. Natural Joins
A natural join is nearly the same as the equijoin; however, the natural join differs from the equijoin by
eliminating duplicate columns in the joining columns.
Method 01
Again we are going to Select the employee name and the products that each of them going to be purchases using
the Natural Join.
Method 02
48/62
iii. Non-equijoins
A non-equijoin joins two or more tables based on a specified column value not equalling a specified column
value in another table.
Next we are going to Select the employee name, Id and the products that each of them going to be purchases
using the Non-equijoins.
Because non-equality was tested in the join of the two tables, each row in the
first table is paired with all rows from the second table, except for its own
corresponding row.
This means that each of the 6 rows is paired with 5 unrelated rows in the
second table; 6 rows multiplied by 5 rows equals 30 rows total.
49/62
iv. Outer Joins
An outer join is used to return all rows that exist in one table, even though corresponding rows do not exist
in the joined table.
Select the Product names and Category names from tables product and category respectively.
The outer join is inclusive of all rows of data in the category table,
whether a corresponding row exists in the product table or not.
50/62
v. Self Joins
The self-join is used to join a table to itself, as if the table were two tables, temporarily renaming at least one
table in the SQL statement using a table alias.
Syntax : SELECT A.COLUMN_NAME,B.COLUMN_NAME,[C.COLUMN_NAME]
FROM TABLE1 A,TABLE2 B[,TABLE3 C ]
WHERE A.COLUMN_NAME = B.COLUMN_NAME
[AND A.COLUMN_NAME = C.COLUMN_NAME ]
The outer join is inclusive of all rows of data in the category table,
whether a corresponding row exists in the product table or not.
51/62
Join Considerations
Select the respective categories of products each of the employee going to purchase.
The product table which has the primary keys of both employee and
category tables is the BASE TABLE.
If you select from two or more tables and do not join the tables, your output is all possible rows from all the
tables selected.
Select the employee number, First name and the product names from employee and product tables.
52/62
Sub-Queries(Nested Queries)
Query embedded within the WHERE clause of another query to further restrict data returned by the query.
When a sub query is used in a query, the sub query is resolved first, and then the main query is resolved
according to the condition(s) resolved by the sub query.
Select the First name of the employee who purchases products from category 2.
53/62
Syntax for SELECT statement:
SELECT COLUMN_NAME[,COLUMN_NAME]
FROM TABLE1[TABLE2]
WHERE COLUMN_NAME OPERATORS
(SELECT COLUMN_NAME[,COLUMN_NAME]
FROM TABLE1[TABLE2]
WHERE CONDITION);
Select the Last name and salary of the employee who lives in Matara and purchases products from category 2.
54/62
Try to complete the
following questions with
the help of practical
Question guide.
Consider the following Schema of my company Database.
Field Name Field type Field Name Field type Field Name Field type
E_no Int P_no Int C_id Int
FirstName Varchar(255) P_name Varchar(255) C_name Varchar(255)
LastName varchar(255) P_category Int
City varchar(255) E_no Int
BirthYear Int
Salary int
Bonus int
EMPLOYEE
E_no FirstName LastName City BirthYear Salary Bonus
536 Sarath Perera matara 1988 25000 2500
537 Nihal Gamage Maharagama 1987 35000 6000
538 Kamal Silva Kandy 1989 25000 4500
539 Sunil De Soysa Matara 1985 35000 4000
540 Gayan Gunasinghe Homagama 1990 27000 6000
541 Kasun Munasinghe Kaluthara 1989 45000 5000
542 Nimal Kuruppu matara 1986 30000 3000
CATEGORY
PRODUCT
C_id C_name
P_no P_name P_category S_no 1 Chocolate Collections
10001 Almond Milk 1 539 2 Choco Collections
10002 Crispy Malt 2 542 3 Gift Packs
10003 Promises 3 537 4 Hand Made
10004 Legend 3 538 5 Wafer Chocolate
10005 Cashew nut 1 540 6 White Choco
23. Select Salary and Bonus of the employees who’s bonus greater than 4000 and having salary greater than
25000 from EMPLOYEE TABLE. (page 24 )
24. Combine the First name and Last name and rename as Full Name in EMPLOYEE TABLE. (page 25 )
25. Replace the letter “c” with “k” in category name in CATEGORY TABLE. (page 25 )
26. Change the case of city to Uppercase in EMPLOYEE TABLE. (page 26 )
27. Change the case of city to Lowercase in EMPLOYEE TABLE. (page 26 )
28. Select first 3 letters of the city name from EMPLOYEE TABLE. (page 26 )
29. Count in which place we can get the letter “a” in First name in EMPLOYEE TABLE. (page 27 )
30. Calculate the length of each product name and show each length p_name wise from PRODUCT
TABLE. (page 28 )
31. Round the given numbers. (page 30)
1.28
2.785 (to first decimal place)
3.845
25.9(CEILING)
25.9(FLOOR)
32. Find the square root of 25, 100, and 64. (page 30)
33. Select the employee name and the products that each of them going to be purchases using equijoin.
(page 31)
34. Select the employee name and the products that each of them going to be purchases using the Natural
Join. (page 32)
35. Select the employee name, Id and the products that each of them going to be purchases using the Non-
equijoins. (page 34)
36. Select the Product names and Category names from tables product and category respectively using
Outer join.(page 35)
37. Select the employee number, First name and the product names from employee and product tables and
check what you will get. (page 37)
38. Select the First name of the employee who purchases products from category 2 using sub queries. (page
38)
39. Select the Last name and salary of the employee who lives in Matara and purchases products from
category 2 using sub queries. (page 38)
57/62
Reference
MySQL Data Types
In MySQL there are three main data types: text, number, and date.
VARCHAR(size) Holds a variable length string (can contain letters, numbers, and
special characters). The maximum size is specified in parenthesis. Can
store up to 255 characters.
Note:If you put a greater value than 255 it will be converted to a
TEXT type
TINYTEXT Holds a string with a maximum length of 255 characters
TEXT Holds a string with a maximum length of 65,535 characters
BLOB For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data
MEDIUMTEXT Holds a string with a maximum length of 16,777,215 characters
MEDIUMBLOB For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of
data
LONGTEXT Holds a string with a maximum length of 4,294,967,295 characters
LONGBLOB For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes
of data
ENUM(x,y,z,etc.) Let you enter a list of possible values. You can list up to 65535 values
in an ENUM list. If a value is inserted that is not in the list, a blank
value will be inserted.
Note: The values are sorted in the order you enter them.
You enter the possible values in this format: ENUM('X','Y','Z')
SET Similar to ENUM except that SET may contain up to 64 list items and
can store more than one choice
59/62
SQL Server Data Types
60/62
numeric(p,s) Fixed precision and scale numbers. 5-17 bytes
Allows numbers from -10^38 +1 to 10^38 –1.
The p parameter indicates the maximum total number of
digits that can be stored (both to the left and to the right of
the decimal point). p must be a value from 1 to 38. Default
is 18.
The s parameter indicates the maximum number of digits
stored to the right of the decimal point. s must be a value
from 0 to p. Default value is 0
smallmoney Monetary data from -214,748.3648 to 214,748.3647 4 bytes
timestamp Stores a unique number that gets updated every time a row gets
created or modified. The timestamp value is based upon an
internal clock and does not correspond to real time. Each table
may have only one timestamp variable
61/62
Other data types:
sql_variant Stores up to 8,000 bytes of data of various data types, except text, ntext, and
timestamp
uniqueidentifier Stores a globally unique identifier (GUID)
xml Stores XML formatted data. Maximum 2GB
cursor Stores a reference to a cursor used for database operations
table Stores a result-set for later processing
62/62