+ All Categories
Home > Documents > Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the...

Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the...

Date post: 12-Mar-2018
Category:
Upload: truongthu
View: 218 times
Download: 1 times
Share this document with a friend
103
INSTITUTE OF SOUTHERN PUNJAB (ISP) MULTAN Page 1 of 103 Department of Computer Science Laboratory Manual Prepared by: Muhammad Nouman Farooq Lecturer and Course Coordinator
Transcript
Page 1: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 1 of 103

Department of Computer Science

Laboratory Manual

Prepared by: Muhammad Nouman Farooq

Lecturer and Course Coordinator

Page 2: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 2 of 103

Course: Database Systems (CS-208 & CS-503)

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-103

Simulator Used: XAMPP Integrated Development Environment using

CONSOLE and Navicat Graphical User Interface (GUI)

Programming Language: SQL (Structured Query Language)

Page 3: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 3 of 103

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.

Page 4: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 4 of 103

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:

Page 5: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 5 of 103

Scenario 2:

Scenario 3:

Scenario 4:

Page 6: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 6 of 103

Scenario 5:

Scenario 6:

End of Lab Activity 1

Page 7: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 7 of 103

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

Page 8: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 8 of 103

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.

Page 9: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 9 of 103

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

Page 10: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 10 of 103

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.

Page 11: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 11 of 103

SQL CREATE DATABASE Syntax

CREATE DATABASE IF NOT EXISTS `dbname`

1. Create database northwind

SQL CREATE TABLE + CONSTRAINT Syntax

CREATE TABLE IF NOT EXISTS `database_name`.`table_name` ( columnName1 data_type not null AUTO_INCREMENT PRIMARY KEY,

columnName2 data_type(size), columnName3 data_type NOT NULL, columnName4 data_type(size) DEFAULT 'anytext', UNIQUE (columnName),

/*PRIMARY KEY (columnName), */

/* CONSTRAINT pk_columnName PRIMARY KEY (columnName1, columnName2,………) for more than one columns; but only create primary key’s with that syntax don’t use it in upper column*/

/* PRIMARY KEY (columnName1, columnName2,………) Or use that syntax for more than one columns */

CONSTRAINT fk_columnName FOREIGN KEY (columnName) REFERENCES ParentTableName (columnName),

CHECK (columnName > 0),

CHECK (columnName = ‘text’) )

Page 12: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 12 of 103

2. Create the tables in the northwind database by understanding the ERD of northwind

Page 13: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 13 of 103

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,...)

3. Insert any 5 rows in all the tables of northwind database.

Page 14: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 14 of 103

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.

Page 15: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 15 of 103

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 customers from the northwind database.

6. Truncate the table products.

7. Drop the northwind database.

End of Lab Activity 2

Page 16: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 16 of 103

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.

Page 17: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 17 of 103

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.

Page 18: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 18 of 103

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;

Page 19: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 19 of 103

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

Page 20: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 20 of 103

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. Insert your meaningful record into Customer table

2. Select customer id, name from the customer table

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

Page 21: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 21 of 103

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

Page 22: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 22 of 103

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.

Page 23: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 23 of 103

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

Page 24: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 24 of 103

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

Page 25: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 25 of 103

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

Page 26: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 26 of 103

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'

Page 27: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 27 of 103

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

Page 28: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 28 of 103

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

Page 29: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 29 of 103

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)

Page 30: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 30 of 103

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

Page 31: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 31 of 103

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

Page 32: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 32 of 103

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.

Page 33: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 33 of 103

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

Page 34: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 34 of 103

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

Page 35: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 35 of 103

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.

Page 36: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 36 of 103

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

Page 37: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 37 of 103

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

Page 38: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 38 of 103

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

Page 39: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 39 of 103

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

Page 40: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 40 of 103

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.

Page 41: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 41 of 103

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

Page 42: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 42 of 103

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

Page 43: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 43 of 103

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.

Page 44: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 44 of 103

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

Page 45: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 45 of 103

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.

Page 46: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 46 of 103

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

Page 47: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 47 of 103

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

Page 48: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 48 of 103

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

Page 49: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 49 of 103

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

Page 50: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 50 of 103

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'

Page 51: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 51 of 103

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

Page 52: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 52 of 103

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'

Page 53: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 53 of 103

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

Page 54: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 54 of 103

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

Page 55: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 55 of 103

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

Page 56: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 56 of 103

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

Page 57: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 57 of 103

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

Page 58: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 58 of 103

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

Page 59: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 59 of 103

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

Page 60: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 60 of 103

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

Page 61: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 61 of 103

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

Page 62: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 62 of 103

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.

Page 63: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 63 of 103

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

Page 64: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 64 of 103

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): -

Page 65: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 65 of 103

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.

Page 66: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 66 of 103

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

Page 67: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 67 of 103

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): -

127.0.0.1/phpmyadmin

Page 68: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 68 of 103

127.0.0.1: -

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

Page 69: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 69 of 103

Securing Server ROOT USER by Implementing Password using the following

steps: -

Go into Edit Privileges

Page 70: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 70 of 103

Then, Go into Change Password: -

Page 71: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 71 of 103

Than: -

Go into installed directory of XAMPP:

C:\xampp\phpMyAdmin

Open: config.inc

And Change: -

config to cookie

Page 72: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 72 of 103

Then, Change and Type that password that already assigned in Server: -

Page 73: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 73 of 103

Data Definition Language Commands (DDL Commands): -

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

Page 74: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 74 of 103

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

Page 75: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 75 of 103

Identifier: - `

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

Page 76: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 76 of 103

-- Without Selecting any database, we can also run some Queries: -

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

Page 77: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 77 of 103

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

Page 78: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 78 of 103

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),

Page 79: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 79 of 103

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

Page 80: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 80 of 103

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.

Page 81: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 81 of 103

And now on the ON DELETE side:

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.

*/

Page 82: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 82 of 103

/*

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 */

Page 83: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 83 of 103

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

Page 84: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 84 of 103

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 */

Page 85: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 85 of 103

select * from `lab1`.`test` order by `test`.`testId` limit 1; -- To limit the output

of a record in ascending order

select * from `lab1`.`test` order by `test`.`testId` limit 1 offset 1; -- To limit the

output of a record in descending order

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

Page 86: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 86 of 103

/*

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

Page 87: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 87 of 103

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

Page 88: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 88 of 103

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)

);

Page 89: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 89 of 103

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

Page 90: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 90 of 103

-- 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)

);

Page 91: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 91 of 103

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

Page 92: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 92 of 103

-- 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. */

Page 93: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 93 of 103

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

*/

Page 94: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 94 of 103

/* 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;

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

Page 95: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 95 of 103

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

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

*/

Page 96: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 96 of 103

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

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;

Page 97: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 97 of 103

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

`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

Page 98: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 98 of 103

`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

`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` =

Page 99: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 99 of 103

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

Page 100: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 100 of 103

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

*/

Page 101: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 101 of 103

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

Page 102: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 102 of 103

-- 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`

*/

Page 103: Prepared by: Muhammad Nouman Farooq Lecturer and · PDF fileDrop the table customers from the northwind database. 6. Truncate the table products. 7. Drop the northwind database. End

INSTITUTE OF SOUTHERN PUNJAB (ISP)

MULTAN

Page 103 of 103

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


Recommended