Introduction to MySQL Environment Pt1 complete (1)
Introduction to MySQL Environment Pt1 complete (1)
Environment
Pt.1
Prof. Olufunke Oladipupo
Mr. Chukwuebuka Ejiobih
Mr. Henry Ogbu
Lecture Outline
• DDL commands
• To create a database objects
• CREATE
• DML commands
• To manipulate data of a database objects part 1
• INSERT Statements
• SELECT Statements
• UPDATE Statements
Lecture Objectives
SHOW DATABASES;
Selecting a DATABASE
You must select a database to work with from the server
with the query:
USE nameofdatabase;
DATATYPES in MySQL Environment
(SQL Server
Data Types
link)
Row as Tuple
Column as Attribute
DDL
• The main SQL command for data definition
• CREATE statement
• create schemas, tables (relations), and domains
(as well as other constructs such as views, indexes,
assertions, and triggers).
Main SQL DDL
• CREATE SCHEMA DROP SCHEMA
• CREATE/ALTER DOMAIN DROP DOMAIN
• CREATE/ALTER TABLE DROP TABLE
• CREATE VIEW DROP VIEW
• Many DBMSs also provide: CREATE INDEX DROP
INDEX
DDL cont.
• Environment
• DBMS
• Catalog.
• a named collection of schemas in an SQL
environment
• Schema
• Domain
• Objects in a schema
• Tables, Views, Domains, assertions , etc
• All have same owner
CREATE SCHEMA
CREATE SCHEMA Name_of_Schema;
Example 1
CREATE SCHEMA COMPANY;
CREATE TABLE
CREATE TABLE COMPANY.EMPLOYEE ... Explicit
rather than
Update table_name
SET column_to_update = newValue
WHERE identifier=value;
Unique Constraint
• The unique constraint is used to show that all values in a column
are uniquely different.
• Example:
);
Unique Constraint
• If you forgot to include the unique constraint at the
point of creating a table, you can add it by using:
• Example:
Insert into Skill( skill_Id, ssn, Number_of_Skill)
Values( 010, 3, 9),
( 011, 9, 2),
( 012, 6, 12);
Exercise
• Insert a row into the skill table with the value of ssn as 3
• a) query the table skill to display its content
• b) Apply the unique constraint on the column ssn (state
your observation)
• c) delete the record where the skill_Id is 010 and repeat
the step in (b)
• d) Try to insert a new record with ssn value of 3 again
and interpret the outcome
Timestamp using default Date and
Time
• Timestamp datatype is an 8-byte value representing a
date and time value in the format: YYYY-MM-DD and
HH:MM:SS
);
Lets insert values into the
transaction table
INSERT INTO transaction (Transaction_no, Product ,
Amount, customer_Id)
values (8, "Apple", 200.20, 5),
(2, "sharwama", 2500, 2),
(3, "Diaper", 5500, 1),
(4, "Calculator", 7000, 6),
(5, "T-Shirt", 15000, 1),
(9, “Calculator", 200.20, 2);
Result of Example 2
• Result of query
Primary-Foreign Key Relationship
Transactions_Table Customers_Table
Applying a Foreign Key to a Table
that Already existed
• To apply a FK constraint to a table that already existed, use the query:
FROM customers;
Example 5 Use of DISTINCT
• List the address of all everyone that is a
customer.
SELECT address
FROM customers;
Example 5 Use of DISTINCT
• Use DISTINCT to eliminate duplicates:
74
Example 8 Calculated Fields
• To name column, use AS clause:
75
Example 9 Comparison Search
Condition
List all staff with a salary greater than 10,000.
SELECT staffNo, fName, lName, position, salary
FROM Staff WHERE salary > 10000;
76
Example 9 Compound Comparison
Search Condition
List addresses of all branch offices in London or
Glasgow.
SELECT *
FROM Branch
WHERE city = “London” OR city =
“Glasgow”;
77
Example 10 Range Search Condition
List all staff with a salary between 20,000 and 30,000.
SELECT staffNo, fName, lName, position, salary
FROM Staff
WHERE salary BETWEEN 20000 AND 30000;
78
Example 10 Range Search
Condition
• Also a negated version NOT BETWEEN.
• BETWEEN does not add much to SQL’s expressive
power. Could also write:
79
Example 11 Set Membership
List all managers and supervisors.
SELECT staffNo, fName, lName, position
FROM Staff
WHERE position IN (‘Manager’, ‘Supervisor’);
80
Example 11 Set Membership
• There is a negated version (NOT IN).
• IN does not add much to SQL’s expressive power.
• Could have expressed this as:
81
Example 12 Pattern Matching
Find all owners with the string ‘Glasgow’ in their address.
82
Example 12 Pattern Matching
• SQL has two special pattern matching symbols:
• %: sequence of zero or more characters;
• _ (underscore): any single character.
83
Example 13 NULL Search Condition
List details of all viewings on property PG4 where a comment has
not been supplied.
• There are 2 viewings for property PG4, one with and one without
a comment.
84
Example 13 NULL Search Condition
85
Example 14 Single Column
Ordering
List salaries for all staff, arranged in descending order of
salary.
86
Example 14 Single Column Ordering
87
Example 15 Multiple Column
Ordering
Produce abbreviated list of properties in order of property
type.
88
Example 15 Multiple Column Ordering
89
Example 15 Multiple Column Ordering
90
Example 15 Multiple Column
Ordering
91
SELECT Statement - Aggregates
92
SELECT Statement - Aggregates
93
SELECT Statement - Aggregates
• COUNT(*) counts all rows of a table, regardless of whether
nulls or duplicate values occur.
94
SELECT Statement - Aggregates
• Aggregate functions can be used only in SELECT list and in
HAVING clause.
95
Example 16 Use of COUNT(*)
How many properties cost more than $350 per month to
rent?
96
Example 16 Use of COUNT(DISTINCT)
How many different properties viewed in May ‘04?
97
Example 16 Use of COUNT and SUM
Find number of Managers and sum of their salaries.
98
Example 17 Use of MIN, MAX, AVG
Find minimum, maximum, and average staff salary.
99
SELECT Statement - Grouping
• Use GROUP BY clause to get sub-totals.
• SELECT and GROUP BY closely integrated: each item in
SELECT list must be single-valued per group, and SELECT
clause may only contain:
• column names
• aggregate functions
• constants
• expression involving combinations of the above.
100
SELECT Statement - Grouping
• All column names in SELECT list must appear in GROUP BY
clause unless name is used only in an aggregate function.
• If WHERE is used with GROUP BY, WHERE is applied first,
then groups are formed from remaining rows satisfying
predicate.
• ISO considers two nulls to be equal for purposes of GROUP
BY.
101
Example 18 Use of GROUP BY
Find number of staff in each branch and their total
salaries.
SELECT branchNo,
COUNT(staffNo) AS count,
SUM(salary) AS sum
FROM Staff
GROUP BY branchNo
ORDER BY branchNo;
102
Example 18 Use of GROUP BY
103
Restricted Groupings – HAVING clause
• HAVING clause is designed for use with GROUP BY to
restrict groups that appear in final result table.
• Similar to WHERE, but WHERE filters individual rows
whereas HAVING filters groups.
• Column names in HAVING clause must also appear in the
GROUP BY list or be contained within an aggregate
function.
104
Example 19 Use of HAVING
For each branch with more than 1 member of staff, find number of
staff in each branch and sum of their salaries.
SELECT branchNo,
COUNT(staffNo) AS count,
SUM(salary) AS sum
FROM Staff
GROUP BY branchNo
HAVING COUNT(staffNo) > 1
ORDER BY branchNo;
105
Example 19 Use of HAVING
106
Subqueries
• Some SQL statements can have a SELECT embedded
within them.
• A subselect can be used in WHERE and HAVING clauses of
an outer SELECT, where it is called a subquery or nested
query.
• Subselects may also appear in INSERT, UPDATE, and
DELETE statements.
107
Example 20 Subquery with Equality
List staff who work in branch at ‘163 Main St’.
108
Example 20 Subquery with Equality
• Inner SELECT finds branch number for branch at ‘163
Main St’ (‘B003’).
110
Example 21 Subquery with Aggregate
List all staff whose salary is greater than the
average salary, and show by how much.
SELECT staffNo, fName, lName, position,
salary – (SELECT AVG(salary) FROM Staff) As SalDiff
FROM Staff
WHERE salary >
(SELECT AVG(salary)
FROM Staff);
111
Example 21 Subquery with
Aggregate
• Cannot write ‘WHERE salary > AVG(salary)’
• Instead, use subquery to find average salary (17000), and
then use outer SELECT to find those staff with salary
greater than this:
112
Example 21 Subquery with
Aggregate
113
Subquery Rules
• ORDER BY clause may not be used in a subquery
(although it may be used in outermost SELECT).
114
Example 22 Nested subquery: use
of IN
List properties handled by staff at ‘163 Main St’.
SELECT propertyNo, street, city, postcode, type, rooms, rent
FROM PropertyForRent
WHERE staffNo IN
(SELECT staffNo
FROM Staff
WHERE branchNo =
(SELECT branchNo
FROM Branch
WHERE street = ‘163 Main St’));
115
Example 22 Nested subquery: use
of IN
116
Create Horizontal View
Create view so that manager at branch B003 can
only see details for staff who work in his or her office.
CREATE VIEW Manager3Staff
AS SELECT *
FROM Staff
WHERE branchNo = ‘B003’;
117
Create Vertical View
Create view of staff details at branch B003 excluding salaries.
118
Class Activity 2 (Database Tables)
Customer_t Orderline_t
119
Class Activity 2 (Database Tables) cont.
Product _t
Order_t
120
Question 1.
12/28/2024
Solution
12/28/2024
Question 2
12/28/2024
Solution
SELECT CUSTOMER_NAME AS NAME ,
CUSTOMER_ADDRESS
FROM CUSTOMER_t
WHERE CUSTOMER_NAME =‘Home
Furnishings’;
12/28/2024
Question 3
• List the unit price, product name and product ID for all
products in the product table.
12/28/2024
Solution
12/28/2024
Question 4
• What is the average standard price for product in inventory.
12/28/2024
Question 5
12/28/2024
Question 5
12/28/2024
Question 6
12/28/2024
Question 7
12/28/2024
Solution
12/28/2024
Question 8
12/28/2024
Question 9
• Count the number of customers with address in each state to
which we ship
12/28/2024
Question 10
• Find only states with more than one customer
State StateNumber
CA 2
FL 3
NJ 2
12/28/2024
Question 11
• List the product finish and average standard price for cherry,
natural ash, natural maple and white ash, where the average
standard price is less than 750.
12/28/2024
Exercises
138
Lecture Reference
• Ramakrishnan, R., Gehrke, J.: Database Management Systems.
USA: McGraw Hill Companies (2000)
• Elmasri, R., & Navathe, S. (2000). Fundamentals of database
systems (3rd ed.). Reading, Mass.: Addison-Wesley.
• Hoffer, J. A., Prescott, M. B., & McFadden, F. R. (2005). Modern
database management. Upper Saddle River, N.J: Pearson/ Prentice
Hall.
• Connolly, T. M., & Begg, C. E. (2002). Database systems: A
practical approach to design, implementation, and management.
Harlow, England: Addison-Wesley
• http://pages.cs.wisc.edu/~dbbook/openAccess/thirdEdition/solution
s/ans3ed-oddonly.pdf
• https://gyires.inf.unideb.hu/GyBITT/03/ 139
SQL Server Data Types
140
SQL Server Data Types cont.
https://www.w3schools.com/sql/sql_datatypes.asp
141
SQL Server Data Types cont.
https://www.w3schools.com/sql/sql_datatypes.asp
143
SQL Server Data Types cont.
Back
144