MySQL Notes PDF - MPrashant
MySQL Notes PDF - MPrashant
x
We can test SQL commands here Click Here- W3
Section Topics Details Comments
We can call it a collection of data
A method for accessing and manipulating that data
Installation on MAC Although we can install WorkBench to use the GUI Version alias mysql="/usr/local/mysql/bin/mysql"
If somehow Workbench is not working, you can use the 3rd party
Intro and Installation DBGate Installation tool like this Replacement of Workbench
We can take example of
SHOW DATABASES; Employee, Students
Show databases A mysql is a DB Server which may have multiple DataBases With graphical example
For db name use
underscore or camel case
Creating Database CREATE DATABASE <db_name> student_db or AppStore
Dropping Database DROP DATABASE <db_name>
USE <db_name> to select the DB when you do show databases
How to Use Database? SELECT database(); to check which DB are you using it will show already existing databases.
SHOW TABLES;
What are tables? Collection of related data in a structured format We store data in tables.
At the time of defining the structure of our table i.e. columns name,
we do need to define the type of data
Example: Age should be a no., name should be String
SHOW TABLES; to check your tables (It will show tables under
current DB, first you need to do USE <db>
Working with quotes In case ' is part of string then use \ In some others type of SQL, double quotes are not allowed
OR
SELECT SUBSTRING(title, 1, 10) AS 'short title' FROM books; If only one no. is provided then from 7th to end
SUBSTRINGS SELECT SUBSTR(title, 1, 10) AS 'short title' FROM books; SUBSTR will also work
SELECT CONCAT
(
SUBSTRING(title, 1, 10),
'...'
) AS 'short title'
FROM books;
COMBINING STRING FUNC We can use function inside function as per the requirement
This can be done in any editor like
Workbench (there is paint brush option)
UPPER & LOWER SELECT UPPER(title) FROM books; To change the string in either upper or lower case
SELECT INSERT('Hello Bobby', 6, 0, 'There');
STRING FUNCTIONS Other Functions SELECT TRIM(' pickle '); - will trim the white space
Select DISTINCT dept from employees;
For Query only Unique Data
SELECT DISTINCT CONCAT(fname,' ', lname) FROM employees;
Can be used with combination of columns too like
DISTINCT SELECT DISTINCT fname, lname FROM employees; full name should be same
sorting the result based on the given column
like sort with firstname or year
In case NULL is there then it will appear first
Select * from employees ORDER BY fname DESC; We can explicityly mention DESC for descending
We can also give Column no but it is not readable If we give more than one column then firstly First column will be
ORDER BY Select * from employees Order By 2 sorted then under that data second column will be sorte
Limit the no. of data of result
Select * from employees LIMIT 5;
If two no. are given then starts with 3 and 5 columns
LIMIT Select * from employees LIMIT 3,5; Note: data index starts with 0
when you are looking for someting like
LIKE select * from employees LIKE '%abc%' If we need to search % or _ in records then use \% similarly \_
SELECT COUNT(*) FROM employees;
COUNT SELECT COUNT(DISTINCT dept) FROM employees; To count the no. of record based on given condition
It will first group all the employees based on department
SELECT
author_lname,
COUNT(*) as books_written,
MAX(released_year) AS latest_release,
MIN(released_year) AS earliest_release, In this example
MAX(pages) AS longest_page_count
FROM books GROUP BY author_lname; We first grouped the students based on section
MIN MAX with GROUP By Then min or max (biggest class in a section)
SELECT SUM(salary) FROM employees;
SELECT
dept,
AVG(salary),
COUNT(*) FROM employees
AVG GROUP BY dept;
1: Find Different type of departments in database?
AGGREGATION FUNCTION Exercises 5: Show records where length of the lname is 4 characters
VARCHAR is better
If we use CHAR(5), then even if we store a value of 3 char, sql will
add 3 whitespace to fill that space and store it, space optimization
vise it is useless
But we can use for fixed lenght values like country code IN, US, etc Reference docs
CHAR vs VARCHAR it will be faster https://dev.mysql.com/doc/refman/8.0/en/data-types.html
INT, TINYINT, BIGINT
DECIMAL(5,2) - (total no. of digit, upto decimal) like 999.99
upto 3 digits are allowed and two decimals
99.99 is right
DECIMAL 9999.99 is not
FLOAT DOUBLE Based on the decimal precision
YYYY-MM-DD
HH:MM:SS
DATE and TIME INSERT INTO people (name, birthdate, birthtime, birthdt)
DATETIME YYYY-MM-DD HH:MM:SS VALUES ('Elton', '2000-12-25', '11:00:00', '2000-12-25 11:00:00');
Built-in functions to get the time
CURDATE(), CURTIME(), NOW()
SELECT
birthdate,
DAY(birthdate),
DAYOFWEEK(birthdate),
DAYOFYEAR(birthdate)
FROM people;
SELECT
birthdate,
MONTHNAME(birthdate),
By using some functions we can get more info like YEAR(birthdate)
FROM people;
Date Function From date, if you need only Month or Year or Day
SELECT
birthtime,
HOUR(birthtime),
MINUTE(birthtime)
FROM people;
SELECT
birthdt,
MONTH(birthdt),
DAY(birthdt),
HOUR(birthdt),
MINUTE(birthdt)
FROM people;
Time Function For getting only Hour or Min
we can define the format of the date and time to be shown in the
result of the query SELECT birthdate, DATE_FORMAT(birthdate, '%a %b %D') FROM
DATE_FORMAT(birthdate, '%a %b %D') people;
DATE_FORMAT(dob, '%m/%d/%y') Result: Tue Mar 27th
DATE_FORMAT(now(), '%D %a at %T') Result: 21st Tue at 22: SELECT birthdt, DATE_FORMAT(birthdt, '%H:%i') FROM people;
28:48
SELECT birthdt, DATE_FORMAT(birthdt, 'BORN ON: %r') FROM
Formatting date people;
DATEDIFF(date1, date2) : 2 -1
We can use once after birthday when will person become 18 years
DATE_ADD(date, INTERVAL expr)
Date Math DATE_SUB(date, INTERVAL expr) DATE_ADD(2020-12-12, INTERVAL 18 YEARS)
Can also be used to store date or time or datetime format
TIMESTAMP takes little storage as compared to DATE command Can be used as data type
CREATE TABLE captions2 (
text VARCHAR(150),
created_at TIMESTAMP default CURRENT_TIMESTAMP, ON UPDATE - whenever we update the row, updated_at column will
ON UPDATE updated_at TIMESTAMP ON UPDATE CURRENT_TIMESTAMP be updated with latest timestamp
Datatypes CURRENT_TIMESTAMP ); useful when we need to keep the record when was data updated
SELECT * FROM books
!= WHERE released_year != 2017;
To drop a column
ALTER TABLE companies DROP COLUMN phone;
To DROP A column
A one-to-one relationship in SQL can be defined with foreign keys Example: Employees table with Contact detail table
where each record in one table corresponds to one and only one one employee will only having one contact detail.
One to One record in another table.
Customers - orders
Bad Way
Making a single table -
When a customer buy something multiple times, there will be
duplicate entries of customer and messy data
Good Way
Separate tables for customer and orders with unique ids A many-to-many relationship in SQL is defined using a junction table
We can use customer_id in orders table like Foreign key that holds foreign keys referencing the primary keys of the related
One To Many tables.
CREATE TABLE customers (
customer_id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50));
-- To perform a (kind of useless) cross join: A cross join is a join operation that returns the Cartesian product of
SELECT * FROM customers, orders; two tables, producing all possible combinations of rows from both
CROSS JOIN tables.
SELECT
first_name, last_name, SUM(amount) AS total
FROM
customers
JOIN
orders ON orders.customer_id = customers.id
GROUP BY first_name , last_name select customer_id, COUNT(amount) from orders GROUP BY
ORDER BY total; customer_id;
INNER JOIN with GROUP BY
Left join means, everything from Left table (table which we kept first
SELECT in the query)
first_name, last_name, order_date, amount
FROM In this case customers
customers
LEFT JOIN Difference?
orders ON orders.customer_id = customers.id; Suppose there are few customers who never placed any orders
those also will be reflected in the result which is not the case in
LEFT JOIN INNER JOIN
SELECT
first_name,
last_name,
IFNULL(SUM(amount), 0) AS money_spent
FROM
customers
LEFT JOIN
orders ON customers.id = orders.customer_id
GROUP BY first_name , last_name;
LEFT JOIN with GROUP BY
SELECT
first_name, last_name, order_date, amount
FROM
customers
RIGHT JOIN
orders ON customers.id = orders.customer_id;
RIGHT JOIN
CREATE TABLE orders ( if you try to delete a customer data which is refferenced in orders
id INT PRIMARY KEY AUTO_INCREMENT, table, you will not be able to do that
order_date DATE,
amount DECIMAL(8 , 2 ), For that purpose, you need to use
customer_id INT, ON DELETE CASCADE
FOREIGN KEY (customer_id)
REFERENCES customers (id) Now when we try to delete any customer data
ON DELETE CASCADE it's associated orders will also be deleted
);
ON DELETE CASCADE
SELECT
first_name,
IFNULL(AVG(grade), 0) AS average,
CASE
WHEN IFNULL(AVG(grade), 0) >= 75 THEN 'passing'
ELSE 'failing'
END AS passing_status
FROM
students
LEFT JOIN
papers ON students.id = papers.student_id
GROUP BY first_name
Relationships and Joins ORDER BY average DESC;
One: MANY Exercise
Students
CREATE TABLE students (
s_id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
Courses
CREATE TABLE courses (
c_id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL,
fee NUMERIC NOT NULL
);
Enrollment
CREATE TABLE enrollment (
enrollment_id SERIAL PRIMARY KEY,
s_id INT NOT NULL,
c_id INT NOT NULL,
enrollment_date DATE NOT NULL,
FOREIGN KEY (s_id) REFERENCES students(s_id),
FOREIGN KEY (c_id) REFERENCES courses(c_id)
);
============================================
INSERT INTO Students (name) VALUES
('Raju'),
('Sham'),
('Alex');
Altering or Deleting Details of CREATE VIEW my_view2 AS But there is one more way, create a VIEW from the result of existing
Virtual Tables SELECT * FROM my_view1; view
VIEWS
SELECT The HAVING clause is used in the SELECT statement with the
title, GROUP BY clause.
AVG(rating), It filters rows from the result set after grouping and aggregation
COUNT(rating) AS review_count operations have been performed.
FROM full_reviews The HAVING clause operates on aggregated values (e.g., the result
GROUP BY title HAVING COUNT(rating) > 1; of SUM, COUNT, AVG, etc.) and filters groups based on these
HAVING aggregated values.
DELIMITER $$
DELIMITER ;
SP with parameters
DELIMITER $$
return v_name;
END$$
set @p_sum = 0;
DELIMITER ; call bank_db.get_sum('Raju', @p_sum);
STORED ROUTINES USER-DEFINED FUNCTIONS select @p_sum;
select
ROW_NUMBER() OVER () row_no,
emp_id,
fname,
salary,
for each row from a query, perform SUM(salary) OVER (ORDER BY emp_id) sum
a calculation using rows related to from employees;
that row.
Parition by
can be used to calculate based on grouping
MAX(salary) OVER (PARTITION BY dept) MAX in this example, it will first group the dept then find the max salary
RANK() OVER(ORDER BY salary DESC) ranking if there are two emp with same salary, their rank will be same
We can combine the windows
operation like OVER(PARTITION BY dept ORDER BY salary DESC)
If two students have 400 marks and third student have 350 marks
RANK() will rank like std1 - 1st rank, std2 - 1st rank, and 3rd student
- 3rd rank
SELECT
emp_no,
department,
salary,
salary - LAG(salary) OVER(ORDER BY salary DESC) as
salary_diff
FROM employees;
SELECT
emp_no,
department,
salary,
salary - LAG(salary) OVER(PARTITION BY department ORDER
BY salary DESC) as dept_salary_diff
WINDOWS Function LEAD & LAG Funciton FROM employees;
CREATE TRIGGER trigger_name
What is Trigger? AFTER INSERT ON table_name
FOR EACH ROW
A trigger is a stored procedure in BEGIN
SQL that automatically executes in -- Trigger logic here
response to specific events on a END;
particular table or view.
WITH AvgSal AS (
SELECT
dept, AVG(salary) AS avg_salary FROM employees
GROUP BY
dept
)
SELECT
e.emp_id, e.fname, e.dept, e.salary,
What is CTE a.avg_salary
FROM
CTE (Common Table Expression) is employees e In short, we are first executing a query, get the result and then using
a temporary result set that you can JOIN it in another query.
define within a query to simplify AvgSal a ON e.dept = a.dept
complex SQL statements. WHERE Once CTE has been created it can only be used once. It will not be
CTE e.salary > a.avg_salary; persisted.
Import
mysql -u root -p mydatabase <
mydatabase_backup.sql