0% found this document useful (0 votes)
34 views62 pages

Updated SQL Practical Guide Book

The SQL Command Testing App, developed by the computer science department, is a user-friendly tool designed for students to practice SQL commands effectively during their lessons. It simplifies the learning process and provides practical experience, complemented by additional resources such as XAMPP and various online platforms for comprehensive SQL training. The document also includes detailed instructions on using the app, SQL command syntax, and examples of data manipulation and design language.

Uploaded by

Manidu Udayanga
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)
34 views62 pages

Updated SQL Practical Guide Book

The SQL Command Testing App, developed by the computer science department, is a user-friendly tool designed for students to practice SQL commands effectively during their lessons. It simplifies the learning process and provides practical experience, complemented by additional resources such as XAMPP and various online platforms for comprehensive SQL training. The document also includes detailed instructions on using the app, SQL command syntax, and examples of data manipulation and design language.

Uploaded by

Manidu Udayanga
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/ 62

Introduction to SQL Commands Testing App

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 SQL Command Testing App is significant for several reasons:

1. Creation: It was developed by the computer science department.


2. Purpose: It was designed as an easily accessible application for students to practice SQL.
3. Utility: It allows for easy practice of all SQL commands.
4. Application: It is used for practical exercises in SQL courses at day schools.
5. Instruction: Lecturers explain how to use the application and how to execute SQL 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.

Here's an overview of additional SQL learning and practice resources:

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

How to Start Work with Command 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.

The CREATE DATABASE statement is used to create a database.

Syntax: CREATE DATABASE database_name;

Now we want to create a database called “my_db”. We use following CREATE DATABASE statement:

Example: create database cou3301_123456790_MY_DB;

Example: create database cou3301_123456790_ MY_DB_2;

5/62
b) Use Database
Before create table, we have to select the relevant database by using USE command.

Syntax: USE database_name;

Example: USE cou3301_123456790_AGENCYSYSTEM;

c) Create a Table

The CREATE TABLE statement is used to create a table in a database.

Syntax: CREATE TABLE table_name(colomn_name1 data_type,


column_name2 data_type, column_name3 data_type,………);

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.

Syntax: CREATE TABLE table_name(colomn_name1 data_type NOT NULL,


column_name2 data_type, column_name3 data_type,PRIMARY
KEY(colomn_name1));

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

Syntax: CREATE TABLE table_name(colomn_name1 data_type NOT NULL,


column_name2 data_type, column_name3 data_type,PRIMARY
KEY(colomn_name1),FOREIGN KEY(colomn_name)REFERENCES
table_name(colomn_name));

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 Employee ( E_no INT, FirstName VARCHAR(255), LastName


VARCHAR(255), City VARCHAR(255), BirthYear INT, Salary INT, Bonus INT );

CREATE TABLE Product ( P_no INT,P_name VARCHAR(255), P_category INT, E_no INT
);

CREATE TABLE Customer ( C_id INT, C_name VARCHAR(255));

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:

SELECT * FROM Employee;

SELECT * FROM Product;

SELECT * FROM Customer;

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.

 Add a column in a table

Syntax: ALTER TABLE table_name ADD column_name datatype;


Example: ALTER TABLE employee ADD NIC_No varcher (10);

 Delete a column in a table

Syntax: ALTER TABLE table_name DROP COLUMN column_name;


Example: ALTER TABLE employee DROP COLUMN NIC_No;

 Change the data type of column in a table

Syntax: ALTER TABLE table_name ALTER COLUMN/MODIFY COLUMN


column_name datatype;
Example: ALTER TABLE employee ALTER COLUMN/MODIFY COLUMN NIC_No
int;

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.

Syntax: DROP TABLE table_name;


Example: DROP TABLE Persons;

f) Drop Database
The DROP DATABASE statement is used to delete a database.

Syntax: DROP database database_name;

Example: DROP database cou3301_123456790_AGENCYSYSTEM;

9/62
2. DATA MANIPULATION LANGUAGE (DML)

a) The INSERT command.

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.

Syntax: INSERT INTO table_name VALUES(value1, value2, value3,…);

Example: INSERT INTO Employee (E_no, FirstName, LastName, City,


BirthYear, Salary, Bonus) VALUES (536, 'Sarath', 'Perera',
'Matara', 1988, 25500, 2500, NULL);

The second form specifies both the column names and the values to be inserted.

Syntax: INSERT INTO table_name VALUES (colomn_name1, colomn_name2,


colomn_name3,…) VALUES(value1, value2, value3,…);
Example: INSERT INTO Employee
VALUES(537,'Nihal','Gamage','Maharagama,1987,35000,6000
);

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.

The UPDATE statement is used to update records in a table.

Syntax: UPDATE table_name SET column1=value, column2=value2,….


WHERE some_column=some_value;

Now we want to update the person “Kasun, Munasinghe” in the “Employee” table. We use the
following SQL statement.

Example: UPDATE employee SET City=’Kandy’ WHERE FirstName=‘Kasun’;

SQL UPDATE Warning

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.

Syntax: SELECT column_name(s) FROM table_name;

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.

Example: SELECT FirstName,LastName FROM Employee;

The result-set will look like this.

Now we want to select all column from the “Employee” table. We use the following SELECT statement:

SELECT * FROM employee;

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.

Syntax: SELECT DISTINCT Column_name (s) FROM table_name;


Example: SELECT DISTINCT City FROM Employee;

e. The WHERE Clause

The WHERE clause is used to extract only those records that fulfill a specified criterion.

Syntax: SELECT column_name(s) FROM table_name WHERE column_name


operator value;

We want to select only the products that belongs to “p_category no 3” from the Product table. We use the
following SELECT statement.

Example: Select * from product where p_category=3;

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.

This is correct: SELECT * FROM employee WHERE FirstName = ‘Nihal’;


This is wrong: SELECT * FROM employee WHERE FirstName = Nihal;

For numeric values:

This is correct: SELECT * FROM employee WHERE BirthYear = 1985;


This is wrong: SELECT * FROM employee WHERE BirthYear = ‘1965’;

g. Operators Allowed in the WHERE Clause


With the WHERE clause, the following operators can be used.

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

In some versions of SQL the <> operator may be written as! =

h. The AND operators (Conjunctive Operators)


The AND operator displays a record if both the first condition and the second condition is true. The OR
operator display a record if either the first condition or the second condition is true.

 AND Operator Example

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:

Example: Select * from employee where FirstName='Kamal' and


LastName='silva';

The result-set will look like this.

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

 Combining AND &OR


You can also combine AND and OR (use parenthesis to form complex expressions.) Now we
want to select only the persons with the City equal to “Matara” AND the first name equal to
“Sunil” OR to “Sarath”: We use the following SELECT statement:
Example: SELECT * FROM Employee WHERE City = 'Matara'
AND (FirstName = 'Sunil' OR FirstName
'Sarath');

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.

Syntax: SELECT column_name(s) FROM table_name ORDER BY column_name


(s) ASC/ DESC

Example: select * from Employee order by FirstName asc;

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.

Note: Not all database systems support the TOP clause.

Syntax: SELECT TOP number/percent column_name (s) FROM table_name;


Syntax: SELECT column_name (s) FROM table_name LIMIT number;

Consider the following table.

Example: SELECT * FROM employee LIMIT 2;

17/62
m. The LIKE Operator
The LIKE operator is used to search for a specified pattern in a column.

Syntax: SELECT Column_name (s) FROM table_name WHERE column_name


LIKE pattern;

 Now we want to select the employee first name that starts with “s” from the “EMPLOYEE” table. We
use the following SELECT statement

Example: select * from employee where FirstName like 's%';

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

Example: select * from employee where City like 'ma%';

Note: The “%” sign can be used to define wildcards (missing letters in the pattern) both before and after
the pattern.

The result-set will look like this.

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.

Example: select * from Employee where LastName like '%sin%';

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

Example: select * from Employee where LastName not like '%sin%';

n. The DELETE command.


The DELETE statement is used to delete rows in a table.

Syntax: DELETE FROM table_name WHERE some_column=some_value;

Look at the following Category table.

19/62
Now we want to delete the category “Hand Made” in the “CATEGORY” table. We use the following
SQL Statement.

Example: delete from Category where C_name='Hand made';

o. Delete All Rows:


It is possible to delete all rows in a table without deleting the table. This means that the table structure,
Attributes and indexes will be intact.

Syntax: DELETE FROM table_name; - or – DELETE * FROM table_name;

p. Counting the Records in a Table.


A simple query can be issued on a table to get a quick count of the number of records in the table or on
the number of values for a column in the table.

Syntax: SELECT COUNT(*) FROM table_name;

Example: SELECT COUNT(*) FROM employee;

Counting the numbe r of values in particular column, in a table.

Syntax: SELECT COUNT(column_name) FROM table_name;

Example: select count(firstname) from employee;

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.

Syntax: SELECT column_name FROM schema.database_name;

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.

Example: SELECT I_Name FROM database2.item;

r. Using Column Aliases.


You can give a table or a column another name by using an alias. This can be a good thing to do if you
have very long or complex table names or column names. An alias name could be anything, but usually it
is short.

Syntax: SELECT column_name alias_name FROM table_name;


SELECT column_name AS alias_name FROM table_name;

Example: SELECT City Town FROM Employee;


SELECT City AS Town FROM Employee;

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.

Consider the “EMPLOYEE” table.

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.

Example - SELECT * FROM Employee WHERE salary = 15000;

Example - SELECT * FROM Employee WHERE salary = 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.

Example - SELECT * FROM Employee WHERE salary <> 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.

The following example shows that salary is less than 30000.

The following example shows that salary is Greater than 30000.

d. Combinations of Comparison Operators


The following example shows that salary is less than or equal to 30000.

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.

The following example shows that salary is NULL.

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.

Syntax: SELECT Column_name (s) FROM table_name WHERE column_name


LIKE pattern;

 Now we want to select the employee first name that starts with “s” from the “EMPLOYEE” table. We
use the following SELECT statement

Example: select * from employee where FirstName like 's%';

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.

The main conjunctive operators in SQL are:

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.

Note: ! = is same as <>.

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

The following example shows that salary not starts with 2.

29/62
Following example shows that salary not ends with 5000.

e. IS NOT NULL

Following example shows that salary is not n

30/62
 Arithmetic Operators

Arithmetic operators are used to perform mathematical function in SQL, the same as in other
languages

Consider the ‘EMPLOYEE’ table..

a. Addition

b. Subtraction

31/62
c. Multiplication

d. Division

e. Arithmetic Operator combinations

32/62
4. SUMMARIZING DATA
Consider the EMPLOYEE table.

 The COUNT function


The COUNT function used is used rows or values of column that do not contain a NULL value.

Syntax: SELECT COUNT [(*)ǀ(DISTINCT ǀ ALL)](Column_name)FROM


table_name;

Example: SELECT COUNT(Bonus) FROM employee;

Example: SELECT COUNT(DISTINCT Salary) FROM employee;

33/62
Example: SELECT COUNT(*)FROM employee;

 The SUM function

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

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;

 The MAX function


The MAX function is used to return the maximum value from the values of a column in a group of rows.
Syntax: MAX((DISTINCT]COLUMN NAME);
Exam ple: SELECT MAX(Salary) FROM Employ

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;

5. SORTING AND GROUPING DATA

 The GROUP BY Clause


The GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into
groups.
Syntax: SELECT column name FROM table name WHERE condition GROUP BY
column_name;
Example 1: SELECT Salary FROM Employee WHERE Bonus > 3000 GROUP BY
Salary;

Example 2: SELECT Salary,Bonus FROM Employee WHERE Bonus &gt; 3000


GROUP BY Salary, Bonus ORDER BY Bonus;

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;

6. RESTRUCTURING THE APPEARANCE OF DATA

Consider the EMPLOYEE,CATEGORY and PRODUCT tables.

 CONCATINATION Function

Syntax in SQL Server: SELECT column1||column2;

SELECT column1+column2;

Syntax in MySQL: SELECT CONCAT(column1,column2);

Example in MySQL: SELECT CONCAT (FirstName,' ',LastName) Full_Name FROM


employee;

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

The LTRIM function is to remove leading spaces.

Syntax: RTRIM( CHARACTER STRING);

Example: SELECT LTRIM(' Kamal');

 RTRIM Function

Like LTRIM, the RTRIM function is used to remove trailing spaces.

Syntax: RTRIM (CHARACTER STRING );

Example: S ELECT RTRIM('Kamal ');

39/62
 LENGTH Function

Syntax: LENGTH (CHARACTER STRING);


Example: SELECT P_Name,length(P_Name)from Product;

 IFNULL (NULL Value Checker)


Syntax: IFNULL('VALUE',’SUBSTITUTION’);
Example: SELECT BirthYear,ifnull(BirthYear,9999)from employee;

 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

General Syntax: FUNCTION(EXPRESSION);

 Absolute Value
Returns the absolute value of a number

Example 1 : Select abs(2);

Example 2 : Select abs(-32);

 Rounding
Rounds the number to 'n' decimal places.

Example 1 : select round (1.58);

Example 2: select round(1.298,1);

42/62
 Square root
Finds the square root of the number argument.
Example : select sqrt(4);

 Power (number1, number2)

Raises number l to the power of number2.

Example : Select power(10,2);

 Ceiling and floor values

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.

Example 1 : Select ceil(10.19);

Example 2 : Select ceiling(10.19);

Example 3 : select floor(10,19);

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.

 Get current date and time

Syntax: SELECT expression1 AS alias1, expression2 AS alias2, expression3 AS alias3;

Command: SELECT CURRENT_DATE AS today, CURRENT_TIME AS now, CURRENT_TIMESTAMP AS


timestamp;

 Extract parts of a date

Syntax: SELECT expression1 AS alias1, expression2 AS alias2, expression3 AS alias3;

Command: SELECT YEAR(CURRENT_DATE) AS current_year, MONTH(CURRENT_DATE) AS


current_month,DAY(CURRENT_DATE) AS current_day;

44/62
 Format a date

Syntax: SELECT DATE_FORMAT(date, format) AS alias;

Command: SELECT DATE_FORMAT(CURRENT_DATE, '%W, %M %d, %Y') AS formatted_date;

 Date arithmetic

Syntax: SELECT expression1 AS alias1, expression2 AS alias2, expression3 AS alias3;

Command: SELECT DATE_ADD(CURRENT_DATE, INTERVAL 7 DAY) AS week_from_now,


DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) AS month_ago,
DATEDIFF(CURRENT_DATE, '2023-01-01') AS days_since_new_year;

 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

Syntax: SELECT STR_TO_DATE('date_string', 'format') AS alias;

Command SELECT STR_TO_DATE('May 1, 2024', '%M %d, %Y') AS converted_date;

46/62
8. JOINING TABLES IN QUERIES

i. Equijoins or Inner Joins

The equijoin joins two tables with a common column in which each is usually the primary key.

Method 01

Syntax: SELECT TABLE1.COLUMN1, TABLE2.COLUMN2...


FROM TABLE1, TABLE2 [, TABLE3]
WHERE TABLE1.COLUMN_NAME =TABLE2.COLUMN_NAME;
[AND TABLE1.COLUMN_NAME = TABLE3.COLUMN_NAME]

Now, Select the employee name and the products that each of them going to be purchases.

Example: SELECT Employee.FirstName, Product.P_name


FROM Employee, Product
WHERE Employee. E_no=Product. E_no;

Method 02

Equijoin with the JOIN syntax is as follows.

Syntax: SELECT TABLE1.COLUMN1, TABLE2.COLUMN2...


FROM TABLE1
INNER JOIN TABLE2 ON TABLE1.COLUMN_NAME=TABLE2.COLUMN_NAME;

Example: SELECT Employee.FirstName, Product.P_name


FROM Employee
INNER JOIN Product ON Employee. E_no=Product. E_no;

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

Syntax: SELECT TABLE1.*, TABLE2.COLUMN_NAME...


FROM TABLE1, TABLE2 [, TABLE3]
WHERE TABLE1.COLUMN_NAME =TABLE2.COLUMN_NAME;
[AND TABLE1.COLUMN_NAME = TABLE3.COLUMN_NAME]

Again we are going to Select the employee name and the products that each of them going to be purchases using
the Natural Join.

Example: SELECT Employee.*, Product.P_name


FROM Employee, Product
WHERE Employee. E_no=Product. E_no;

Method 02

Natural join with the NATURAL JOIN syntax is as follows.

Syntax: SELECT TABLE1.*, TABLE2.COLUMN2...


FROM TABLE1
NATURAL JOIN TABLE2;

Example: SELECT Employee.*, Product.P_name


FROM Employee
NATURAL JOIN Product;

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.

Syntax: SELECT TABLE1.COLUMN_NAME, TABLE2.COLUMN_NAME...


FROM TABLE1, TABLE2 [, TABLE3]
WHERE TABLE1.COLUMN_NAME! =TABLE2.COLUMN_NAME;

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.

Example: SELECT Employee.E_no, Employee.LastName, Product.P_name FROM


Employee JOIN Product ON Employee.E_no <> Product.E_no;

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.

Syntax: SELECT TABLE1.COLUMN1, TABLE2.COLUMN2...


FROM TABLE1
{RIGHT|LEFT|FULL}[OUTER]JOIN TABLE2
ON TABLE1.COLUMN_NAME= TABLE2.COLUMN_NAME;

Select the Product names and Category names from tables product and category respectively.

Example: SELECT Product.P_name, Category.C_name FROM


Product RIGHT OUTER JOIN Category ON
Product.P_Category= Category.C_id;

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 ]

Example: SELECT A.LastName, B.LastName, A.FirstName


FROM Employee A,Employee B
WHERE A.LastName = B.LastName;

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

a. Using a Base Table

Select the respective categories of products each of the employee going to purchase.

Example: SELECT E.FirstName,E.LastName,C.C_name


FROM Employee E,product P,category C
WHERE E.E_no = P.E_no
AND C.C_id=P.P_category;

The product table which has the primary keys of both employee and
category tables is the BASE TABLE.

b. The Cartesian Product

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.

Syntax : SELECT TABLE1.COLUMN1,TABLE2.COLUMN2...


FROM TABLE1,TABLE2[,TABLE3]

Select the employee number, First name and the product names from employee and product tables.

Example: SELECT E.E_no,E.FirstName,P.P_name


FROM Employee E,Product P;

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.

Basic Syntax : SELECT COLUMN_NAME


FROM TABLE
WHERE COLUMN_NAME =( SELECT COLUMN_NAME
FROM TABLE
WHERE CONDITION);

Select the First name of the employee who purchases products from category 2.

Example: SELECT FirstName


FROM employee
WHERE E_no=(SELECT E_no
FROM product
WHERE P_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.

Example: SELECT LastName,Salary


FROM employee
WHERE City=’Matara’ AND E_no=(SELECT E_no
FROM product
WHERE P_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.

Employee (e_no, FirstName, LastName, City, BirthYear, Salary, Bonus)


Product (P_no, P_name, P_category, E_no)
Category (C_id, C_name)

Primary keys are underlined.


1. Create the following tables in my db database.
2. Apply the primary keys (cannot have null values), foreign keys for the tables.
3. Insert the given values to the tables.

EMPLOYEE PRODUCT CATEGORY

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

1. Display all values in EMPLOYEE, PRODUCT and CATEGORY tables.(page 6)


2. Add a column NIC_No varchar (10) to EMPLOYEE TABLE. (page 5 )
3. Delete the above added column from EMPLOYEE TABLE. (page 5 )
4. Change the city of “Kasun” as “Kandy” in EMPLOYEE TABLE. (page 7 )
5. Show the products which are belong to 3 category in PRODUCT TABLE. (page 9 )
55/62
6. Display the details of the person whose first name = “Kamal” and last name= “Silva” in
EMPLOYEE TABLE. (page 10 )
7. Select only the persons with the first name equal to “Nihal” OR the first name equal to “Kamal” from
EMPLOYEE TABLE. (page 10 )
8. Select only the persons with the City equal to “Matara” AND the first name equal to “Sunil” OR to
“Sarath” from EMPLOYEE TABLE. (page 11 )
9. Sort and arrange the EMPLOYEE table by first name in ascending order /descending order. (page 11 )
10. Select only the first 2 records from the EMPLOYEE TABLE. (page 12 )
11. Select all the employees’ first name that starts with “s” from the EMPLOYEE TABLE. (page 12 )
12. Select all the employees living in a city that ends with “ra” from the EMPLOYEE TABLE. (page 12 )
13. Select all the Last Name of the employees that contains the pattern “sin” from the EMPLOYEE
TABLE. (page 12 )
14. Select the Last Name of the employees that NOT contains the pattern “sin” from the EMPLOYEE
TABLE. (page 13 )
15. Remove the category “Hand Made” from CATEGORY TABLE. (page 14 )
16. Get the count of all the employees, products, categories in EMPLOYEE, PRODUCT AND
CATEGORY TABLES respectively. (page 14 )
17. Select the cities of each employee and display the City as Town from EMPLOYEE TABLE. (page 15
)
18. Show the results of
a) Salary equal to 15000
b) Salary equal to 35000
c) Salary less than 30000
d) Salary Greater than 30000
e) Salary less than or equal to 30000 from EMPLOYEE TABLE. (page 16 )
19. Show the results of
a) Salary is NULL.
b) Salary between 20000 and 30000
c) Salary within 25000, 35000, 45000 from EMPLOYEE TABLE. (page 17 )
20. Show the results of
a) Salary not equal to 35000
b) Salary not between 20000 and 30000
c) Salary not within 25000,35000,45000
d) salary not starts with 2
e) Salary is not NULL. from EMPLOYEE TABLE. (page 19 )
21. Show the results of following operations.
a) Salary + Bonus
b) Salary - Bonus
c) Salary * 10
d) Salary/30
e) Total of Salary
f) Average of Salary
g) Maximum amount of Salary
h) Minimum amount of Salary from EMPLOYEE TABLE. (page 21 )
22. Select the Salary of the employees whose bonus is greater than 3000 from EMPLOYEE TABLE.
56/62
(page 24 )

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.

Text data types:

Data type Description


CHAR(size) Holds a fixed length string (can contain letters, numbers, and special
characters). The fixed size is specified in parenthesis. Can store up to
255 characters

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

Number data types:

Data type Description


TINYINT(size) -128 to 127 normal. 0 to 255 UNSIGNED*.
The maximum number of digits may be specified in parenthesis
SMALLINT(size) -32768 to 32767 normal. 0 to 65535 UNSIGNED*.
The maximum number of digits may be specified in parenthesis
MEDIUMINT(size) -8388608 to 8388607 normal. 0 to 16777215 UNSIGNED*.
The maximum number of digits may be specified in parenthesis
INT(size) -2147483648 to 2147483647 normal. 0 to 4294967295 UNSIGNED*.
The maximum number of digits may be specified in parenthesis
58/62
BIGINT(size) -9223372036854775808 to 9223372036854775807 normal. 0 to
18446744073709551615 UNSIGNED*.
The maximum number of digits may be specified in parenthesis
FLOAT(size,d) A small number with a floating decimal point. The maximum number
of digits may be specified in the size parameter. The maximum
number of digits to the right of the decimal point is specified in the d
parameter
DOUBLE(size,d) A large number with a floating decimal point. The maximum number
of digits may be specified in the size parameter. The maximum
number of digits to the right of the decimal point is specified in the d
parameter
DECIMAL(size,d) A DOUBLE stored as a string , allowing for a fixed decimal point. The
maximum number of digits may be specified in the size parameter.
The maximum number of digits to the right of the decimal point is
specified in the d parameter

Date data types:

Data type Description


DATE() A date. Format: YYYY-MM-DD
Note: The supported range is from '1000-01-01' to '9999-12-31'
DATETIME() *A date and time combination. Format: YYYY-MM-DD HH:MI:SS
Note: The supported range is from '1000-01-01 00:00:00' to '9999-12-
31 23:59:59'

TIMESTAMP() *A timestamp. TIMESTAMP values are stored as the number of


seconds since the Unix epoch ('1970-01-01 00:00:00' UTC). Format:
YYYY-MM-DD HH:MI:SS

Note: The supported range is from '1970-01-01 00:00:01' UTC to


'2038-01-09 03:14:07' UTC
TIME() A time. Format: HH:MI:SS

Note: The supported range is from '-838:59:59' to '838:59:59'


YEAR() A year in two-digit or four-digit format.

Note: Values allowed in four-digit format: 1901 to 2155. Values


allowed in two-digit format: 70 to 69, representing years from 1970 to
2069

59/62
SQL Server Data Types

String data types:

Data type Description Max size Storage

char(n) Fixed width character string 8,000 characters Defined width


varchar(n) Variable width character 8,000 characters 2 bytes + number
string of chars
varchar(max) Variable width character 1,073,741,824 characters 2 bytes + number
string of chars
text Variable width character 2GB of text data 4 bytes + number
string of chars
nchar Fixed width Unicode string 4,000 characters Defined width x 2
nvarchar Variable width Unicode 4,000 characters
string
nvarchar(max) Variable width Unicode 536,870,912 characters
string
ntext Variable width Unicode 2GB of text data
string
binary(n) Fixed width binary string 8,000 bytes
varbinary Variable width binary string 8,000 bytes

varbinary(max) Variable width binary string 2GB


image Variable width binary string 2GB

Number data types:

Data type Description Storage


bit Integer that can be 0, 1, or NULL
tinyint Allows whole numbers from 0 to 255 1 byte
smallint Allows whole numbers between -32,768 and 32,767 2 bytes
int Allows whole numbers between -2,147,483,648 and 4 bytes
2,147,483,647
decimal(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

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

money Monetary data from -922,337,203,685,477.5808 to 8 bytes


922,337,203,685,477.5807
float(n) Floating precision number data from -1.79E + 308 to 4 or 8 bytes
1.79E + 308.
The n parameter indicates whether the field should hold 4
or 8 bytes. float(24) holds a 4-byte field and float(53)
holds an 8-byte field. Default value of n is 53.

real Floating precision number data from -3.40E + 38 to 3.40E 4 bytes


+ 38

Date data types:

Data type Description Storage


datetime From January 1, 1753 to December 31, 9999 with an accuracy 8 bytes
of 3.33 milliseconds
datetime2 From January 1, 0001 to December 31, 9999 with an accuracy 6-8 bytes
of 100 nanoseconds
smalldatetime From January 1, 1900 to June 6, 2079 with an accuracy of 1 4 bytes
minute
date Store a date only. From January 1, 0001 to December 31, 9999 3 bytes

time Store a time only to an accuracy of 100 nanoseconds 3-5 bytes


datetimeoffset The same as datetime2 with the addition of a time zone offset 8-10 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:

Data type Description

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

Microsoft Access Data Types

Data type Description Storage


Text Use for text or combinations of text and numbers. 255
characters maximum
Memo Memo is used for larger amounts of text. Stores up to 65,536
characters. Note: You cannot sort a memo field. However, they
are searchable
Byte Allows whole numbers from 0 to 255 1 byte
Integer Allows whole numbers between -32,768 and 32,767 2 bytes
Long Allows whole numbers between -2,147,483,648 and 4 bytes
2,147,483,647
Single Single precision floating-point. Will handle most decimals 4 bytes
Double Double precision floating-point. Will handle most decimals 8 bytes
Currency Use for currency. Holds up to 15 digits of whole dollars, plus 4 8 bytes
decimal places. Tip: You can choose which country's currency
to use
AutoNumber AutoNumber fields automatically give each record its own 4 bytes
number, usually starting at 1
Date/Time Use for dates and times 8 bytes
Yes/No A logical field can be displayed as Yes/No, True/False, or 1 bit
On/Off. In code, use the constants True and False (equivalent to
-1 and 0). Note: Null values are not allowed in Yes/No fields
Ole Object Can store pictures, audio, video, or other BLOBs (Binary Large up to 1GB
OBjects)
Hyperlink Contain links to other files, including web pages
Lookup Let you type a list of options, which can then be chosen from a 4 bytes
Wizard drop-down list

62/62

You might also like