0% found this document useful (0 votes)
20 views

MYSQL Session Notes

notes

Uploaded by

emargins15
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

MYSQL Session Notes

notes

Uploaded by

emargins15
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 11

MYSQL

-------
Session-01
----------
File Management System
-----------------------
Information / data stored in file.
MS Excel

What is a Database ?

The database is a collection of inter-related data which is used to retrieve,


insert and delete the data efficiently.
It is also used to organize the data in the form of a table, schema, views, and
reports, etc.

C - Create
R- Read
U - Update
D - Delete

Example : The college Database organizes the data about the admin, staff, students
and faculty etc.

Using the database, you can easily retrieve, insert, and delete the information.

Types Of Database
-----------------
1) DBMS ( Database management System) Dbase, Foxpro
2) RDBMS (Relational Database Management System) - MySQL, SQL Serever, DB2, Oracle,
MS-Access..

SQL (Structure Query Language)- used to communicate with the database to perform
different kinds of operations.

Components of Database
----------------------
1) Server - actual data is stored
2) Client - used to perform operations on databse server

Types of client
---------------
Graphical user Interface client
Command line client

MySQL Clients
-------------
MySQL Workbench (GUI Client)
MySQL Shell (CLI Client)
Toad
Squirell

Install MySQL
-------------

Session-02
--------------
1) Working on MySQL Workbench & Command prompt client
2) SQL Commands

Types of SQL Commands


-----------------------
1. DDL (Data Definition Language)
Create, Alter, Drop, Truncate , Rename
Commands are auto committed

2. DML (Data Manupulation Language)


Insert, Update, Delete
DML Commands are not auto commited means it cant permanetly save all the changes in
the database. They can be rollback.

3. DCL (Data Control Language) (Administrative use)


Grant, Revoke

4. TCL (Transaction Control Language)


Commit , Rollback, Savepoint

5. DQL (Data Query Language)


Select

CREATE DATABASE IF NOT EXIST databasename;


CREATE SCHEMA databasename;

DROP DATABASE databaseName;


DROP SCHEMA databaseName;

CREATE TABLE EMPLOYEE(Name VARCHAR(20), Email VARCHAR(100), DOB DATE);


describe Student;

INSERT INTO Student values(1, "Prachi", 77);


INSERT INTO Student (SNO, SNAME, MARKS)values(1, "Prachi", 77);

Session-03
----------
How to select Data from the table?
Select

mysql -u root -p employees < employees.sql

set path=%PATH%;C:\Program Files\MySQL\MySQL Server 8.0\bin;

Error Code: 1075. Incorrect table definition; there can be only one auto column and
it must be defined as a key

SQL Datatypes
--------------
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);

Numeric
Text
Date/Time

->WHERE CLAUSE
-------------
SELECT column1, column2, ...
FROM table_name
WHERE condition;

Session-04
-----------

ORDER BY (For Sorting the rows in the result)

SELECT
select_list
FROM
table_name
ORDER BY
column1 [ASC|DESC],
column2 [ASC|DESC],
...;

MySQL DISTINCT clause to remove duplicates from the result given by the SELECT
clause.

SELECT DISTINCT
select_list
FROM
table_name
WHERE
search_condition
ORDER BY
sort_expression;

Session-05

OPERATORS
---------
AND operator
It is used in the WHERE clause of the SELECT, UPDATE, DELETE statements to form a
condition.
The AND operator is used to filter records based on more than one condition

SELECT column1, column2, ...


FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;
Or Operator

SELECT column1, column2, ...


FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;

Ex1.

SELECT
customername,
country
FROM
customers
WHERE country = 'USA' OR
country = 'France';

Ex2.

SELECT
customername,
country,
creditLimit
FROM
customers
WHERE(country = 'USA'
OR country = 'France')
AND creditlimit > 100000;

The OR operator displays a record if any of the conditions are TRUE.


The AND operator displays a record if all the conditions are TRUE.

Not Operator
The NOT operator is used in combination with other operators to give the opposite
result

NOT LIKE
NOT BETWEEN
NOT IN
NOT GREATER THAN (>)
NOT LESS THAN (<)

IN Opertator
The IN operator allows you to specify multiple values in a WHERE clause.

Session- 06
-----------
DDL Commands

Primary Key
A primary key is a column or a set of columns that uniquely identifies each row in
the table.

Rules of Primary Key:

1) A primary key must contain unique values. If the primary key consists of
multiple columns, the combination of values in these columns must be unique.

2 )A primary key column cannot have NULL values. Any attempt to insert or update
NULL to primary key columns will result in an error.
MySQL implicitly adds a NOT NULL constraint to primary key columns.

3) A table can have one an only one primary key.


DROP TABLE table_name;

DDL Commands (Auto committed)


---------------------------------
1) Create Table- Used for creating database objects like a database and a database
table, views, Triggers etc.

2) Alter Table - Used for modifying and renaming elements of an existing database
table. Add new column, Drop column, Modify existing column, Rename column

3) Truncate Table- Used to remove all the records from a database table.
TRUNCATE TABLE table_name;

DELETE FROM TABLE_NAME WHERE Condition; (DML, not auto committed)

4) Drop Table- Used for removing an entire database or a database table.


DROP TABLE table_name;

5) Rename Table- Used to change the name of the database table.

RENAME TABLE old_table _name To new_table_name;

ALTER TABLE table_name RENAME TO new_table_name;

Session-07
----------
1) String Functions
2) Mathematical/Numeric functions
3) Date/Time Functions
4) Aggregate Function

Session-08
-----------
1) Mathematical/Numeric functions
2) Date/Time Functions
3) Aggregate Function

Session-09
-----------
Group By Clause
In MySQL GROUP BY clause is used to collect data from multiple records and group
the result by one or more column.
Group by clause is often used with aggregate functions such as SUM, AVG, MAX, MIN,
and COUNT.

Filter the records based on condition


----------------------------------------
Having Clause - After Group By Clause

Where Clause - before Group By Clause


Order By - to sort the records/result

Select Column-names
From Table-name
where condition
Group By Column-names
Having condition
Order By Column-names

-------------------------SQL Queries----------------------------------------

create database project_hr;

select * from employees;

select department_id, count(*) from employees group by department_id;

select * from employees where department_id=5;

select department_id, sum(salary) from employees group by department_id;

select department_id, min(salary), max(Salary) from employees group by


department_id;
select * from employees;

select job_id, department_id ,count(*) from employees group by job_id,


department_id;
select job_id, count(*) from employees group by job_id having count(*) > 2;

select department_id, sum(salary) from employees group by department_id having


sum(salary) > 20000;

select department_id, sum(salary) from employees where department_id <> 6 group by


department_id having sum(salary) > 20000;

select * from employees order by salary desc;

select department_id, sum(salary) from employees group by department_id order by


sum(salary) desc;

select department_id, sum(salary) from employees


where department_id <> 6
group by department_id having sum(salary) > 20000
order by sum(salary) desc;

Session -10
------------
Set Operators
1. Union - UNION operator combine two or more result sets from multiple SELECT
statements into a single result set.

2. Union all - The UNION ALL command combines the result set of two or more SELECT
statements (allowsduplicate values).

3. Intersect (INTERSECT was added in MySQL 8.0.31.) - compares the result sets of
two queries and returns the common rows.
Intersect ALL (allow duplicates)

4. Except (Minus) (EXCEPT was added in MySQL 8.0.31.)- allows you to retrieve rows
from one query that do not appear in another query. EXCEPT operator find the set
difference between two sets of data.

Rules
=====
The number of columns in all the SELECT statements must be the same.
The order of columns in all the SELECT statements must be the same.
The data types of the corresponding columns in both SELECT statements must be the
same or similar or convertible/compatible.

CREATE TABLE A (
col1 INT ,col2 INT
);

CREATE TABLE B (
col1 INT ,col2 INT
);

CREATE TABLE C (
col1 INT ,col2 INT
);

INSERT INTO A VALUES (1,2),(2,3),(3,4);


INSERT INTO B VALUES (1,2),(1,3),(3,4);
INSERT INTO C VALUES (1,3),(1,3),(3,4);

CREATE TABLE t1 (
id INT
);

CREATE TABLE t2 (
id INT
);

INSERT INTO t1 VALUES (1),(2),(3);


INSERT INTO t2 VALUES (2),(3),(4);

select * from t1;


select * from t2;

select * from t1
union
select * from t2;

select * from t1
union all
select * from t2;

select concat(contactFirstName, contactLastName) As Fullname from customers


union
select concat(firstName,"", lastName) from employees;

select * from t1
intersect
select * from t2;

Session -11
-----------
JOINS
-----

JOINS are used with SELECT statement. It is used to retrieve data from multiple
tables.
The tables are mutually related using primary and foreign keys.

TYPES OF JOINS
--------------

1) INNER JOIN / simple join - Matched records.

SELECT
select_list
FROM t1
INNER JOIN t2 ON join_condition1
INNER JOIN t3 ON join_condition2
...;

2) LEFT OUTER JOIN / LEFT JOIN - Matched records from both the tables + un matched
records from left table.
SELECT
select_list
FROM
t1
LEFT JOIN t2 ON
join_condition;

3) RIGHT OUTER JOIN / RIGHT JOIN - Matched records from both the tables + un
matched records from right table.
SELECT
select_list
FROM t1
RIGHT JOIN t2 ON
join_condition;

4) CROSS JOIN (or Cartesian join) - is used to generate a paired combination of


each row of the first table with each row of the second table.
5) FULL JOIN - To retrieve all records from both tables, whether there is a match
or not.
Not supported in MySQL.
use demodb;
CREATE TABLE t1 (
num INT
);

CREATE TABLE t2 (
num INT
);

INSERT INTO t1 VALUES (10),(11),(12),(14);


INSERT INTO t2 VALUES (11),(12),(13),(15);

select * from t1 inner join t2 on t1.num = t2.num;

use project_hr;
select * from employees inner join departments on employees.department_id =
departments.department_id;

SELECT
productCode,
productName,
textDescription
FROM
products t1
INNER JOIN productlines t2
ON t1.productline = t2.productline;

SELECT
productCode,
productName,
textDescription
FROM
products
INNER JOIN productlines
using (productline);

select * from t1 left join t2 on t1.num = t2.num;

use classicmodels;
SELECT
customers.customerNumber,
customerName,
orderNumber,
status
FROM
customers
LEFT JOIN orders
ON customers.customerNumber = orders.customerNumber
WHERE
orderNumber IS NULL;

select * from t1 right join t2 on t1.num = t2.num;

use demodb;
SELECT * FROM T1 cross join T2;
Session -12
===========

Sub Queries

A MySQL subquery is a query nested within another query such as SELECT, INSERT,
UPDATE or DELETE.
Also, a subquery can be nested within another subquery.

A MySQL subquery is called an inner query while the query that contains the
subquery is called an outer query.

The output of inner query becomes input of outer query

There are two types of sub queries;


1. Single row sub query (<=, >=, !=)
2. Multi row sub Query (IN, ANY, ALL)

select * from employees;


select * from employees where salary > 12000;
select salary from employees where first_name ='Michael';

-- select employees whose is greater than 'Michael's' salary


select * from employees where salary > (select salary from employees where
first_name ='Michael');

-- the following query returns the customer who has the highest payment.
SELECT MAX(amount) FROM payments;
SELECT
customerNumber,
checkNumber,
amount
FROM
payments
WHERE
amount = (SELECT MAX(amount) FROM payments);

select * from employees;


-- 2nd highest salary from employees table
select max(salary) from employees;

select max(salary) from employees where salary < (select max(salary) from
employees);

-- List employees having highest salary


select first_name from employees where salary = (select max(salary) from
employees);

-- 3rd highest salary from employees table


select max(salary) from employees where salary <
(select max(salary) from employees where salary <
(select max(salary) from employees));

-- find the customers who have not placed any orders


SELECT DISTINCT
customerNumber
FROM
orders;

SELECT
customerName
FROM
customers
WHERE
customerNumber NOT IN (SELECT DISTINCT
customerNumber
FROM
orders);

-- query to get first name, lastname department id and department name


select first_name, last_name, department_id,
(select department_name from departments where employees.department_id =
departments.department_id) departmentname from employees;

You might also like