ALRIGHT!
MYSQL TUTORIAL
SETUP AND START WORING ON LINUX
Topics
MySql Installation
Securing MySQL
Testing connectivity with MySQL
Basic necessary queries
Creating Database
Creating Table
Inserting data into the table
Reading data from Table
Update data into a table
Step 1: Installation
#yum install mysql-server.x86_64
Start/Enable MySQL
#sudo systemctl status mysqld.service
#sudo systemctl start mysqld.service
#sudo systemctl enable/disable mysqld.service
Step 2: Changing default options
Secure the authentication process by
setting password for root
#sudo mysql_secure_installation
Step 3: Testing Connection
You can verify your installation with the
mysqladmin tool
#mysqladmin -u root -p version
To connect and start using SQL Queries
#mysql -u root -p
Some Important Queries in starting
SHOW DATABASES;
SHOW TABLES;
USE <database_name>
Creating a new Database
CREATE DATABASE <db_name>;
CRUD
CREATE
READ
UPDATE
DELETE
Creating a new Table
CREATE TABLE students (
id INT,
name VARCHAR(100)
)
CREATE TABLE students (name VARCHAR(100), age INT)
Checking yout table
DESC TABLE
Adding data into a Table
INSERT INTO students(id, name)
VALUES (101, "Rahul")
INSERT INTO students VALUES (101, "Rahul")
Reading data from a Table
SELECT * FROM <table_name>
SELECT <column_name> from students
Modify/Update data from a Table
UPDATE students
SET contact=12345
WHERE name='Raju';
DELETE data from a Table
DELETE FROM students
WHERE name='Raju';
Deleting a Database or Table
DROP DATABASE <db_name>;
DROP TABLE <table_name>;
THANKS FOR WATCHING
Databases
List All Existing Database
SHOW DATABASES;
Creating a new Database
CREATE DATABASE <db_name>;
Working with a Database
USE <db_name>;
Deleting a Database
DROP DATABASE <db_name>;
Tables
Table
A table is a collection of related data
held in a table format within a database.
Creating a new Table
CREATE TABLE students (
id INT,
name VARCHAR(100)
)
CREATE TABLE students (name VARCHAR(100), age INT)
Checking your table
DESC TABLE
Adding data into a Table
INSERT INTO students(id, name)
VALUES (101, "Rahul")
INSERT INTO students VALUES (101, "Rahul")
Reading data from a Table
SELECT * FROM <table_name>
SELECT <column_name> from students
Modify/Update data from a Table
UPDATE students
SET contact=12345
WHERE name='Raju';
DELETE data from a Table
DELETE FROM students
WHERE name='Raju';
DataTypes
DataTypes
An attribute that specifies the type of data in a
column of our database - table.
Most widely used are
Numeric - INT DOUBLE FLOAT DECIMAL
String - VARCHAR
Date
NOT NULL
DEFAULT Value
CREATE TABLE employee(
name VARCHAR(100),
acc_type VARCHAR(50) DEFAULT 'savings'
);
Primary Key
Primary Key
The PRIMARY KEY constraint uniquely identifies each
record in a table.
Primary keys must contain UNIQUE values, and cannot
contain NULL values.
A table can have only ONE primary key.
AUTO_INCREMENT
ALIAS
WHERE
Exercise - 1
Task
Create a database - bank_db
Create a table - employees
emp_id
name
desig
dept
emp_id column should not allow duplicate and null values
Value of emp_id column should auto increment
name column should not contain null value
desig column should have default value as 'Probation'
Task
Insert the following data
Task
Display the data
Exercise - 2
Task
Display the data
Task
Update the following data
Task
DELETE the following data
String Functions
CONCAT
CONCAT(first_col, sec_col)
CONCAT(first_word, sec_word, ...)
CONCAT_WS
CONCAT_WS('-', fname, lname)
SUBSTRING
SELECT SUBSTRING('Hey Buddy', 1, 4);
SUBSTRING
SELECT SUBSTRING('Hey Buddy', 1, 4);
1 4
Result: Hey
REPLACE
REPLACE
Hey Buddy Hello Buddy
Hey Hello
REPLACE(str, from_str, to_str)
REPLACE('Hey Buddy', 'Hey', 'Hello')
REVERSE
SELECT REVERSE('Hello World');
CHAR_LENGTH
Select CHAR_LENGTH('Hello World');
UPPER & LOWER
SELECT UPPER('Hello World');
SELECT LOWER('Hello World');
Other Functions
SELECT INSERT('Hello Wassup', 6, 0, 'Raju');
SELECT LEFT('Abcdefghij', 3);
SELECT RIGHT('Abcdefghij', 4);
SELECT REPEAT('o', 5);
SELECT TRIM(' Alright! ');
Exercise - 3
Task 1:
101:Raju:Manager:Loan
Task2:
101:Raju Rastogi:Manager:Loan
Task3
101:Raju:MANAGER:Loan
Task4
L101 Raju
C102 Sham
DISTINCT
SELECT DISTINCT fname FROM employees;
ORDER BY
SELECT * FROM employees ORDER BY fname;
LIKE
Select * FROM employees
WHERE dept LIKE "%Acc%";
LIMIT
SELECT * FROM employees LIMIT 3;
ALTER TABLE employees
ADD COLUMN
salary INT NOT NULL
DEFAULT 25000;
GROUP BY
Loan Cash Account
Deposit
IT
SELECT dept FROM employees GROUP BY dept;
SELECT dept, COUNT(fname) FROM employees GROUP
BY dept;
COUNT
SELECT COUNT(*) FROM employees;
MAX & MIN
SELECT MAX(age) FROM employees;
SELECT MIN(age) FROM employees;
SELECT emp_id, fname, salary FROM employees
WHERE
salary = (SELECT MAX(salary) FROM employees);
SUM & AVG
SELECT SUM(salary) FROM employees;
SELECT AVG(salary) FROM employees;
Exercise - 4
DISTINCT, ORDER BY, LIKE and LIMIT
1: Find Different type of departments in database?
2: Display records with High-low salary
3: How to see only top 3 records from a table?
4: Show records where first name start with letter 'A'
5: Show records where length of the lname is 4 characters
1 2
3
4
5
Exercise - 5
COUNT, GROUP BY, MIN, MAX and SUM and AVG
1: Find Total no. of employees in database?
2: Find no. of employees in each department.
3: Find lowest salary paying
4: Find highest salary paying
5: Find total salary paying in Loan department?
6: Average salary paying in each department
DATAYPES
CHAR vs VARCHAR
DATAYPES
The CHAR and VARCHAR types are similar,
but differ in the way they are stored
and retrieved.
DATAYPES
VARCHAR(50)
The length can be specified as a value
from 0 to 65,535.
DATAYPES
CHAR is fixed length
CHAR(5) --> Only 5 character allowed
The length can be any value from 0 to
255.
DATAYPES
When CHAR values are stored, they are right-
padded with spaces to the specified length.
When CHAR values are retrieved, trailing spaces
are removed unless the PAD_CHAR_TO_FULL_LENGTH
SQL mode is enabled.
CHAR(4)
If you try to insert value 'AB'
MySQL will store the value as 'AB '
CHAR can be used in case of fixed length values
like
Country code: US, IN, AU
DATAYPES
DECIMAL
DATAYPES
So far we have only used and seen
INT Datatype...
DATAYPES
What will happen when we store
values like 15.35?
DATAYPES
DECIMAL(6,3)
The maximum number of digits for DECIMAL is 65
DATAYPES
Digits after decimal
DECIMAL(5,2)
Total digit
DATAYPES
Example: 155.38
119.12
28.15
1150.15
DATAYPES
FLOAT, DOUBLE
DATAYPES
FLOAT, DOUBLE
MySQL uses four bytes for single-precision
values and eight bytes for double-precision
DATAYPES
FLOAT, DOUBLE
Float - upto ~7 digits, takes 4 bytes of memory
Double - upto ~15 digits, takes 8 bytes of memory
DATAYPES
DATE, TIME, DATETIME
DATAYPES
DATE, TIME, DATETIME
DATE
yyyy-mm-dd format
DATAYPES
DATE, TIME, DATETIME
TIME
HH:MM:SS format
DATAYPES
DATE, TIME, DATETIME
DATETIME
'yyyy-mm-dd HH:MM:SS' format
DATE TIME Functions
CURDATE, CURTIME, NOW
DATE TIME Functions
CURDATE() - yyyy-mm-dd
CURTIME() - hh:mm:ss
NOW() - yyyy-mm-dd hh:mm:ss
DATE TIME Functions
DAYNAME,
DAYOFMONTH,DAYOFWEEK
DATE Formatting
DATE Formatting
Suppose we need to get date in a given format like
Tue Mar 28th
21st Tue at 21:20:28
2023/04/18
DATE Formatting
DATE_FORMAT()
DATE_FORMAT(now(), '%D %a at %T')
Result: 21st Tue at 21:20:28
DATE_FORMAT(now(), '%m/%d/%y')
Result: 04/16/23
DATE Formatting
DATE_FORMAT()
DATE_FORMAT(now(), '%H:%i')
Result: 20:34
DATE_FORMAT(dob, '%r')
Result: 08:35:48 PM
DATE MAth
DATEDIFF(expr1, expr2)
DATE_ADD(date, INTERVAL expr unit)
DATE_SUB(date, INTERVAL expr unit)
DATE_ADD('2023-05-01',INTERVAL 1 DAY)
DATE_ADD('2023-05-01',INTERVAL 1 YEAR)
DATE_SUB('2023-05-01',INTERVAL 1 MONTH)
TIMEDIFF(expr1, expr2)
TIMEDIFF('20:00:00', '18:00:00')
DEFAULT &
ON UPDATE TIMESTAMP
CREATE TABLE blogs (
text VARCHAR(150),
created_at DATETIME default CURRENT_TIMESTAMP,
updated_at DATETIME ON UPDATE CURRENT_TIMESTAMP
);
Exercise - 6
Exercise - 6
Print the current time (HH:MM:SS)
Print the current date (yyyy-mm-dd)
Print current day of the week (Monday, Tuesday...)
What is the use case of CHAR datatype?
Which datatype can be used to store value 123.456?
Display date in format
dd:mm:yyyy
April 22nd at 22:00:00
Exercise - 6
Solution
Exercise - 6
Print the current time (HH:MM:SS)
Print the current date (yyyy-mm-dd)
Print current day of the week (Monday, Tuesday...)
What is the use case of CHAR datatype?
Which datatype can be used to store value 123.456?
Display date in format
dd:mm:yyyy
April 22nd at 22:00:00
Exercise - 6
SELECT CURTIME();
SELECT CURDATE();
SELECT DAYNAME(NOW());
What is the use case of CHAR datatype?
Which datatype can be used to store value 123.456?
Display date in format
dd:mm:yyyy - date_format(now(), '%d:%m:%Y')
April 22nd at 22:00:00 - date_format(now(), '%M %D at %T')
Operators
Relational Operators
Find employees whose salary is more than
65000
We have relational =
operators
=
SELECT * FROM employees
WHERE salary > 65000;
Logical Operators
AND
OR
Condition 1 AND Condition 2
When both the conditions are true
salary=25000 AND dept=Loan
Condition 1 OR Condition 2
When either of the condition is true
salary=65000 OR desig='Lead'
IN, NOT IN
Find employees From following department
Account
Cash
Loan
SELECT * FROM employees
WHERE dept = 'Account'
OR dept = 'Cash'
OR dept = 'Loan';
SELECT * FROM employees
WHERE dept IN ('Account', 'Cash', 'Loan');
BETWEEN
Find employees whose salary is more than
40000 and Less than 65000
>40000
<65000
SELECT * FROM employees
WHERE
salary >=40000 AND salary <=65000;
SELECT * FROM employees
WHERE
salary BETWEEN 40000 AND 65000;
CASE
IS NULL
IS NULL
SELECT * FROM employees
WHERE fname IS NULL;
NOT LIKE
IS NULL
SELECT * FROM employees
WHERE fname NOT LIKE 'A%';
Exercise - 7
Find employees whose salary are between
30000 to 40000
Find employees whose first name start with
'R' or 'S'
Find employee whose salary=25000 and
department should be 'Cash'
Find employees from following designation
Manager, Lead and Associate
Exercise - 7
Solution
CONSTRAINT
UNIQUE
What if we need to store the
phone numbers in a column.
CONSTRAINT
CHECK
We want to make sure phone no. is
atleast 10 digits...
NAMED CONSTRAINT
ALTERING
Tables
How to add or remove a column?
How to rename a column or table name?
How to rename a column?
How to rename a table name?
How to modify a column?
Ex: Changing datatype
or adding Default values etc
How to add DEFAULT value to a column?
How to change column name and set NOT
NULL?
How to Add or Drop Constraints?
How to Check Existing Constraints?
Relationship
RElATIONSHIP
Simple data and table...
Real World
Data is not that simple...
Employees
Salary Attendance
Employees
offices
requests task
Types of Relationship
One to One
One to Many
Many to Many
1:1
Employees
Employee
Details
1 : MANY
Employees
Employee Task
Many : Many
Books Authors
Book B
Book C
Book D
Author A
Book A
Author B
Let's Understand a Use-Case of
1:Many
Suppose we need to store the following data
customer name
customer email
order date
order price
Customers Orders
cust_id order_id
cust_name order_date
cust_email order_amount
Customers Orders
cust_id order_id
cust_name order_date
cust_email order_amount
cust_id
Customers
Orders
Foreign Key
Customers
Orders
Primary Key
Customers
Foreign Key
Primary Key
Orders
Let's work practically with
Foreign Key..
JOINS
JOIN operation is used to combine rows
from two or more tables based on a related
column between them.
Primary Key
Customers
Foreign Key
Primary Key
Orders
Types of Join
Cross Join
Inner Join
Left Join
Right Join
Cross Join
Every row from one table is combined with
every row from another table.
Inner Join
Returns only the rows where there is a match
between the specified columns in both the
left (or first) and right (or second) tables.
Inner Join with Group By
Left Join
Returns all rows from the left (or first) table
and the matching rows from the right (or
second) table.
Right Join
Returns all rows from the right (or second)
table and the matching rows from the left (or
first) table.
CASCADE ON DELETE
Primary Key
Customers
Foreign Key
Primary Key
Orders
Exercise - 8
Books
Authors
book_id
author_id title
author_name ratings
au_id
Exercise - 8
Solution
Many : Many
Let's Understand a Use-Case of
Many : Many
Students Courses
Course A
Student A
Course B
Course C
Student A
Course A
Student B
Student C
courses
students id
id
course_name
student_name
fees
students
id
student_name student_course
student_id
courses course_id
id
course_name
fees
students
id
student_name student_course
student_id
courses course_id
id
course_name
fees
Exercise - 9
Solution
Print No. of students for each course.
Print No. of courses taken by each students
Total FEES Paid by Each Student
VIEWS
HAVING Clause
GROUP BY ROLLUP
STORED Routine
STORED Routine
An SQL statement or a set of SQL
Statement that can be stored on
database server which can be call no. of
times.
Types of STORED Routine
STORED Procedure
User defined Functions
STORED Procedure
STORED PROCEDURE
These are routines that contain a series of
SQL statements and procedural logic.
Often used for performing actions like data
modification, transaction control, and
executing sequences of statements.
USER DEFINED FUNCTIONS
WINDOW FUNCTIONS
Introduced in version 8.0.
Window functions, also known as analytic
functions allow you to perform calculations
across a set of rows related to the current row.
Defined by an OVER() clause.
ROW_NUMBER()
RANK()
DENSE_RANK()
LAG()
LEAD()