department of computer science & it...jan 01, 1970 · a student may borrow some books from the...
TRANSCRIPT
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 1 of 120
Department of Computer Science & IT
Laboratory Manual (A Guide to MySQL)
Prepared by: Muhammad Nouman Farooq
Senior Lecturer
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 2 of 120
Course: Advance Database Systems (CS-214 & CS-514)
Table of Contents
Lab Activity 1- Database Design Phase (ERD) ………………………….… 3-6
Lab Activity 2- SQL Syntax, Keywords, DDL Commands ...……......….…. 7-15
Lab Activity 3- Data Manipulation Language (DML) Commands …........… 16-20
Lab Activity 4- SQL Select Statement, Where Clause & Operators …......… 21-31
Lab Activity 5- SQL Statements & Alias Syntax …………………...…....… 32-37
Lab Activity 6- SQL Union Operator, Joining & Views ………….…..….… 38-53
Lab Activity 7- Normalization up to Third Normal Form (3-NF) ..…...…..... 54-54
Lab Activity 8- SQL Aggregate Function .…..…............................................ 55-63
Lab Activities-Detailed Review- MySQL Coding using Console …..……... 64-120
Simulator Used: XAMPP Integrated Development Environment using
CONSOLE and Navicat Graphical User Interface (GUI)
Programming Language: SQL (Structured Query Language)
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 3 of 120
Lab 1- Database Design Phase (ERD)
1. ERD Designing:
Scenarios:
1. A player plays for a cricket team. In a cricket team, at least one or more player plays.
2. Each patient has at least one or more patient histories; each instance of patient history
belongs to one patient.
3. An employee may be recorded as having many jobs; a particular job may be recorded as
having been held by many employees.
4. A person is a citizen of a country. A country has more than one citizens.
5. A student may borrow some books from the library. A book in the library must be
borrowed by a student.
6. A student takes at least one course. A course is taken by at least one student.
Case Study 1:
Odeon Cinema and other international cinemas have decided to install a centralized database.
This database should keep information regarding cinemas including its name, address and phone
number. Each CINEMA must have one or more THEATERS and each theater has a specific
SHOWING TIME. During these showing times, a MOVIE is shown to the public.
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 4 of 120
Case Study 2:
In a school, students are allocated to different classes. Each student must be allocated to exactly
one class, and a class is formed by at least one or more than one student. Each class must be
managed by several different students on different posts, namely Monitors and Prefect. Draw an
E-R Diagram for the school, indicating Cardinalities.
2. ERD Reading:
Scenario 1:
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 5 of 120
Scenario 2:
Scenario 3:
Scenario 4:
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 6 of 120
Scenario 5:
Scenario 6:
End of Lab Activity 1
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 7 of 120
Lab Activity 2 – SQL Syntax, Keywords, DDL Commands
Step No. Details of the step
1
Data Definition Language Commands: -
It is used to communicate with database. DDL is used to:
o Create an object o Alter/Modify the structure of an object
o To drop the object created.
2 The commands used are: Create, Alter, Drop, Truncate
3
Integrity Constraint: -
An integrity constraint is a mechanism used to prevent invalid data entry into
the table. It has enforcing the rules for the columns in a table. The types of the
integrity constraints are:
a) Domain Integrity b) Entity Integrity c) Referential Integrity
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 8 of 120
4
a) Domain Integrity
This constraint sets a range and any violations that take place will prevent the
user from performing the manipulation that caused the breach. It includes:
Not Null Constraint:
While creating tables, by default the rows can have null value, the enforcement of
not null constraint in a table ensure that the table contains values.
Principle of Null Values:
o Setting null value is appropriate when the actual value is unknown, or when
a value would not be meaningful.
o A null value is not equivalent to a value of zero.
o A null value will always evaluate to null in any expression.
o When a column name is defined as not null, that column becomes a
mandatory i.e., the user must enter data into it.
o Not null Integrity constraint cannot be defined using the alter table
command when the table contain rows.
5
Check Constraint:
Check constraint can be defined to allow only a particular range of values. When
the manipulation violates this constraint, the record will be rejected. Check
condition cannot contain sub queries.
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 9 of 120
6
b) Entity Integrity
Maintains uniqueness in a record. An entity represents a table and each row of
a table represents an instance of that entity. To identify each row in a table
uniquely we need to use this constraint.
There are 2 entity constraints: Unique key Constraint
It is used to ensure that information in the column for each record is unique, as
with telephone or driver’s license numbers. It prevents the duplication of value
with rows of a specified column in a set of columns’. A column defined with
the constraint can allow null value.
If unique key constraint is defined in more than one column i.e., combination
of column cannot be specified. Maximum combination of columns that a
composite unique key can contain is 16. Primary Key Constraint
A primary key avoids duplication of rows and does not allow null values. It
can be defined on one or more columns in a table and is used to uniquely
identify each row in a table. These values should never be changed and should
never be null.
A table should have only one primary key. If a primary key constraint is
assigned to more than one column or combination of column is said to be
composite primary key, which can contain 16 columns.
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 10 of 120
7
c) Referential Integrity
It enforces relationship between tables. To establish parent-child relationship
between 2 tables having a common column definition, we make use of this
constraint. To implement this, we should define the column in the parent table
as primary key and same column in the child table as foreign key referring to
the corresponding parent entry. Foreign key
A column or combination of column included in the definition of
referential integrity, which would refer to a referenced key. Referenced key It is a unique or primary key upon which is defined on a column belonging to the parent table.
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 11 of 120
SQL CREATE DATABASE Syntax
DROP DATABASE IF EXISTS `dbname`;
CREATE DATABASE IF NOT EXISTS `dbname`;
USE `dbname`;
1. Create database northwind (Import northwind database)
SQL CREATE TABLE + CONSTRAINT Syntax
Drop TABLE IF EXISTS `database_name`.`table_name`;
CREATE TABLE IF NOT EXISTS `database_name`.`table_name` ( columnName1 data_type AUTO_INCREMENT PRIMARY KEY,
columnName2 data_type(size), columnName3 data_type NOT NULL, columnName4 data_type(size) DEFAULT 'anytext', UNIQUE (columnName3), -- CONSTRAINT `uk_columnname` UNIQUE (columnName3, columnName4..)
-- PRIMARY KEY (columnName),
/* CONSTRAINT pk_columnName PRIMARY KEY (columnName1, columnName2,………) for more than one columns */
/* PRIMARY KEY (columnName1, columnName2,………) -- Or use that syntax for more than one columns */
CONSTRAINT fk_columnName FOREIGN KEY (columnName) REFERENCES ParentTableName (columnName) ON update cascade on DELETE restrict,
-- CHECK (columnName > 0),
-- CHECK (columnName = ‘text’) );
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 12 of 120
2. Create the tables in the northwind database as per given SCHEMA Diagram
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 13 of 120
SQL SHOW DATABASE Syntax
SHOW DATABASES
show databases
SQL SHOW TABLES Syntax
SHOW TABLES
SQL INSERT INTO Syntax
The INSERT INTO statement is used to insert new records in a table.
INSERT INTO `database_name`.`table_name`
VALUES (value1,value2,value3,...); -- comment (single line)
/*
Multi line comment
*/
Insert Data Only in Specified Columns
It is also possible to only insert data in specific columns.
INSERT INTO `database_name`.`table_name` (column1,column2,column3)
VALUES (value1,value2,value3), (value1,value2,value3) …
3. Insert any 5 rows in all the tables of northwind database.
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 14 of 120
SQL ALTER TABLE Syntax
To add a column in a table, use the following syntax:
ALTER TABLE `database_name`.`table_name` ADD column_name datatype
To delete a column in a table, use the following syntax (notice that some database systems don't allow deleting a column):
ALTER TABLE `database_name`.`table_name` DROP COLUMN column_name
To change the data type of a column in a table, use the following syntax:
ALTER TABLE `database_name`.`table_name` MODIFY COLUMN column_name datatype
4. Practice to alter any column in any table in the northwind database.
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 15 of 120
The DROP TABLE Syntax
The DROP TABLE statement is used to delete a table.
DROP TABLE IF EXISTS `database_name`.`table_name`
The DROP DATABASE Syntax
The DROP DATABASE statement is used to delete a database. DROP DATABASE IF EXISTS `database_name`
The TRUNCATE TABLE Syntax
What if we only want to delete the data inside the table, and not the table itself?
Then, use the TRUNCATE TABLE statement: TRUNCATE TABLE `database_name`.`table_name`
5. Drop the table CUSTOMER from the northwind database.
6. Truncate the table PRODUCT.
7. Drop the northwind database.
8. Write a code for Lab 1-Database Design Phase (ERD)
End of Lab Activity 2
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 16 of 120
Lab Activity 3- Data Manipulation Language (DML) Commands
Step no. Details of the step
1
DML COMMAND DML commands are the most frequently used SQL commands and is used to query
and manipulate the existing database objects. Some of the commands are: -
Insert, Select, Update and Delete
2
Insert Command
This is used to add one or more rows to a table. The values are separated by commas
and the data types char and date are enclosed in apostrophes. The values must be
entered in the same order as they are defined.
3
Select Commands
It is used to retrieve information from the table. It is generally referred to as
querying the table. We can either display all columns in a table or only specify
column from the table.
4 Update Command
It is used to alter the column values in a table. A single column may be updated or
more than one column could be updated.
5
Delete command
After inserting row in a table, we can also delete them if required. The delete
command consists of a ‘FROM’ clause followed by an optional where clause.
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 17 of 120
The INSERT COMMAND Syntax
Inserting a single row into a table:
INSERT INTO `database_name`.`table name` VALUES (value list);
Example:
insert into customer.customer values (97, 'Nouman', '9km Bosan Road, ISP Main Campus, Multan', 'Multan', 'Punjab',
786)
Skipping the fields while inserting:
INSERT INTO database_name.tablename (column names to which data is to be
inserted) VALUES (list of values);
Note: Other way is to give null while passing the values.
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 18 of 120
The SELECT COMMAND Syntax
Selects all rows from the table:
SELECT * FROM database_name.tablename;
Example:
SELECT * FROM customer.customer;
The retrieval of specific columns from a table: It retrieves the specified columns from the table
SELECT column_name1, …..,column_name n FROM database_name.table name;
Example:
SELECT id, name FROM customer.customer;
Elimination of duplicates from the select clause: It prevents retrieving the duplicated values. Distinct keyword is to be used.
SELECT DISTINCT col1, col2 FROM database_name.table name;
Example:
SELECT DISTINCT name FROM customer.customer;
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 19 of 120
Select command with where clause: To select specific rows from a table we include “WHERE” clause in the select command. It
can appear only after the “FROM” clause.
SELECT column_name1, …..,column_name n FROM database_name.table name WHERE condition;
Example:
SELECT name FROM customer.customer WHERE id = 95;
Select command with order by clause: SELECT column_name1, …..,column_name n FROM database_name.table name
WHERE condition ORDER BY colmnname;
Example:
SELECT name FROM customer.customer ORDER BY id;
SELECT name FROM customer.customer ORDER BY id ASC;
SELECT name FROM customer.customer ORDER BY id Desc;
Select command to create a table (Inserting Existing Table Records): CREATE TABLE if not exists database_name.tablename AS SELECT * FROM
existing_tablename;
Example:
CREATE TABLE customer.customer1 AS SELECT * FROM
customer.customer;
Select command to insert records: INSERT INTO database_name.tablename (SELECT columns FROM existing_tablename);
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 20 of 120
Example:
INSERT INTO customer.customer1 (SELECT * FROM customer.customer);
The UPDATE COMMAND Syntax: update database_name.tablename SET FIELD = values WHERE condition;
Example:
UPDATE customer.customer1 SET name = 'Arslan' WHERE id = 97;
The DELETE COMMAND Syntax:
DELETE FROM database_name.tablename WHERE conditions;
Example:
DELETE FROM customer.customer1 WHERE ID = 98;
1. Import CUSTOMER database (CUSTOMER database for lab activity 3) and
Insert your meaningful record into Customer table
2. Select customer id, name from the customer table
3. CREATE CUSTOMER1 table using above syntax & UPDATE the customer1
table to set the state to NY of all customer ranging from ID 1 to 10
4. Delete only those who are living in state NY
5. List the records in the CUSTOMER table order by ID into descending order
6. Display only that customer whose ID is from 25 to 30
7. Display STATE from the table CUSTOMER avoiding the duplicated values.
End of Lab Activity 3
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 21 of 120
Lab Activity 4- SQL Select Statement, Where Clause & Operators
The SQL SELECT Statement
The SELECT statement is used to select data from a database.
The result is stored in a result table, called the result-set.
SQL SELECT Syntax
To select the specific data
SELECT column_name,column_name
FROM database_name.table_name
To select the entire data in a table
SELECT * FROM database_name.table_name
1. Import CUSTOMER database (CUSTOMER database for lab activity 4) and Find
the "CustomerName" and "City" columns from the "Customer" table.
2. Find all the columns from the "Customer" table
The SQL SELECT DISTINCT Statement
In a table, a column may contain many duplicate values; and sometimes you only want to list the
different (distinct) values. The DISTINCT keyword can be used to return only distinct (different)
values.
SQL SELECT DISTINCT Syntax SELECT DISTINCT column_name,column_name
FROM database_name.table_name
3. Find only the distinct values from the "City" columns from the "Customer" table
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 22 of 120
The SQL WHERE Clause
The WHERE clause is used to filter records. The WHERE clause is used to extract only those
records that fulfill a specified criterion.
SQL WHERE Syntax SELECT column_name,column_name
FROM database_name.table_name
WHERE column_name value
4. Find all the customer from the city "New York", in the "Customer" table.
5. Find all the customer in the customer tables whose CustomerID=1.
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 23 of 120
Operators in the WHERE Clause
The following operators can be used in the WHERE clause:
Operator Description
= Equal
<> Not equal. Note: In some versions of SQL this operator may be written as !=
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
IN To specify multiple possible values for a column
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 24 of 120
The SQL LIKE Operator
The LIKE operator is used to search for a specified pattern in a column.
SQL LIKE Syntax SELECT column_name(s)
FROM database_name.table_name
WHERE column_name LIKE pattern
SELECT * FROM table_name
WHERE column_name LIKE pattern
SQL LIKE Operator Examples
The following SQL statement selects all customers with a City starting with the letter "s":
Try it yourself SELECT * FROM customer.customer
WHERE City LIKE 's%';
Tip: The "%" sign is used to define wildcards (missing letters) both before and after the pattern.
The following SQL statement selects all customers with a City ending with the letter "s":
Try it yourself SELECT * FROM customer.customer
WHERE City LIKE '%s'
The following SQL statement selects all customer with a Country containing the pattern "land":
Try it yourself SELECT * FROM customer.customer
WHERE city LIKE '%land%'
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 25 of 120
Using the NOT keyword allows you to select records that do NOT match the pattern.
The following SQL statement selects all customer with Country NOT containing the pattern "land":
Try it yourself SELECT * FROM customer.customer
WHERE city NOT LIKE '%land%'
SQL Wildcard Characters
In SQL, wildcard characters are used with the SQL LIKE operator. SQL wildcards are used to search
for data within a table. With SQL, the wildcards are:
Wildcard Description
% A substitute for zero or more characters
_ A substitute for a single character
[charlist] Sets and ranges of characters to match
[^charlist]
or
[!charlist]
Matches only a character NOT specified within the brackets
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 26 of 120
Using the SQL % Wildcard
The following SQL statement selects all customer with a City starting with "b":
Try it yourself SELECT * FROM customer.customer
WHERE City LIKE 'b%'
The following SQL statement selects all customer with a City containing the pattern "es":
Try it yourself SELECT * FROM customer.customer
WHERE City LIKE '%es%'
Using the SQL _ Wildcard
The following SQL statement selects all customer with a City starting with any character, followed
by "oston":
Try it yourself SELECT * FROM customer.customer
WHERE City LIKE '_oston'
The following SQL statement selects all customer with a City starting with "L", followed by any
character, followed by "s", followed by any character, followed by "Vegas":
Try it yourself SELECT * FROM customer.customer
WHERE City LIKE 'L_s_Vegas'
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 27 of 120
Using the SQL [charlist] Wildcard
The following SQL statement selects all customer with a City starting with "l", "a", or "s":
Try it yourself SELECT * FROM customer.customer
WHERE City LIKE 'LAS%'
The following SQL statement selects all customer with a City starting with "holl":
Try it yourself SELECT * FROM customer.customer
WHERE City LIKE 'holl%'
The following SQL statement selects all customer with a City NOT starting with "h", “o", “l", or "l":
Try it yourself
SELECT * FROM customer.customer
WHERE City NOT LIKE 'holl%'
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 28 of 120
The IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
SQL IN Syntax SELECT column_name(s)
FROM database_name.table_name
WHERE column_name IN (value1,value2,...)
IN Operator Example
The following SQL statement selects all customer with a City of "Paris" or "London":
Try it yourself SELECT * FROM customer.customer
WHERE City IN ('Paris','London')
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 29 of 120
The SQL BETWEEN Operator
The BETWEEN operator selects values within a range. The values can be numbers, text, or dates.
SQL BETWEEN Syntax
SELECT column_name(s)
FROM database_name.table_name
WHERE column_name BETWEEN value1 AND value2
SQL NOT BETWEEN Syntax
SELECT column_name(s)
FROM database_name.table_name
WHERE column_name NOT BETWEEN value1 AND value2
6. Find all addresses with a id BETWEEN 15 and 25.
7. Display the addresses outside the range of 15 and 25, use NOT BETWEEN
BETWEEN Operator with IN Example
The following SQL statement selects all customer with a Id BETWEEN 1 and 20, but customer with a
id of 1, 2, or 3 should not be displayed:
Try it yourself SELECT * FROM customer.customer
WHERE (id BETWEEN 1 AND 10)
AND NOT id IN (1,2,3)
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 30 of 120
BETWEEN Operator with Text Value Example
The following SQL statement selects all customer with a city beginning with any of the letter
BETWEEN 'D' and 'I':
Try it yourself SELECT * FROM customer.customer
WHERE city BETWEEN 'D' AND 'I'
NOT BETWEEN Operator with Text Value Example
The following SQL statement selects all customer with a city beginning with any of the letter NOT
BETWEEN 'D' and 'I':
Try it yourself SELECT * FROM customer.customer
WHERE city NOT BETWEEN 'D' AND 'I'
BETWEEN Operator with Date Value Example
The following SQL statement selects all customer with an zip BETWEEN '2104' and '3320':
Try it yourself SELECT * FROM customer.customer
WHERE zip BETWEEN 2104 AND 3320
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 31 of 120
Notice that the BETWEEN operator can produce different result in different databases!
In some databases, BETWEEN selects fields that are between and excluding the test values.
In other databases, BETWEEN selects fields that are between and including the test values.
And in other databases, BETWEEN selects fields between the test values, including the first test
value and excluding the last test value.
Therefore: Check how your database treats the BETWEEN operator!
8. Practice and Display every given above Syntax in Customer Table
End of Lab Activity 4
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 32 of 120
Lab Activity 5- SQL Statements & Alias Syntax
The SQL AND & OR Operators
The AND & OR operators are used to filter records based on more than one condition.
The AND operator displays a record if both the first condition AND the second condition are
true.
The OR operator displays a record if either the first condition OR the second condition is true.
SQL AND Syntax
SELECT * FROM database_name.table_name
WHERE column_name=value
AND column_name=value
SQL OR Syntax
SELECT * FROM database_name.table_name
WHERE column_name=value
OR column_name=value
1. Find all customers from the country "Germany" AND the city "Berlin", in the "Customers"
table.
2. Find all customers from the city "Berlin" OR "München", in the "Customers" table.
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 33 of 120
Combining AND & OR
You can also combine AND and OR (use parenthesis to form complex expressions).
The following SQL statement selects all customers from the country "Germany" AND the city must
be equal to "Berlin" OR "München", in the "Customers" table:
Try it yourself
SELECT * FROM customer.Customer
WHERE Country='Germany'
AND (City='Berlin' OR City='München')
The SQL ORDER BY Keyword
The ORDER BY keyword is used to sort the result-set by one or more columns.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in a
descending order, you can use the DESC keyword.
SQL ORDER BY Syntax
SELECT column_name, column_name
FROM database_name.table_name
ORDER BY column_name ASC|DESC, column_name ASC|DESC
3. Find all customers from the "Customers" table, sorted by the "Country" column.
4. Find all customers from the "Customers" table, sorted DESCENDING by the "Country"
column.
5. Find all customers from the "Customers" table, sorted by the "Country" and the
"CustomerName" column.
6. Find all customers from the "Customers" table, sorted ascending by the "Country" and
descending by the "CustomerName" column
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 34 of 120
The SQL UPDATE Statement
The UPDATE statement is used to update existing records in a table.
SQL UPDATE Syntax
UPDATE database_name.table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value
Notice the WHERE clause in the SQL UPDATE statement!
The WHERE clause specifies which record or records that should be updated. If you omit the
WHERE clause, all records will be updated!
7. Update the customer "Alfreds Futterkiste" with a new contact person and city.
The SQL DELETE Statement
The DELETE statement is used to delete rows in a table.
SQL DELETE Syntax
DELETE FROM database_name.table_name
WHERE some_column=some_value
Notice the WHERE clause in the SQL DELETE statement!
The WHERE clause specifies which record or records that should be deleted. If you omit the
WHERE clause, all records will be deleted!
8. Delete the customer "Alfreds Futterkiste" from the "Customers" table
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 35 of 120
The SQL LIMIT Clause
The LIMIT clause is used to specify the number of records to return.
The LIMIT clause can be very useful on large tables with thousands of records. Returning a large
number of records can impact on performance.
Note: Not all database systems support the LIMIT clause.
MySQL LIMIT Syntax
SELECT column_name(s)
FROM database_name.table_name
LIMIT number
9. Find the two first records from the "Customers" table.
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 36 of 120
SQL Aliases
SQL aliases are used to give a database table, or a column in a table, a temporary name.
Basically, aliases are created to make column names more readable.
SQL Alias Syntax for Columns
SELECT column_name AS alias_name
FROM database_name.table_name
SQL Alias Syntax for Tables
SELECT column_name(s)
FROM database_name.table_name AS alias_name
Alias Example for Table Columns
The following SQL statement specifies two aliases, one for the CustomerName column and one for
the ContactName column.
Tip: It requires double quotation marks or square brackets if the column name contains spaces:
Try it yourself SELECT CustomerName AS Customer, ContactName AS [Contact Person]
FROM Customers
In the following SQL statement, we combine four columns (Address, City, PostalCode, and Country)
and create an alias named "Address":
Try it yourself
SELECT CustomerName, CONCAT (Address,', ',City,', ',PostalCode,', ',Country) AS Address
FROM Customers
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 37 of 120
Alias Example for Tables The following SQL statement selects all the orders from the customer with CustomerID=4 (Around
the Horn). We use the "Customers" and "Orders" tables, and give them the table aliases of "c" and
"o" respectively (Here we have used aliases to make the SQL shorter):
Try it yourself SELECT o.OrderID, o.OrderDate, c.CustomerName
FROM customer.Customer AS c, Orders AS o
WHERE c.CustomerName="Around the Horn"
AND c.CustomerID=o.CustomerID
The same SQL statement without aliases:
Try it yourself SELECT Orders.OrderID, Orders.OrderDate, Customers.CustomerName
FROM customer.Customer, Orders
WHERE Customer.CustomerName="Around the Horn"
AND Customer.CustomerID=Orders.CustomerID
Aliases can be useful when:
• There are more than one table involved in a query
• Functions are used in the query
• Column names are big or not very readable
• Two or more columns are combined together
End of Lab Activity 5
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 38 of 120
Lab Activity 6- SQL Union Operator, Joining & Views
SQL JOIN An SQL JOIN clause is used to combine rows from two or more tables, based on a common field
between them.
Different SQL JOINs
• CROSS JOIN: Cross Join returns the Cartesian product of rows from tables in the join.
• INNER JOIN: Returns all rows when there is at least one match in BOTH tables
• LEFT JOIN: Return all rows from the left table, and the matched rows from the right
table
• RIGHT JOIN: Return all rows from the right table, and the matched rows from the left
table
• FULL JOIN: Return all rows when there is a match in ONE of the tables
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 39 of 120
SQL CROSS JOIN Keyword
Cross Join returns the Cartesian product of rows from tables in the join.
SQL CROSS JOIN Syntax SELECT column_name(s)
FROM database_name.table1
CROSS JOIN database_name.table2
ORDER BY `CROS`.`table_name that will be in both table’s` ASC -- Example of an Explicit Cross Join
OR
SELECT *
FROM database_name.table1 . database_name.table2
ORDER BY `database_name`.`table_name that will be in both table’s` ASC -- Example of an Implicit
Cross Join
Try it yourself
SELECT * from JOINING.EMPLOYEE
CROS JOIN
JOINING.Department
ORDER BY `CROS`.`DepartmentID` ASC -- Example of an Explicit Cross Join
SELECT * from `JOINING`.`EMPLOYEE` , `JOINING`.`Department` ORDER BY
`EMPLOYEE`.`DepartmentID` ASC; -- Example of an Implicit Cross Join
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 40 of 120
SQL INNER JOIN Keyword The INNER JOIN keyword selects all rows from both tables as long as there is a match between the
columns in both tables.
SQL INNER JOIN Syntax SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name=table2.column_name
OR
SELECT column_name(s)
FROM table1
JOIN table2
ON table1.column_name=table2.column_name
PS! INNER JOIN is the same as JOIN.
SQL INNER JOIN Example
The following SQL statement will return all customers with orders:
Try it yourself SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
INNER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName
Note: The INNER JOIN keyword selects all rows from both tables as long as there is a match between
the columns. If there are rows in the "Customers" table that do not have matches in "Orders", these
customers will NOT be listed.
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 41 of 120
SQL LEFT JOIN Keyword The LEFT JOIN keyword returns all rows from the left table (table1), with the matching rows in the
right table (table2). The result is NULL in the right side when there is no match.
SQL LEFT JOIN Syntax
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name=table2.column_name
OR
SELECT column_name(s)
FROM table1
LEFT OUTER JOIN table2
ON table1.column_name=table2.column_name
PS! In some databases LEFT JOIN is called LEFT OUTER JOIN.
SQL LEFT JOIN Example
The following SQL statement will return all customers, and any orders they might have:
Try it yourself SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName
Note: The LEFT JOIN keyword returns all the rows from the left table (Customers), even if there are
no matches in the right table (Orders).
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 42 of 120
SQL RIGHT JOIN Keyword
The RIGHT JOIN keyword returns all rows from the right table (table2), with the matching rows in
the left table (table1). The result is NULL in the left side when there is no match.
SQL RIGHT JOIN Syntax
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name=table2.column_name
OR
SELECT column_name(s)
FROM table1
RIGHT OUTER JOIN table2
ON table1.column_name=table2.column_name
PS! In some databases, RIGHT JOIN is called RIGHT OUTER JOIN.
SQL RIGHT JOIN Example
The following SQL statement will return all employees, and any orders they have placed:
Try it yourself SELECT Orders.OrderID, Employees.FirstName
FROM Orders
RIGHT JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID
ORDER BY Orders.OrderID
Note: The RIGHT JOIN keyword returns all the rows from the right table (Employees), even if there
are no matches in the left table (Orders).
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 43 of 120
SQL FULL OUTER JOIN Keyword
The FULL OUTER JOIN keyword returns all rows from the left table (table1) and from the right table
(table2). The FULL OUTER JOIN keyword combines the result of both LEFT and RIGHT joins.
Important Note: We don't have FULL JOINS on MySQL, but we can sure use this query to get our
desired result as per full join definition.
SQL FULL OUTER JOIN Syntax
SELECT * FROM t1 -- Syntax with Two Tables “t1 and t2”
LEFT JOIN t2 ON t1.column_name = t2.column_name
UNION ALL
SELECT * FROM t1
RIGHT JOIN t2 ON t1.column_name = t2.column_name
SQL FULL OUTER JOIN Example
The following SQL statement selects all customers, and all orders: SELECT * from `JOINING`.`EMPLOYEE`
LEFT JOIN `JOINING`.`DEPARTMENT`
ON `EMPLOYEE`.`DEPARTMENTID` = `DEPARTMENT`.`DEPARTMENTID`
UNION ALL
SELECT * FROM `JOINING`.`EMPLOYEE`
RIGHT JOIN
ON `EMPLOYEE`.`DEPARTMENTID` = `DEPARTMENT`.`DEPARTMENTID`
ORDER BY `DEPARTMENT`.`DEPARTMENTID` ASC;
Note: The FULL OUTER JOIN keyword returns all the rows from the left table (Customers), and all
the rows from the right table (Orders). If there are rows in "Customers" that do not have matches in
"Orders", or if there are rows in "Orders" that do not have matches in "Customers", those rows will
be listed as well.
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 44 of 120
Lab Assignment: -
1. Create three tables named EMPLOYEE_DETAIL & SALARY & PHONE_NUMBER in a
database named EMPLOYEE via code as shown in figure:
2. Implement all Joining Queries on the above created database named EMPLOYEE_DETAIL
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 45 of 120
The SQL UNION Operator
The UNION operator is used to combine the result-set of two or more SELECT statements.
Notice that each SELECT statement within the UNION must have the same number of columns. The
columns must also have similar data types. Also, the columns in each SELECT statement must be in
the same order.
SQL UNION Syntax
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2
Note: The UNION operator selects only distinct values by default. To allow duplicate values, use the
ALL keyword with UNION.
SQL UNION ALL Syntax
SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2
PS: The column names in the result-set of a UNION are usually equal to the column names in the
first SELECT statement in the UNION.
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 46 of 120
SQL UNION Example
The following SQL statement selects all the different cities (only distinct values) from the
"Customers" and the "Suppliers" tables:
Try it yourself SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City
Note: UNION cannot be used to list ALL cities from the two tables. If several customers and
suppliers share the same city, each city will only be listed once. UNION selects only distinct values.
Use UNION ALL to also select duplicate values!
SQL UNION ALL Example
The following SQL statement uses UNION ALL to select all (duplicate values also) cities from the
"Customers" and "Suppliers" tables:
Try it yourself SELECT City FROM Customers
UNION ALL
SELECT City FROM Suppliers
ORDER BY City
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 47 of 120
SQL UNION ALL With WHERE
The following SQL statement uses UNION ALL to select all (duplicate values also) German cities
from the "Customers" and "Suppliers" tables:
Try it yourself SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION ALL
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 48 of 120
The SQL SELECT INTO Statement
The SELECT INTO statement selects data from one table and inserts it into a new table.
SQL SELECT INTO Syntax
We can copy all columns into the new table: SELECT *
INTO newtable [IN externaldb]
FROM table1
Or we can copy only the columns we want into the new table: SELECT column_name(s)
INTO newtable [IN externaldb]
FROM table1
The new table will be created with the column-names and types as defined in the SELECT
statement. You can apply new names using the AS clause.
SQL SELECT INTO Examples
• Create a backup copy of Customers: SELECT *
INTO CustomersBackup2013
FROM Customers
• Use the IN clause to copy the table into another database: SELECT *
INTO CustomersBackup2013 IN 'Backup.mdb'
FROM Customers
• Copy only a few columns into the new table: SELECT CustomerName, ContactName
INTO CustomersBackup2013
FROM Customers
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 49 of 120
• Copy only the German customers into the new table: SELECT *
INTO CustomersBackup2013
FROM Customers
WHERE Country='Germany'
• Copy data from more than one table into the new table: SELECT Customers.CustomerName, Orders.OrderID
INTO CustomersOrderBackup2013
FROM Customers
LEFT JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
Tip: The SELECT INTO statement can also be used to create a new, empty table using the schema of
another. Just add a WHERE clause that causes the query to return no data: SELECT *
INTO newtable
FROM table1
WHERE 1=0
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 50 of 120
The SQL INSERT INTO SELECT Statement
The INSERT INTO SELECT statement selects data from one table and inserts it into an existing table.
Any existing rows in the target table are unaffected.
SQL INSERT INTO SELECT Syntax
We can copy all columns from one table to another, existing table: INSERT INTO table2
SELECT * FROM table1
Or we can copy only the columns we want to into another, existing table: INSERT INTO table2
(column_name(s))
SELECT column_name(s)
FROM table1
SQL INSERT INTO SELECT Examples
Copy only a few columns from "Suppliers" into "Customers":
Try it yourself INSERT INTO Customers (CustomerName, Country)
SELECT SupplierName, Country FROM Suppliers
Copy only the German suppliers into "Customers":
Try it yourself INSERT INTO Customers (CustomerName, Country)
SELECT SupplierName, Country FROM Suppliers
WHERE Country='Germany'
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 51 of 120
SQL CREATE VIEW Statement
In SQL, a view is a virtual table based on the result-set of an SQL statement.
A view contains rows and columns, just like a real table. The fields in a view are fields from one or
more real tables in the database.
You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the
data were coming from one single table.
SQL CREATE VIEW Syntax
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
Note: A view always shows up-to-date data! The database engine recreates the data, using the
view's SQL statement, every time a user queries a view
SQL CREATE VIEW Examples
If you have the Northwind database, you can see that it has several views installed by default.
• The view "Current Product List" lists all active products (products that are not discontinued)
from the "Products" table. The view is created with the following SQL: CREATE VIEW [Current Product List] AS
SELECT ProductID,ProductName
FROM Products
WHERE Discontinued=No
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 52 of 120
We can query the view above as follows: SELECT * FROM [Current Product List]
• Another view in the Northwind sample database selects every product in the "Products"
table with a unit price higher than the average unit price:
CREATE VIEW [Products Above Average Price] AS
SELECT ProductName,UnitPrice
FROM Products
WHERE UnitPrice>(SELECT AVG(UnitPrice) FROM Products)
We can query the view above as follows: SELECT * FROM [Products Above Average Price]
• Another view in the Northwind database calculates the total sale for each category in 1997.
Note that this view selects its data from another view called "Product Sales for 1997":
CREATE VIEW [Category Sales For 1997] AS
SELECT DISTINCT CategoryName,Sum(ProductSales) AS CategorySales
FROM [Product Sales for 1997]
GROUP BY CategoryName
We can query the view above as follows: SELECT * FROM [Category Sales For 1997]
We can also add a condition to the query. Now we want to see the total sale only for the category
"Beverages":
SELECT * FROM [Category Sales For 1997]
WHERE CategoryName='Beverages'
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 53 of 120
SQL Updating a View
You can update a view by using the following syntax:
SQL CREATE OR REPLACE VIEW Syntax
CREATE OR REPLACE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
Now we want to add the "Category" column to the "Current Product List" view. We will update the
view with the following SQL: CREATE OR REPLACE VIEW [Current Product List] AS
SELECT ProductID,ProductName,Category
FROM Products
WHERE Discontinued=No
SQL Dropping a View
You can delete a view with the DROP VIEW command.
SQL DROP VIEW Syntax
DROP VIEW view_name
End of Lab Activity 6
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 54 of 120
Lab Activity 7- Normalization up to Third Normal Form (3-NF)
Database Normalization up to 3-NF:
Lab Assignment: -
1. Create and Normalize the following given table’s up to 3-NF via Code:
2. Name of a database must be ADVISOR_SCHEDULE
End of Lab Activity 7
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 55 of 120
Lab Activity 8- SQL Aggregate Functions
SQL Aggregate Functions
SQL aggregate functions return a single value, calculated from values in a column.
Useful aggregate functions:
• AVG() - Returns the average value
• COUNT() - Returns the number of rows
• FIRST() - Returns the first value
• LAST() - Returns the last value
• MAX() - Returns the largest value
• MIN() - Returns the smallest value
• SUM() - Returns the sum
•
SQL Scalar functions
SQL scalar functions return a single value, based on the input value.
Useful scalar functions:
• UCASE() - Converts a field to upper case
• LCASE() - Converts a field to lower case
• MID() - Extract characters from a text field
• LEN() - Returns the length of a text field
• ROUND() - Rounds a numeric field to the number of decimals specified
• NOW() - Returns the current system date and time
• FORMAT() - Formats how a field is to be displayed
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 56 of 120
The AVG() Function
The AVG() function returns the average value of a numeric column.
SQL AVG() Syntax
SELECT AVG(column_name) FROM table_name
SQL AVG() Example
The following SQL statement gets the average value of the "Price" column from the "Products"
table:
Try it yourself SELECT AVG(Price) AS PriceAverage FROM Products
The following SQL statement selects the "ProductName" and "Price" records that have an above
average price:
Try it yourself SELECT ProductName, Price FROM Products
WHERE Price>(SELECT AVG(Price) FROM Products)
SQL COUNT() Function
The COUNT() function returns the number of rows that matches a specified criteria.
SQL COUNT(column_name) Syntax
The COUNT(column_name) function returns the number of values (NULL values will not be counted)
of the specified column: SELECT COUNT(column_name) FROM table_name
SQL COUNT(*) Syntax
The COUNT(*) function returns the number of records in a table: SELECT COUNT(*) FROM table_name
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 57 of 120
SQL COUNT(DISTINCT column_name) Syntax
The COUNT(DISTINCT column_name) function returns the number of distinct values of the specified
column: SELECT COUNT(DISTINCT column_name) FROM table_name
Note: COUNT(DISTINCT) works with ORACLE and Microsoft SQL Server, but not with Microsoft
Access.
SQL COUNT(column_name) Example
The following SQL statement counts the number of orders from "CustomerID"=7 from the "Orders"
table:
Try it yourself SELECT COUNT(CustomerID) AS OrdersFromCustomerID7 FROM Orders
WHERE CustomerID=7
SQL COUNT(*) Example
The following SQL statement counts the total number of orders in the "Orders" table:
Try it yourself SELECT COUNT(*) AS NumberOfOrders FROM Orders
SQL COUNT(DISTINCT column_name) Example
The following SQL statement counts the number of unique customers in the "Orders" table:
Try it yourself SELECT COUNT(DISTINCT CustomerID) AS NumberOfCustomers FROM Orders
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 58 of 120
The MAX() Function
The MAX() function returns the largest value of the selected column.
SQL MAX() Syntax
SELECT MAX(column_name) FROM table_name
SQL MAX() Example
The following SQL statement gets the largest value of the "Price" column from the "Products" table:
Try it yourself SELECT MAX(Price) AS HighestPrice FROM Products
The MIN() Function
The MIN() function returns the smallest value of the selected column.
SQL MIN() Syntax
SELECT MIN(column_name) FROM table_name
SQL MIN() Example
The following SQL statement gets the smallest value of the "Price" column from the "Products"
table:
Try it yourself SELECT MIN(Price) AS SmallestOrderPrice FROM Products
The SUM() Function
The SUM() function returns the total sum of a numeric column.
SQL SUM() Syntax
SELECT SUM(column_name) FROM table_name
SQL SUM() Example
The following SQL statement finds the sum of all the "Quantity" fields for the "OrderDetails" table:
Try it yourself SELECT SUM(Quantity) AS TotalItemsOrdered FROM OrderDetails
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 59 of 120
The GROUP BY Statement
The GROUP BY statement is used in conjunction with the aggregate functions to group the result-
set by one or more columns.
SQL GROUP BY Syntax
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
SQL GROUP BY Example Now we want to find the number of orders sent by each shipper.
The following SQL statement counts as orders grouped by shippers:
Try it yourself SELECT Shippers.ShipperName,COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders
LEFT JOIN Shippers
ON Orders.ShipperID=Shippers.ShipperID
GROUP BY ShipperName
GROUP BY More Than One Column
We can also use the GROUP BY statement on more than one column, like this:
Try it yourself SELECT Shippers.ShipperName, Employees.LastName,
COUNT(Orders.OrderID) AS NumberOfOrders
FROM ((Orders
INNER JOIN Shippers
ON Orders.ShipperID=Shippers.ShipperID)
INNER JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID)
GROUP BY ShipperName,LastName
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 60 of 120
The HAVING Clause
The HAVING clause was added to SQL because the WHERE keyword could not be used with
aggregate functions.
SQL HAVING Syntax
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value
SQL HAVING Example
Now we want to find if any of the employees has registered more than 10 orders.
We use the following SQL statement:
Try it yourself SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders FROM (Orders
INNER JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID)
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 10
Now we want to find if the employees "Davolio" or "Fuller" have registered more than 25 orders.
We add an ordinary WHERE clause to the SQL statement:
Try it yourself SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders
INNER JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID
WHERE LastName='Davolio' OR LastName='Fuller'
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 25
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 61 of 120
The UPPER() Function
The UPPER() function converts the value of a field to uppercase.
SQL UPPER Syntax
SELECT UPPER(column_name) FROM table_name
SQL UPPER() Example
The following SQL statement selects the "CustomerName" and "City" columns from the
"Customers" table, and converts the "CustomerName" column to uppercase:
Try it yourself SELECT UPPER(CustomerName) AS Customer, City
FROM Customers
The LOWER() Function
The LOWER() function converts the value of a field to lowercase.
SQL LOWER() Syntax
SELECT LOWER(column_name) FROM table_name
SQL LOWER() Example
The following SQL statement selects the "CustomerName" and "City" columns from the
"Customers" table, and converts the "CustomerName" column to lowercase:
Try it yourself SELECT LOWER(CustomerName) AS Customer, City
FROM Customers
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 62 of 120
The LEN() Function
The LEN() function returns the length of the value in a text field.
SQL LEN() Syntax
SELECT LEN(column_name) FROM table_name
SQL LEN() Example
The following SQL statement selects the "CustomerName" and the length of the values in the
"Address" column from the "Customers" table:
Try it yourself SELECT CustomerName,LEN(Address) as LengthOfAddress
FROM Customers
The ROUND() Function
The ROUND() function is used to round a numeric field to the number of decimals specified.
Note: Many database systems do rounding differently than you might expect. When rounding a
number with a fractional part to an integer, our school teachers told us to round .1 through .4
DOWN to the next lower integer, and .5 through .9 UP to the next higher integer. But if all the digits
1 through 9 are equally likely, this introduces a slight bias towards infinity, since we always round .5
up. Many database systems have adopted the IEEE 754 standard for arithmetic operations,
according to which the default rounding behavior is "round half to even." In this scheme, .5 is
rounded to the nearest even integer. So, both 11.5 and 12.5 would be rounded to 12.
SQL ROUND() Syntax
SELECT ROUND(column_name,decimals) FROM table_name
Parameter Description
column_name Required. The field to round.
decimals Required. Specifies the number of decimals to be returned.
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 63 of 120
SQL ROUND() Example
The following SQL statement selects the product name and rounds the price in the "Products" table:
Try it yourself SELECT ProductName, ROUND(Price,0) AS RoundedPrice
FROM Products
The NOW() Function
The NOW() function returns the current system date and time.
SQL NOW() Syntax
SELECT NOW() FROM table_name
SQL NOW() Example
The following SQL statement selects the product name, and price for today from the "Products"
table:
Try it yourself SELECT ProductName, Price, Now() AS PerDate
FROM Products
End of Lab Activity 8
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 64 of 120
Lab Activities Detailed Review- MySQL Coding Using Console
XAMPP: -
XAMPP stands for Cross-Platform (X), Apache (A), MySQL (M), PHP
(P) and Perl (P). It is a simple, light-weighted Apache server that makes it
extremely easy for developers to create a local http server with just few clicks.
An integrated development environment (IDE) is a software application that
provides comprehensive facilities to computer programmers for software
development. An IDE normally consists of a source code editor, build automation
tools and a debugger/Tester of Program/Execution of program.
After Installation of XAMPP Server
Starting Services of Apache and MySQL (the sign changes from red to green): -
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 65 of 120
We can access the local server via graphical user interface (GUI) by click on
the Admin button of MySQL.
phpMyAdmin: -
It is a free and open source tool/simulator written in PHP intended
to handle the administration of MySQL or MariaDB (DBMS Engines) with the use
of a web browser. It can perform various tasks such as creating, modifying or
deleting databases, tables, fields or rows; executing SQL statements; or managing
users and permissions.
Apache: -
It is the most widely used web server software. Developed and
maintained by Apache Software Foundation, Apache is an open source software
available for free. It runs on 67% of all webservers in the world. It is fast, reliable,
and secure.
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 66 of 120
We can access the local server via Domain Name directly in the browser that is by default (after
starting services of Apache and MySQL): -
localhost/phpmyadmin
Also, we can access the local server via loopback IP Address in web browser
that is by default (after starting services of Apache and MySQL): -
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 67 of 120
127.0.0.1/phpmyadmin
127.0.0.1: -
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 68 of 120
This is a loopback IP address (Special IP address) that is used to
access the local server.
Drop Command: -
This command is disable by default. So, to enable it follow the
following process:
1. Go To: -
C:\xampp\phpmyadmin\libraries
2. Open the file called "config.default.php"
3. Go to line 653 and change $cfg['AllowUserDropDatabase'] = false; to true
4. Restart the server to see the changes
Securing Server ROOT USER by Implementing Password using the following
steps: -
Go into Edit Privileges
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 69 of 120
Then, Go into Change Password: -
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 70 of 120
Than: -
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 71 of 120
Go into installed directory of XAMPP:
C:\xampp\phpMyAdmin
Open: config.inc
And Change: -
config to cookie
Then, Change and Type that password that already assigned in Server: -
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 72 of 120
Data Definition Language Commands (DDL Commands): -
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 73 of 120
1. CREATE
2. ALTER
3. DROP
4. TRUNCATE
Data Manipulation Language Commands (DML Commands): -
1. INSERT
2. SELECT
3. UPDATE
4. DELETE
SQL Keywords: -
1. MODIFY
2. SHOW
3. USE
SQL (Sequel) is Case Insensitive
SQL (Sequel) is Open Source Language that means FREE FOR ALL
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 74 of 120
Double Hyphen -- is used for single line comment
/*
these backslash steric and steric backslash is used for multi-line comment
*/
# is NOT a standard SQL Comment
; -- semi colon is used to terminate a query)
/* When we write a single SQL Query than we may not terminate it using
Semi Colon “;” */
Conditions: these given below conditions are used to make any query in
MySQL error free and efficient
IF EXISTS and IF NOT EXISTS
Identifier: - `
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 75 of 120
In MySQL, an Identifier is used to separate database and table name.
Identifier is a sequence of characters used to identify or refer to a program or an
element, such as a variable or a set of data, within it.
`Database_Name`
/* Advantage of Using Identifier in MySQL Coding: Identifier is a sequence of
characters used to identify or refer to a program or an element, such as a variable
or a set of data, within it for Example If we want to create a Database with the
name “CREATE”. We cannot create it without the use of an Identifier because
CREATE is a Command in MySQL. */
-- Example: - "The following Command cannot be executed without
Identifier"
/* drop database if exists `create`; CREATE DATABASE IF NOT EXISTS
CREATE; */
/* But; Example: - "The following Command can be executed with Identifier" */
drop database if exists `create`; CREATE DATABASE IF NOT EXISTS
`CREATE`;
Qualifier Character: - .
In MySQL the Qualifier Character is a separate token and need not be connecting
with the associated identifiers. For example,
`table_name`.`column_name` and `table_name` . `column_name` are
equivalen
-- Without Selecting any database, we can also run some Queries: -
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 76 of 120
select 25 + 25; -- We can perform calculations in Console/Command line Interface
(CLI)
select 50 + 25; -- We can perform calculations in Console/CLI
select 26 mod 26; -- We can perform calculations in Console/CLI
select 27 mod 26; -- We can perform calculations in Console/CLI
select "This is Database Systems lab "; -- We can write and show output in
Console/CLI
select "HELLO CLASS!!"; -- We can write and show output in Console/CLI
select "this subject is just amazing"; -- We can write and show output in
Console/CLI
SELECT SYSDATE(); -- SYSDATE() Function returns current date & time of
the system
Show Databases; -- To show all databases in a Server
-- Use database_Name -- Syntax to use a specific database
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 77 of 120
drop database if exists `LAB`; -- Use IF EXISTS to prevent an error from
occurring for databases that do not exist
create database `LAB`; -- Creating a database VIA Single Query (Double
Hyphen for Comments)
use `lab`;
create table `lab`.`TEST`
(
`testNo` int (3) not null auto_increment,
`testId` int(3),
`testName` varchar (20),
`CREATE` int (20), -- If we want to Create a CREATE TABLE we must use
identifier
primary key (`testNo`, `testId`, `testName`) /* To create multiple primary
keys (Composite Primary Key in a table; Use the given syntax) */
);
/*
The DESCRIBE and EXPLAIN statements are synonyms, used either to obtain
information about table structure via code.
*/
DESCRIBE `lab`.`test`; -- to show the structure of a table
drop database `LAB`; -- To delete a Database
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 78 of 120
create database IF NOT EXISTS `LAB`; -- Creating a database VIA Single but
efficient Query
drop database if exists `LAB`; -- To delete a Database Query but Efficient than
previous query
drop database if exists `lab1`; -- To delete a Database Query
create database if not exists `LAB1`; /* Creating, Selecting and Inserting
Values in Table VIA Single Query (Double Hyphen for Comments) */
use `lab1`;
create table `lab1`.`TEST` /* Using Qualifier Character to quickly
create a table in a selected database via single query */
(
`testId` int(2) not null PRIMARY KEY,
`test1Id` int(2),
`testName` varchar (20)
);
create table `lab1`.`TEST1`
(
`test1Id` int(2),
`testId` int(2),
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 79 of 120
`test1Name` varchar (20),
constraint `fk_1` FOREIGN KEY (`testId`) references `lab1`.`test` (`testId`)
ON DELETE RESTRICT ON UPDATE CASCADE;
);
ALTER TABLE `lab1`.`test` ADD testMarks float not null; -- To add a column
in a table, use the following syntax via Query
-- DESCRIBE `lab1`.`test`;
ALTER TABLE `lab1`.`test1` ADD PRIMARY KEY(`test1Id`); -- To alter and
add a primary key in 2nd table, use the following syntax via Query
-- EXPLAIN `lab1`.`test1`;
ALTER TABLE `lab1`.`test` ADD CONSTRAINT `fk_test` FOREIGN KEY
(`test1Id`) REFERENCES `lab1`.`test1`(`test1Id`) ON DELETE RESTRICT
ON UPDATE RESTRICT; -- By Altering and adding a foreign key constraint in
first table, use the following syntax via Query
-- EXPLAIN `lab1`.`test`;
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 80 of 120
ALTER TABLE `lab1`.`test1` DROP FOREIGN KEY `fk_1`;
ALTER TABLE `lab1`.`test1` ADD CONSTRAINT `fk_test1` FOREIGN
KEY (`testId`) REFERENCES `lab1`.`test`(`testId`) ON DELETE
RESTRICT ON UPDATE RESTRICT;
-- To change the name of the foreign key constraint in a table, firstly drop the
Constraint of Foreign key than again write the whole query as given
/*
Let's look at the ON UPDATE clause:
ON UPDATE RESTRICT: the default: if you try to update a company_id in table
COMPANY the engine will reject the operation if one USER at least links on this
company.
ON UPDATE NO ACTION: same as RESTRICT.
ON UPDATE CASCADE: the best one usually: if you update a company_id in a
row of table COMPANY the engine will update it accordingly on all USER rows
referencing this COMPANY (but no triggers activated on USER table, warning).
The engine will track the changes for you, it's good.
ON UPDATE SET NULL: if you update a company_id in a row of table
COMPANY the engine will set related USERs company_id to NULL (should be
available in USER company_id field). I cannot see any interesting thing to do with
that on an update, but I may be wrong.
And now on the ON DELETE side:
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 81 of 120
ON DELETE RESTRICT: the default: if you try to delete a company_id Id in
table COMPANY the engine will reject the operation if one USER at least links on
this company, can save your life.
ON DELETE NO ACTION: same as RESTRICT
ON DELETE CASCADE: dangerous: if you delete a company row in table
COMPANY the engine will delete as well the related USERs. This is dangerous
but can be used to make automatic cleanups on secondary tables (so it can be
something you want, but quite certainly not for a COMPANY<->USER example)
ON DELETE SET NULL: * handful*: if you delete a COMPANY row the
related USERs will automatically have the relationship to NULL. If Null is your
value for users with no company this can be a good behavior, for example maybe
you need to keep the users in your application, as authors of some content, but
removing the company is not a problem for you.
usually my default is:
ON DELETE RESTRICT ON UPDATE CASCADE
with some ON DELETE CASCADE for track tables (logs--not all logs--,
things like that) and ON DELETE SET NULL when the master table is a 'simple
attribute' for the table containing the foreign key, like a JOB table for the USER
table.
*/
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 82 of 120
ALTER TABLE `lab1`.`test1` DROP FOREIGN KEY `fk_test1`;
ALTER TABLE `lab1`.`test1` ADD CONSTRAINT `fk_test1` FOREIGN
KEY (`testId`) REFERENCES `lab1`.`test` (`testId`) ON DELETE
CASCADE ON UPDATE CASCADE;
/*
ALTER TABLE `lab1`.`test1` DROP FOREIGN KEY `fk_test1`;
ALTER TABLE `lab1`.`test1` ADD CONSTRAINT `fk_test1` FOREIGN
KEY (`testId`) REFERENCES `lab1`.`test`(`testId`) ON DELETE
RESTRICT ON UPDATE CASCADE;
*/
ALTER TABLE `LAB1`.`TEST` CHANGE `testName` `test_Name`
VARCHAR (20); -- To change the data type and Name of a column in a table, use
the following syntax `backtick`)
ALTER TABLE `LAB1`.`TEST` CHANGE `test_Name` `testName`
varchar(20); -- To change the data type and Name of a column in a table, use
the following syntax
/* FOEREIGN Keys can have Null Values */
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 83 of 120
INSERT INTO `LAB1`.`TEST` (testId, testName, testMarks) VALUES
(1,'Quiz 01',7.5); -- The INSERT INTO statement is used to insert new records in
specific columns in a table
INSERT INTO `LAB1`.`TEST` (testId, testName) VALUES (2, 'Quiz 02'); --
It is also possible to only insert data in specific columns.
INSERT INTO `LAB1`.`TEST1` (test1Id, test1Name) VALUES (1,'Quiz 01'),
(2,'Quiz 02'); -- Inserting Multiple records into a 2nd table VIA Single Query
-- select * from `lab1`.`test1`
UPDATE `lab1`.`test` SET `test1Id` = '1' WHERE `test`.`testId` = 1;
-- Updating and relating Primary and Foreign Key’s in a table via query
UPDATE `lab1`.`test1` SET `testId` = '1' WHERE `test1`.`test1Id` = 1;
-- Updating and relating Primary and Foreign Key’s in second table via query
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 84 of 120
SELECT * FROM `lab1`.`test` ORDER BY `test`.`testId` ASC; -- To show the
output of all record in Ascending Order
SELECT * FROM `lab1`.`test` ORDER BY `test`.`testId` DESC; -- To show
the output of all record in Descending Order
SELECT testId FROM `lab1`.`test` ORDER BY `test`.`testId` ASC; -- To
show the output of one column in Ascending Order
SELECT testId FROM `lab1`.`test` ORDER BY `test`.`testId` DESC; -- To
show the output of one column in Descending Order
SELECT * FROM `lab1`.`test` WHERE `test`.`testId` < 3
AND
`test`.`testName` = 'Quiz 01'; /*To show the output using
WHERE clause and operator’s */
SELECT * FROM `lab1`.`test` WHERE `test`.`testId` <= 3
AND
`test`.`testName` > 'Quiz 01'; /*To show the output using WHERE clause
and operator’s */
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 85 of 120
select * from `lab1`.`test` order by `test`.`testId` limit 2; -- To limit the output
of a record to output of: 1 and 2
select * from `lab1`.`test` order by `test`.`testId` limit 1 offset 1; -- To limit
only output of 2 using offset
select `testId` AS `Id` FROM `lab1`.`test` ; -- To use the ALIAS to change the
table name temporary
select `testId` AS `Id` FROM `lab1`.`test` order by `Id` desc ; -- To use the
ALIAS to change the table name temporary and show output in Descending order
select COUNT(*) from `lab1`.`test`; -- To use the COUNT(*) FUNCTION that
will return the number of records in a table
select COUNT(testMarks) from `lab1`.`test`; -- To use the
COUNT(column_name) FUNCTION that will return the number of records in a
table from a specific selected column
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 86 of 120
/*
TRUNCATE TABLE `LAB1`.`TEST`; What if we only want to delete the data
inside the table, and not the table itself. BUT it will generate an error because table
are in primary to foreign relationship
*/
ALTER TABLE `lab1`.`test` DROP FOREIGN KEY `fk_test`;
-- To drop a foreign key in second table, use the following syntax via Query
ALTER TABLE `lab1`.`test1` DROP FOREIGN KEY `fk_test1`;
-- To drop a foreign key in second table, use the following syntax via Query
TRUNCATE TABLE `LAB1`.`TEST`; -- What if we only want to delete the data
inside the table, and not the table itself
TRUNCATE TABLE `LAB1`.`TEST1`; -- What if we only want to delete the
data inside the table, and not the table itself
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 87 of 120
ALTER TABLE `LAB1`.`TEST` /* To delete a column in a table having primary
key assigned but no relationship via foreign key, use the following syntax (notice
that some database systems don't allow deleting a column) {this is for Multi
Line Comments} */
DROP COLUMN `testId`;
ALTER TABLE `LAB1`.`TEST` /* To delete a column in a table having primary
key assigned but no relationship via foreign key, use the following syntax (notice
that some database systems don't allow deleting a column) {this is for Multi
Line Comments} */
DROP COLUMN `test1Id`;
ALTER TABLE `LAB1`.`TEST1` /* To delete multiple column in a table
having primary key assigned but no relationship via foreign key, use the following
Efficient syntax */
DROP COLUMN `testId`,
DROP COLUMN `test1Id`;
ALTER TABLE `Lab1`.`TEST` MODIFY COLUMN `testName`
varchar(30); -- To change Only the data type of a column in a table, use the
following syntax
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 88 of 120
INSERT INTO `LAB1`.`TEST` VALUES ('Quiz 01',9.5);
INSERT INTO `LAB1`.`TEST` VALUES ('Quiz 02',10);
SELECT * FROM `LAB1`.`TEST` WHERE `testMarks` = '9.5'; -- It is also
possible to select a specific data from a specific colum_name or label_name.
DELETE FROM `LAB1`.`TEST`
WHERE `testMarks`=10; -- It is also possible to delete a data from a specific
ROW.
DROP table if exists `lab1`.`test1`; -- To delete a Table in a Database
CREATE table IF NOT EXISTS `lab1`.`TEST` /* Using Qualifier
Character to quickly select a database and a table via Code using Console.*/
(
testId int(200)
);
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 89 of 120
DROP table if exists `lab1`.`test1` , `lab1`.`test`; -- To delete multiple tables in a
Database via One Query
DROP database if exists lab1; -- To delete a Database
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 90 of 120
/*
Data Types in MySQL: -
Date and Time Types:
The MySQL date and time datatypes are:
• DATE - A date in YYYY-MM-DD format, between 1000-01-01 and 9999-
12-31. For example, December 30th, 1973 would be stored as 1973-12-30.
• DATETIME - A date and time combination in YYYY-MM-DD
HH:MM:SS format, between 1000-01-01 00:00:00 and 9999-12-31
23:59:59. For example, 3:30 in the afternoon on December 30th, 1973 would
be stored as 1973-12-30 15:30:00.
• TIMESTAMP - A timestamp between midnight, January 1, 1970 and
sometime in 2037. This looks like the previous DATETIME format, only
without the hyphens between numbers; 3:30 in the afternoon on December
30th, 1973 would be stored as 19731230153000 ( YYYYMMDDHHMMSS
).
• TIME - Stores the time in HH:MM:SS format.
• YEAR(M) - Stores a year in 2-digit or 4-digit format. If the length is
specified as 2 (for example YEAR(2)), YEAR can be 1970 to 2069 (70 to
69). If the length is specified as 4, YEAR can be 1901 to 2155. The default
length is 4.
Numeric Data Types:
MySQL uses all the standard ANSI SQL numeric data types, so if you're coming to
MySQL from a different database system, these definitions will look familiar to
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 91 of 120
you. The following list shows the common numeric data types and their
descriptions:
• INT - A normal-sized integer that can be signed or unsigned. If signed, the
allowable range is from -2147483648 to 2147483647. If unsigned, the
allowable range is from 0 to 4294967295. You can specify a width of up to
11 digits.
• TINYINT - A very small integer that can be signed or unsigned. If signed,
the allowable range is from -128 to 127. If unsigned, the allowable range is
from 0 to 255. You can specify a width of up to 4 digits.
• SMALLINT - A small integer that can be signed or unsigned. If signed, the
allowable range is from -32768 to 32767. If unsigned, the allowable range is
from 0 to 65535. You can specify a width of up to 5 digits.
• MEDIUMINT - A medium-sized integer that can be signed or unsigned. If
signed, the allowable range is from -8388608 to 8388607. If unsigned, the
allowable range is from 0 to 16777215. You can specify a width of up to 9
digits.
• BIGINT - A large integer that can be signed or unsigned. If signed, the
allowable range is from -9223372036854775808 to 9223372036854775807.
If unsigned, the allowable range is from 0 to 18446744073709551615. You
can specify a width of up to 20 digits.
• FLOAT(M,D) - A floating-point number that cannot be unsigned. You can
define the display length (M) and the number of decimals (D). This is not
required and will default to 10,2, where 2 is the number of decimals and 10
is the total number of digits (including decimals). Decimal precision can go
to 24 places for a FLOAT.
• DOUBLE(M,D) - A double precision floating-point number that cannot be
unsigned. You can define the display length (M) and the number of decimals
(D). This is not required and will default to 16,4, where 4 is the number of
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 92 of 120
decimals. Decimal precision can go to 53 places for a DOUBLE. REAL is a
synonym for DOUBLE.
• DECIMAL(M,D) - An unpacked floating-point number that cannot be
unsigned. In unpacked decimals, each decimal corresponds to one byte.
Defining the display length (M) and the number of decimals (D) is required.
NUMERIC is a synonym for DECIMAL.
String Types:
Although numeric and date types are fun, most data you'll store will be in string
format. This list describes the common string datatypes in MySQL.
• CHAR(M) - A fixed-length string between 1 and 255 characters in length
(for example CHAR(5)), right-padded with spaces to the specified length
when stored. Defining a length is not required, but the default is 1.
• VARCHAR(M) - A variable-length string between 1 and 255 characters in
length; for example VARCHAR(25). You must define a length when
creating a VARCHAR field.
• BLOB or TEXT - A field with a maximum length of 65535 characters.
BLOBs are "Binary Large Objects" and are used to store large amounts of
binary data, such as images or other types of files. Fields defined as TEXT
also hold large amounts of data; the difference between the two is that sorts
and comparisons on stored data are case sensitive on BLOBs and are not
case sensitive in TEXT fields. You do not specify a length with BLOB or
TEXT.
• TINYBLOB or TINYTEXT - A BLOB or TEXT column with a maximum
length of 255 characters. You do not specify a length with TINYBLOB or
TINYTEXT.
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 93 of 120
• MEDIUMBLOB or MEDIUMTEXT - A BLOB or TEXT column with a
maximum length of 16777215 characters. You do not specify a length with
MEDIUMBLOB or MEDIUMTEXT.
• LONGBLOB or LONGTEXT - A BLOB or TEXT column with a
maximum length of 4294967295 characters. You do not specify a length
with LONGBLOB or LONGTEXT.
• ENUM - An enumeration, which is a fancy term for list. When defining an
ENUM, you are creating a list of items from which the value must be
selected (or it can be NULL). For example, if you wanted your field to
contain "A" or "B" or "C", you would define your ENUM as ENUM ('A',
'B', 'C') and only those values (or NULL) could ever populate that field.
*/
/*
We have three fields as given below, What data type’s we will choose and why?
studentId –
INT
studentFirstName –
VARCHAR
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 94 of 120
studentAddress –
VARCHAR
If you look at the list of field types, there is an INT but no Number; and there are
different Text Types to choose from. We can use INT (meaning integer) for the
numbers, but again, there are a few Integer Types to choose from. And that's
leaving out things like float and double. Here's given the difference between them:
Integer Values
TINYINT
Signed: -128 to 127. Unsigned: 0 to 255
SMALLINT
Signed: -32768 to 32767. Unsigned: 0 to 65535
MEDIUMINT
Signed: -8388608 to 8388607. Unsigned: 0 to 16777215
INT
Signed: -2147483648 to 2147483647. Unsigned: 0 to 4294967295
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 95 of 120
BIGINT
Signed: -9223372036854775808. Unsigned: 0 to 18446744073709551615
The signed and unsigned are for minus and non-minus values. So, if you need to
store negative values, you need to be aware of the signed ranges. If you were
using a TINYINT value, for example, you can go from minus 128 to positive 127.
If you didn't need the minus value, you can go from 0 to positive 255.
For our address book, we have an ID field. We're using this just to identify a record
(row). Each record will be unique, so it will need a different number for each. We
can set it to one of the INT values. But which one?
If we set ID to TINYINT, then you'd run in to problem if you tried to store more
than 255 records. If you used SMALLINT, you'd have problems if you tried to
store the details of friend number 65536. IF you have more than 65 and half
thousand friends, then you need a different INT type. We'll assume that you don't,
so we'll use SMALLINT
➢ All Integer Types cannot follow the specified range; If range is assigned in
MySQL. So, Choose the One that is accurate as per your requirement against
your preliminary study of field’s
➢ Fields with any of the above Integer type can be made Primary Key.
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 96 of 120
Text Types
The length for the text types can be quite confusing. The MySQL manual says this
about the various lengths that each text type can hold:
TINYTEXT L+1 byte, where L < 2^8
TEXT L+2 bytes, where L < 2^16
MEDIUMTEXT L+3 bytes, where L < 2^24
LONGTEXT L+4 bytes, where L < 2^32
This in not terribly helpful for beginners! So, what does it mean. Well, the L + 1
part means, "The length of the string, plus 1 byte to store the value." The translated
values for each are approximately:
TINYTEXT 256 bytes
TEXT 64 KiloBytes
MEDIUMTEXT 16 MegaBytes
LONGTEXT 4 GigaBytes
➢ Text cannot follow the specified range; If range is assigned in MySQL.
➢ Fields with Text data type cannot be made Primary Key’s.
To confuse the issue even more, you can also use CHAR and VARCHAR to store
your text. These are quite useful, if you know how many characters you want to
store. For example, for a UK postcode you don't need more than 9 characters, and
one of those will be a blank space. So, there's no sense in setting a postcode field to
hold 4 gigabytes! Instead, use CHAR or VARCHAR.
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 97 of 120
CHAR
You specify how many characters you want the field to hold. The maximum value
is 255.
For example:
CHAR (10)
This field can then hold a maximum of ten characters. But if you only use 4 of
them, the rest of the 10 characters will be blank spaces. The blank spaces get added
to the right of your text:
"TEXT "
"TENLETTERS"
➢ But, if range not specified than it will show only one CHARACTER in the
output.
➢ Fields with CHAR data types can be set as Primary Keys with or without
specifying range.
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 98 of 120
VARCHAR
Like CHAR, but the rest of the characters are not padded with blank spaces. The
maximum value before MySQL 5.0.3 was 255. After this it's jumped to 65, 535.
With VARCHAR, there is also an extra byte that records how long your text is.
➢ But, if range not specified than MySQL creates a logical error.
➢ Fields with VARCHAR data types can be set Primary Keys but range must
be assigned.
UNIQUE
The UNIQUE constraint in MySQL does not allow to insert a duplicate value in a
column. The UNIQUE constraint maintains the uniqueness of a column in a table.
More than one UNIQUE column can be used in a table.
Null Constraint
This is an important field in database terminology. It essentially means, "Should
the field contain anything?" If you set a field to NOT NULL, then you can't leave it
blank when you come to adding records to your database. Otherwise you'll get
errors.
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 99 of 120
Extra (earlier versions of phpMyAdmin)
This is where you can set an auto increment value. This means adding one to the
previous record number. This is ideal for us, as we have an ID field. Then we don't
have to worry about this field. MySQL will take care of updating it for us.
*/
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 100 of 120
-- Implementation of Data Types via Code using Console: -
drop database if exists `lab`;
create database if not exists `lab`;
/*
drop table if exists `lab`.`std`;
create table if not exists `lab`.`std`
(
stdName varchar not null primary key
);
insert into `lab`.`std` values ('Nouman Farooq'), ('Arslan Farooq');
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 101 of 120
select * from `lab`.`std`;
*/
/*
drop table if exists `lab`.`std1`;
create table if not exists `lab`.`std1`
(
stdName varchar (7) not null primary key
);
insert into `lab`.`std1` values ('Nouman Farooq'), ('Arslan Farooq');
select * from `lab`.`std1`;
*/
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 102 of 120
/*
drop table if exists `lab`.`std2`;
create table if not exists `lab`.`std2`
(
stdName char not null primary key
);
insert into `lab`.`std2` values ('Nouman Farooq'), ('Arslan Farooq');
select * from `lab`.`std2`;
*/
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 103 of 120
/*
drop table if exists `lab`.`std3`;
create table if not exists `lab`.`std3`
(
stdName char (7) not null primary key
);
insert into `lab`.`std3` values ('Nouman Farooq'), ('Arslan Farooq');
select * from `lab`.`std3`;
*/
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 104 of 120
/*
drop table if exists `lab`.`std4`;
create table if not exists `lab`.`std4`
(
stdName text not null primary key
);
insert into `lab`.`std4` values ('Nouman Farooq'), ('Arslan Farooq');
select * from `lab`.`std4`;
*/
/*
drop table if exists `lab`.`std5`;
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 105 of 120
create table if not exists `lab`.`std5`
(
stdName text(6) not null primary key
);
insert into `lab`.`std4` values ('Nouman Farooq'), ('Arslan Farooq');
select * from `lab`.`std5`;
*/
/*
drop table if exists `lab`.`std6`;
create table if not exists `lab`.`std6`
(
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 106 of 120
stdName char not null primary key
);
insert into `lab`.`std6` values ('Nouman Farooq'), ('Arslan Farooq');
UPDATE `lab`.`std6` SET stdName = 'Muhammad Farooq Khan'
where stdName = 'Arslan Farooq';
select * from `lab`.`std6`;
*/
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 107 of 120
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 108 of 120
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 109 of 120
-- Joining Concepts - DS_ISP_Lecture 8 (Coding)
drop database if exists `JOINING`;
create database if not exists `JOINING`;
USE `JOINING`;
CREATE TABLE `JOINING`.`DEPARTMENT`
(
DepartmentId varchar(4) not null PRIMARY KEY,
DepartmentName text (12) not null
);
CREATE table `JOINING`.`EMPLOYEE`
(
LastName text (12),
DepartmentId varchar (4)
);
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 110 of 120
INSERT INTO `Joining`.`DEPARTMENT` VALUES (31,'Sales') ,
(33,'Engineering') , (34,'Clerical') , (35,'Marketing') ;
INSERT INTO `Joining`.`EMPLOYEE` (`LastName`, `DepartmentId`)
VALUES ('Rafferty', 31) , ('Jones', 33) , ('Heisenberg', 33) , ('Robinson', 34),
('Smith', 34) , ('Williams', ''); -- for insertion of empty value we use: ''
-- Cros Join: -
SELECT * from `JOINING`.`EMPLOYEE`
CROS JOIN
`JOINING`.`Department`
ORDER BY `CROS`.`DepartmentId` ASC; -- Example of an Explicit
Cross Join
SELECT * from `JOINING`.`EMPLOYEE` , `JOINING`.`Department`
ORDER BY `EMPLOYEE`. `LastName` ASC; -- Example of an Implicit
Cross Join
/* Something is implicit when it is implied but not directly stated. Something is
explicit when it is directly stated and leaves no room for uncertainty. */
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 111 of 120
-- Inner Join: -
/*
1. An inner join requires each record in the two joined tables to
have matching records.
2. Inner join creates a new result table by combining column values
of two tables (A and B) based upon the join-condition.
3. The query compares each row of A with each row of B to find all
pairs of rows which satisfy the join-condition.
*/
/* The "explicit join notation" uses the JOIN keyword, optionally
preceded by the INNER keyword, to specify the table to join, and the
ON keyword to specify the condition for the join, as in the following
example:
*/
SELECT * from `JOINING`.`EMPLOYEE`
Inner JOIN `JOINING`.`Department`
ON `Employee`.`DepartmentId` = `department`.`DepartmentId`
ORDER BY `EMPLOYEE`.`DepartmentId` ASC;
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 112 of 120
-- The following example is equivalent to the previous one, but this time using
implicit join notation:
SELECT * from `JOINING`.`EMPLOYEE` , `JOINING`.`Department`
WHERE
`EMPLOYEE`.`DEPARTMENTId` = `DEPARTMENT`.`DEPARTMENTId`
ORDER BY `EMPLOYEE`.`DepartmentId` ASC;
-- Outer Join: -
/*
1. An Outer Join does not require each record in the two joined
tables to have a matching record.
2. The joined table retains each record; even if no other matching
record exists.
3. Outer joins subdivide further into left outer joins, right outer joins,
and full outer joins, depending on which table's rows are retained
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 113 of 120
(left, right, or both). (In this case left and right refer to the two
sides of the JOIN keyword.)
4. No implicit join-notation for outer joins exists in standard SQL.
*/
-- Left Outer Join: -
/*
1. The result of a left outer join (or simply left join) for tables A and B always
contains all records of the "left" table (A), even if the join condition does not
find any matching record in the "right" table (B).
2. This means that if the ON clause matches 0 (zero) records in B (for a given
record in A), the join will still return a row in the result (for that record) but
with NULL in each column from B.
3. A left outer join returns all the values from an inner join plus all values in
the left table that do not match to the right table, including rows with NULL
(empty) values in the link field.
For example, this allows us to find an employee's department, but still shows the
employee(s) even when they have not been assigned to a department (contrary to
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 114 of 120
the inner-join example above, where unassigned employees were excluded from
the result).
Example of a left outer join (the OUTER keyword is optional), with the additional
result row (compared with the inner join):
-- SYNTAX to Use LEFT JOIN Condition: -
-- SELECT < selected list of fields for all fields use *> FROM
left_table LEFT JOIN right_table ON left_table.right_id =
right_table.id;
-- AND
-- SELECT < selected list of fields for all fields use *> FROM
left_table LEFT JOIN right_table ON right_table.left_id =
left_table.id;
*/
/*
SELECT * from `JOINING`.`EMPLOYEE`
LEFT JOIN
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 115 of 120
`JOINING`.`DEPARTMENT`
ON
`EMPLOYEE`.`DEPARTMENTId` = `DEPARTMENT`.`DEPARTMENTId`
ORDER BY ` DEPARTMENT`.`DepartmentName` ASC;
*/
-- SELECT * from `JOINING`.`EMPLOYEE` LEFT OUTER JOIN
`DEPARTMENT` ON `EMPLOYEE`.`DEPARTMENTId` =
`DEPARTMENT`.`DEPARTMENTId` ORDER BY
`EMPLOYEE`.`DepartmentId` ASC;
-- SELECT LASTNAME, DEPARTMENTNAME from
`JOINING`.`department` left JOIN `employee` ON
`DEPARTMENT`.`DEPARTMENTId` =
`EMPLOYEE`.`DEPARTMENTId`;
-- SELECT LASTNAME, DEPARTMENTNAME from
`JOINING`.`department` LEFT JOIN `employee` ON
`department`.`DEPARTMENTId` = `employee`.`DEPARTMENTId`
WHERE `DEPARTMENT`.`DEPARTMENTNAME` = 'SALES' ORDER BY
`EMPLOYEE`.`LASTNAME` ASC;
-- SELECT LASTNAME, DEPARTMENTNAME from
`JOINING`.`department` LEFT JOIN `employee` ON
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 116 of 120
`department`.`DEPARTMENTId` = `employee`.`DEPARTMENTId`
WHERE `EMPLOYEE`.`LASTNAME` = 'RAFFERTY';
-- SELECT `EMPLOYEE`.`DEPARTMENTID`, LASTNAME,
DEPARTMENTNAME from `JOINING`.`department` LEFT JOIN
`employee` ON `department`.`DEPARTMENTId` =
`employee`.`DEPARTMENTId` WHERE
`EMPLOYEE`.`DEPARTMENTID` = '31';
-- SELECT `EMPLOYEE`.`DEPARTMENTID`, LASTNAME,
DEPARTMENTNAME from `JOINING`.`department` LEFT JOIN
`employee` ON `department`.`DEPARTMENTId` =
`employee`.`DEPARTMENTId` WHERE
`EMPLOYEE`.`DEPARTMENTID` = 31;
-- SELECT EMPLOYEE.DEPARTMENTID, LASTNAME,
DEPARTMENTNAME from `JOINING`.`department` LEFT JOIN
`employee` ON `department`.`DEPARTMENTId` =
`employee`.`DEPARTMENTId` WHERE
`EMPLOYEE`.`DEPARTMENTID` > 31 AND
`EMPLOYEE`.`DEPARTMENTID` < 34;
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 117 of 120
-- Right Outer Join: -
/*
1. A right outer join (or right join) closely resembles a left outer join, except
with the treatment of the tables.
2. Every row from the "right" table (B) will appear in the joined table at least
once. If no matching row from the "left" table (A) exists, NULL will appear
in columns from A for those records that have no match in B.
3. A right outer join returns all the values from the right table and matched
values from the left table (NULL in the case of no matching join predicate).
For example, this allows us to find each employee and his or her department,
but still show departments that have no employees.
-- SYNTAX to Use RIGHT JOIN Condition: -
-- SELECT <select list> FROM left_table RIGHT JOIN right_table ON
left_table.id = right_table.id;
-- AND
-- SELECT <select list> FROM left_table RIGHT JOIN right_table ON
right_table.id = left_table.id;
*/
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 118 of 120
-- Below are some examples of a right outer join (the OUTER keyword is
optional):
-- SELECT * from `JOINING`.`EMPLOYEE` RIGHT OUTER JOIN
`DEPARTMENT` ON `EMPLOYEE`.`DEPARTMENTId` =
`DEPARTMENT`.`DEPARTMENTId` ORDER BY
`EMPLOYEE`.`DepartmentId` ASC;
-- SELECT LASTNAME, DEPARTMENTNAME from
`JOINING`.`department` right JOIN `employee` ON
`DEPARTMENT`.`DEPARTMENTId` =
`EMPLOYEE`.`DEPARTMENTId`;
-- SELECT LASTNAME, DEPARTMENTNAME from
`JOINING`.`department` right JOIN `employee` ON
`department`.`DEPARTMENTId` = `employee`.`DEPARTMENTId`;
-- SELECT LASTNAME, DEPARTMENTNAME from
`JOINING`.`department` right JOIN `employee` ON
`department`.`DEPARTMENTId` = `employee`.`DEPARTMENTId` ORDER
BY `EMPLOYEE`.`LASTNAME` DESC;
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 119 of 120
-- Full Join: -
/*
1. Conceptually, a full join combines the effect of applying both left and right
outer joins.
2. Also, records in the FULL JOIN tables do not match; the result set will have
NULL values for every column of the table that lacks a matching row. For
those records that do match, a single row will be produced in the result set
(containing fields populated from both tables).
For example, this allows us to see each employee who is in a department and
each department that has an employee, but also see each employee who is not
part of a department and each department which doesn't have an employee.
Important Note:
We don't have FULL JOINS on MySQL, but we can sure use this query to get our desired result as per full join definition.
Syntax with Two Tables “t1 and t2”: -
SELECT * FROM `db_name`.`t1`
LEFT JOIN `t2` ON `t1`.`column_name` = `t2`.`column_name`
UNION ALL
SELECT * FROM `db_name`.`t1`
RIGHT JOIN `t2` ON `t1`.`column_name` = `t2`.`column_name`
*/
INSTITUTE OF SOUTHERN PUNJAB (ISP)
MULTAN
Page 120 of 120
-- Below is an example of a full outer join (the OUTER keyword is optional):
SELECT * from `JOINING`.`EMPLOYEE`
LEFT JOIN `JOINING`.`DEPARTMENT`
ON `EMPLOYEE`.`DEPARTMENTId` =
`DEPARTMENT`.`DEPARTMENTId`
UNION ALL
SELECT * FROM `JOINING`.`EMPLOYEE`
RIGHT JOIN
`JOINING`.`EMPLOYEE`
ON `EMPLOYEE`.`DEPARTMENTId` = `DEPARTMENT`.`departmentId`;
-- End of Lab Activities Detailed Review- MySQL Coding Using Console