5 MySQL-Rev
5 MySQL-Rev
Database • Tables
• Queries
Some Commonly used RDBMS • Views
software are- Oracle, • Index
Relational Model
RDBMS Terminology
Relation (Table)
A Relation or Table is Two-Dimensional (Matrix) like structure
arranged in Rows and Columns. It has the following properties-
Column homogeneous - All items in a column are of
same data type.
Each column assigned a unique name and must have atomic
(indivisible) value.
All rows of a relation are distinct i.e. no two identical rows
(records) can exist in the Relation.
Ordering or Rows (Records) or Columns (fields) are
immaterial.
Domain
It is collection (set) of possible values from which the value for a
column is derived.
Tuple/ Entity/ Record :
A Row of a table is called Tuple or Record.
Attribute/ Field:
Column of a table is called Attribute or Field.
Degree : Number of columns (attributes) in a table.
Cardinality : Number of Records in a table.
Concept of Keys
In a Relation, each record must be unique i.e. no two identical
records are allowed in the Database. A column or combination of
column which identifies a record called Key of the Table. A key
attribute must have unique (non-repeatable ) value.
Primary Key
A set of one or more column that can uniquely identify a record in
the relation is called Primary Key.
Candidate Key
A Column or group of columns which can be used as primary key
are called Candidate keys, as they are candidate to become as
Primary key.
Alternate Key
A Candidate Key that is not a Primary key is called Alternate key.
Foreign Key
A non-key column whose values are derived from the primary key
of some other table is called Foreign key.
Introduction to MySQL
MySQL is an Open Source, Fast and Reliable Relational Database
Management System (RDBMS) . It is alternative to many of the
commercial RDBMS. The main features of MySQL are-
Open Source & Free of Cost:
It is Open Source and available free of cost. It is part of LAMP
(Linux, Apache, MySQL, PHP/ Perl/ Python) Open Source group.
Portability:
It can be installed and run on any types of Hardware and OS like
Linux, MS Windows or Mac etc.
Security :
It offers privilege and password system for authorization.
Connectivity
It may connect various types of client using different protocols and
Programming Languages .
Query Language
It uses SQL (Structured Query Language) as query language,
which is standardized by ANSI.
Types of SQL Commands
MySQL follows SQL specifications for its commands . These
SQL commands can be categorized as -
Data Definition Language (DDL)
These SQL commands are used to create, alter and delete
database objects like table, views, index etc.
Example : CREATE , ALTER , DROP etc.
Data Manipulation Language (DML)
These commands are used to insert, delete, update and retrieve
the stored records from the table.
Ex. SELECT…., INSERT…, DELETE…, UPDATE…. etc.
Transaction Control Language (TCL)
These commands are used to control the transaction.
Ex. COMMIT, ROLLBACK, SAVEPOINT etc.
Data Control Language (DCL)
These commands are used to manipulate permissions or access
rights to the tables etc.
Ex. GRANT , REVOKE etc.
Database Handling commands in MySQL
Creating a Database.
The following command will create School database in MySQL.
mysql> CREATE DATABASE School;
Opening a database
To open an existing database, following command is used.
mysql> USE school ;
Getting listings of database and tables
mysql> SHOW DATABASES;
mysql> SHOW TABLES;
Deleting a Database and Table
mysql> DROP DATABASE School;
mysql> DROP TABLE Student;
Viewing Table Structure
S
mysql> DESCRIBE Student; e
Shows the name of
l
currently
e open database
c
t
Data type in MySQL
Numeric Data Types:
INTEGER or INT – up to 11 digit number without decimal.
SMALLINT – up to 5 digit number without
decimal.
FLOAT (M,D) or DECIMAL(M,D) or
NUMERIC(M,D)
Stores Real numbers upto M digit length
(including .) with D
decimal places.
e.g. Float (10,2) can store 1234567.89
Date & Time Data Types:
DATE - Stores date in YYYY-MM-DD format.
TIME - Stores time in HH:MM:SS format.
String or Text Data Type:
CHAR(Size)
A fixed length string up to 255 characters. (default is 1)
Char,Varchar, Date and Time values should be enclosed with single (‘ ‘) or
VARCHAR(Size)
double ( “”) quotes in MySQL.
A variable length string up to 255 characters.
Creating Tables
Creating Simple Tables:
CREATE TABLE < Table Name>
(<Col name1><data type>[(size)][Constraints],….);
Data types- INTEGER, NUMERIC(P,D), CHAR(n), VARCHAR(n), DATE etc.
MySQL will display the all records with all columns in the Student
table.
* Is used to represent all columns.
StID Name Fname DOB City Class
S1 Amitabh Harivansh Rai 1948-11-10 Allahabad 12
S2 Sharukh Firoz 1970-05-10 Delhi 11
S3 Irphan Akbar 1970-10-05 Jaipur 11
S4 Salman Salim Javed 1972-04-10 Mumbai 10
S5 Abhishek Amitabh 1975-03-12 Mumbai 10
Making Simple Queries – Cont..
Selecting columns
If you want to view only Name and City columns of the student table
mysql> SELECT Name, City FROM Student ;
Name City
Amitabh Allahabad
Sharukh Delhi
Irphan Jaipur
Salman Mumbai
Abhishek Mumbai
City
Mumbai is repeated
Allahabad
Delhi
Jaipur
Mumbai
Mumbai
Relational Operators
We can use the following Relational operators in condition.
=, > , < , >=, <=, <>, IS , LIKE, IN,
BETWEEN
Logical Operators
We can use the following Logical Operators to connect two conditions.
OR , AND , NOT (!)
Specifying List – IN
Operator
mysql> SELECT * FROM Emp
WHERE Sal IN (5000, 10000) ;
The same query can also be written as
-
mysql> SELECT * FROM Emp
Selecting Specific Rows – WHERE clause
In this syntax:
•First, specify the name of the table from which you want to drop the
foreign key after the ALTER TABLE keywords.
•Second, specify the constraint name after the DROP FOREIGN
KEY keywords.
Notice that constraint_name is the name of the foreign key constraint
specified when you created or added the foreign key constraint to the
table.
Working with Functions
What is Function?
A function is a special types of command that
performs some operation and returns a single
value as a result.
It is similar to method or function in JAVA, which
can be called by giving some argument.
Types of Functions:
Numeric Functions
String Functions
Date & Time Function
Aggregate Functions
Numeric Functions
These functions may accept some numeric values and
performing required operation, returns numeric values as result.
STR_TO_DATE Converts a string into a date and time value based on a specified
format.
SYSDATE Returns the current date.
TIMEDIFF Calculates the difference between two TIME or DATETIME values.
1. A _________ is pre-defined set of commands that is used to perform a specific task and return values.
2. The values that are provided to function is called __________ or __________.
3. The ___________ functions allows to manipulate the text from table or string passed as parameter to
the function.
4. The ___________ function returns the character for the passed integer number.
5. To display a specific word from a text, __________ function is used.
6. The ____________ function removes leading extra spaced from the text.
7. To know the length of specified text, the __________ function is used.
8. The ___________ function accepts numeric values and returns numerical values as well.
9. The ___________ function returns remainder of specified two numbers.
10.A _________ MySQL function returns square of the given number.
11.Mr. Kalpesh wants to ignore the fractional part of the number. A ___________ function will help him to
serve his purpose.
12.To know the square root of the given number in MySQL ___________ function will be used.
Answers
1.function
2.parameters, arguments
3.text/string
4.char()
5.substr() or substring() or mid()
6.ltrim()
7.length()
8.Numeric
9.mod()
10.pow()/power()
11.round()
12.sqrt()
13.truncate()
Aggregate Functions
Name Purpose Example
SUM() Returns the sum of given Select SUM(Pay) from Emp;
column. Select Sum(Pay),
Sum(Net) from Emp;
MIN() Returns the minimum value Select MIN(Pay) from Emp;
in the given column.
MAX() Returns the maximum value Select MAX(Pay) from Emp;
in the given column.
AVG() Returns the Average value of Select AVG(Pay) from Emp;
the given column.
COUNT() Returns the total number of Select COUNT(Name) from Emp;
values/ records in given Select COUNT(*) from Emp;
column.
Aggregate Functions should not be used with other columns which may
have multiple values in the table. The following query is illogical and
wrong. Why? Think yourself….
Select sum(pay), name from Employee;
The MySQL GROUP BY Statement
The GROUP BY statement groups rows that have the same values into summary rows,
like "find the number of customers in each country".
The GROUP BY statement is often used with aggregate functions
(COUNT(), MAX(), MIN(), SUM(), AVG()) to group the result-set by one or more columns.
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
If you want to total salary for all employees then we used
the SUM function and you will get a sum of the total salary.
COUNT(CustomerID) Country
3 Argentina
2 Austria
2 Belgium
9 Brazil
3 Canada
2 Denmark
2 Finland
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;
COUNT(CustomerID) Country
13 USA
11 Germany
11 France
9 Brazil
7 UK
5 Mexico
5 Spain
MySQL HAVING Clause
HAVING Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
Lists the number of customers in each country. Only
include countries with more than 5 customers:
B) After dividing the amount into EMIs, find out the remaining amount to be paid immediately, by performing
modular division. Following SQL query can be used to solve the above-mentioned problems.
Items_Ordered
Customers
From the items_ordered table, select the item, maximum price, and
minimum price for each specific item in the table. Hint: The items will
need to be broken up into separate groups.
How many orders did each customer make? Use the items_ordered
table. Select the customerid, number of orders they made, and the sum
of their orders. Click the Group By answers link below if you have any
problems.
SELECT state, count(state)
FROM customers
GROUP BY state;
Display the customer Id and number of cars purchased if the customer purchased more
than 1 car from SALE table
Display the number of people in each category of payment mode from the table SALE
Display the PaymentMode and number of payments made using that mode more than once.
We can perform certain operations on relations like
Intersect operation is used to get the common tuples from two tables and is represented by the symbol ∩.
Figure 1.4 shows intersection of two sets
Music Dance Figure 1.4: Intersection of two sets Suppose we have to display the list of students who are
participating in both the events (DANCE and MUSIC), then intersection operation is to be applied on these two
tables.
The output of INTERSECT operation is shown in Table 1.13. Table 1.13 DANCE ∩ MUSI
MINUS (-)
This operation is used to get tuples/rows which are in the first table but not in the second table, and
the operation is represented by the symbol - (minus). Figure 1.5 shows minus operation (also called set
difference) between two sets
Cartesian Product
Inner Join
Self Join
Natural Join
Non-Equal Join
Cartesian Product
(Unrestricted Join)
Mysql>SELECT * FROM
MUSIC CROSS JOIN
DANCE
Select * from Student Cross Join Games;
Student Games
Roll No Name Game no Game
1 Rohan 10 Football
2 Jay 11 Tennis
3 Tina
Syntax:
SELECT columns
FROM table1
LEFT [OUTER] JOIN table2
ON table1.column = table2.column;
SELECT officers.officer_name, officers.address, students.course_name
FROM officers
LEFT JOIN students
ON officers.officer_id = students.student_id;
MySQL Right Outer Join
The MySQL Right Outer Join returns all rows from the RIGHT-hand table specified in
the ON condition and only those rows from the other table where he join condition is
fulfilled.
SELECT columns
FROM table1
RIGHT [OUTER] JOIN table2
ON table1.column = table2.column;