Lesson plan
TOTAL HOURS:
Subject: MySQL DATE
Introduction, History, Feature, Version Datatype, Variable. MySQL Data Definition 20-6-23
Language: Create, Alter, Drop, Truncate, 23-6-23
Data Manipulation Language: Insert, select, delete, Update, 7-7-23
11-7-23
Data Control language: Grant, revoke.
MySQL Key: Primary key, Unique key, foreign key, Null, Not Null, Auto Increment, Default,
Boolean,
Condition: And, Or, Like, not like In, Between, Not, Not equal. SQL Where • SQL And & Or •
SQL Order By
MySQL Union, Union All, Distinct value
SQL Functions
1. SQL Group By, SQL Having.
2. Aggregate Function- max, min, count, avg, sum
2. Math Function---ABS, Sqrt, Ceil, Floor, Div, Mod, Pow, Random, Round
3.String function-----
ASCII(), CHAR_LENGTH(), CONCAT(), REVERSE(), SUBSTR(),TRIM(),STRCMP(),
UPPER(), POSITION(), Replace()
4.Date function-----CURRENT_DATE(), CURRENT_TIME(), NOW(),SYSDATE(),Month(),
5.Additional function-----bin(), user(),version(),Database(),conv().
SQL Joins;
• SQL Inner Join
• SQL Left Join
• SQL Right Join
• SQL Full Join
Subqueries: Definition, Application, example
MySQL IF Statement
• MySQL CASE Statement
• IF vs. CASE
MYSQL VIEWS
• Introduction to Database View
• Views in MySQL
• MySQL CREATE VIEW
any, all with example
Interview question
If statement IF statement can be used to conditionally execute code based on a specified
condition
Definition
Syntax IF condition THEN
-- Code to execute when condition is true
ELSE
-- Code to execute when condition is false
END IF;
Or
IF(condition, statement1, statement2);
select
1. Select all products and show a message for out-of-stock products
select id,name,price,quantity,if(quantity=0,'out','')as result from products;
2. write a query display only those student name whose pass and fail
pass above 50 Below fail
SELECT empname, IF(salary> 6000, 'high', 'low') AS result FROM emp1;
Real time example
SET @age = 25;
SELECT IF(@age >= 18, 'You are an adult', 'You are a minor') AS status;
SELECT IF(STRCMP('Rinky Ponting','Yuvraj Singh')=0, 'Correct', 'Wrong');
Suppose you have a table called employees with the following columns: id,
name, age, and salary. You want to create a new column called bonus that
will be calculated based on the employee's age and salary. If the employee is
younger than 30 years old and earns less than $50,000 per year, they will
receive a bonus of $5,000. Otherwise, they will not receive a bonus.
TEST
1. to check person eligible for vote or not
2. Suppose you have a table called orders with the following columns:
id, customer_id, order_date, and order_total. You want to update the
order_total column for all orders placed by customer with
customer_id of 1234 by increasing the value by 10%, but only if the
original order_total is less than $100.
Select case
SELECT CASE is a useful feature in MySQL that allows you to conditionally
select a specific value
Syntax
SELECT
column1,
column2,
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
ELSE default_result
END as new_column
FROM
table_name;
1. suppose you have a table called employees with columns id, name,
and salary, and you want to add a new column called bonus based on
the employee's salary.
SELECT
EMPID,
EMPNAME,
salary,
CASE
WHEN salary > 50000 THEN 'High'
WHEN salary > 30000 THEN 'Medium'
ELSE 'Low'
END as bonus
FROM
Emp1;
Select CASE 300
WHEN 100 THEN 'It is matched'
WHEN 200 THEN 'It is not matched'
ELSE 'No use of this Number'
END as 'Matching the Number';
Interview question
Demonstrate simple calculator
CREATE TABLE calculator1(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
operand1 DECIMAL(10,2),
operand2 DECIMAL(10,2),
operator CHAR(1)
);
INSERT INTO calculator1 (operand1, operand2, operator)
VALUES
(5, 10, '+'),
(20, 5, '-'),
(3, 4, '*'),
(10, 2, '/'),
(10, 0, '/'),
(2, 3, '%');
SELECT id, operand1, operand2, operator,
CASE operator
WHEN '+' THEN operand1 + operand2
WHEN '-' THEN operand1 - operand2
WHEN '*' THEN operand1 * operand2
WHEN '/' THEN
CASE
WHEN operand2 = 0 THEN 'Error: divide by zero'
ELSE operand1 / operand2
END
WHEN '%' THEN operand1 % operand2
ELSE NULL
END AS result
FROM calculator1;
2. To display student grade. ---id, name, score.
CREATE TABLE grades (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
student_name VARCHAR(50),
score INT
);
SELECT id, student_name, score,
CASE
WHEN score >= 90 THEN 'A'
WHEN score >= 80 THEN 'B'
WHEN score >= 70 THEN 'C'
WHEN score >= 60 THEN 'D'
ELSE 'F'
END AS letter_grade
FROM grades;
Subquery
Definition:
subquery is a query that is nested inside another query, and it is used to
retrieve data that will be used as part of a larger query.
The results of a subquery can be used as a comparison
Subqueries can be made using WHERE, FROM or SELECT clause.
The following are the rules to use subqueries:
Subqueries should always use in parentheses. ()
If the main query does not have multiple columns for subquery, then a
subquery can have only one column in the SELECT command.
We can use various comparison operators with the subquery, such as >, <, =,
A multiple-row operator is very useful when the subquery returns more than
one row.
We cannot use the ORDER BY clause in a subquery, although it can be used
inside the main query.
syntax
SELECT column_list (s) FROM table_name
WHERE column_name OPERATOR
(SELECT column_list (s) FROM table_name [WHERE])
Application
1. Filtering data: For example, you can use a subquery to retrieve all
customers who have made a purchase in the past month:
2. Calculating values: example, you can use a subquery to retrieve the
total revenue for each customer:
Step-1
Create Table
CREATE TABLE employees1 (
id INT(11) NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
department VARCHAR(50) NOT NULL,
salary INT(11) NOT NULL,
PRIMARY KEY (id)
);
Step-2
Insert the data
INSERT INTO employees1 (name, department, salary)
VALUES
('apt', 'Accounting', 50000),
('vikaas', 'Sales', 60000),
('laksita', 'Marketing', 55000);
1. How to find first Highest salary
2. Second highest salary
3. Third highest salary.
select max(salary) from employees1 where salary >(select min(salary) from
employees1);
select max(salary) from employees1 where salary <(select max(salary) from
employees1);
select min(salary) from employees1 where salary <(select max(salary) from
employees1);
Assignment question Task
Step-1
Create table
create table employee1(emp_id int,emp_name varchar(40),emp_age int,city
varchar(40),income int);
create table employee2(emp_id int,emp_name varchar(40),emp_age int,city
varchar(40),income int);
step-2
Insert the data
Step-3
1.SQL statement that returns the employee detail whose id matches in a
subquery:
2. write a query to display employee detail whose income is more than 3000
with the help of subquery:
3. find employee details with maximum income using a subquery.
4. student detail who does not belong to tirupathi City
Today Task
Subquery ---- ANY and ALL
Multiple Table
Date function
view
Any
1.The any operator return true if any of the query values meet the condition.
Example
For example, if you want to find all customers who have placed orders with
an amount greater than 100,
Select * from orders;
2.It compare to each value in the list.
3.The any operator are used with a where
Syntax
Select column from tablename1 where column operator any (select column
from table name2 where condition);
Step-1 Create the table
Step-2 insert the data
Step-3 Use "ANY" operator to select customers who have placed an order
with an amount greater than 100:
SELECT order_id,amount FROM orders
WHERE order_id= ANY (SELECT order_id FROM orders WHERE amount > 150);
ALL
1. The "ALL" operator is used to return true if all the subquery values
meet the condition
Example
if you want to find all customers who have placed orders with an
amount greater than or equal to 100,
2.It compare to each value in the list.
3.All operator return true if all of the query values meet the condition.
SELECT * FROM orders
WHERE customer_id = ALL (SELECT customer_id FROM orders WHERE amount
>= 50);
Another Example
Step-1
Create table
CREATE TABLE products
CREATE TABLE orders1
CREATE TABLE order_details
Step-2
Insert
Stpe-3
Select * from products;
Select * from orders1;
Select * from order_details;
Step-4
SELECT * FROM orders1
WHERE order_id = ANY (SELECT order_id FROM order_details WHERE
product_id = 1);
SELECT * FROM orders1
WHERE order_id = ALL (SELECT order_id FROM order_details WHERE
product_id IN (2, 3));
Test
Suppose you have a database with two tables: employees and salaries. The
employees table contains information about each employee, including their
name and department. The salaries table contains information about each
employee's salary, including the salary amount and the year it was earned.
Now, suppose you want to identify all employees who have earned a salary
greater than $100,000 in any year. You can use the "ANY" operator in a
subquery to find all salaries greater than $100,000,
Multiple query
Suppose you have a database with three tables: products, categories, and
sales. The products table contains information about each product, including
its name, price, and category. The categories table contains information
about each product category, including its name and ID. The sales table
contains information about each sale, including the product name, the
quantity sold, and the date of the sale.
Step-1
Create
CREATE TABLE orders2 (
id INT PRIMARY KEY AUTO_INCREMENT,
customer_id INT,
product_id INT,
quantity INT,
order_date DATE
);
CREATE TABLE customers (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50),
email VARCHAR(50)
);
CREATE TABLE products2 (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50),
price DECIMAL(10,2)
);
Step-2
INSERT INTO customers (name, email) VALUES ('apt btm',
'[email protected]'), ('kumar', '[email protected]');
INSERT INTO products2 (name, price) VALUES ('Product A', 100.00), ('Product
B', 200.00), ('Product C', 300.00);
Step-3
select * from customers;
select * from products2;
desc orders2;
INSERT INTO products (name, price) VALUES ('Product A', 100.00), ('Product
B', 200.00), ('Product C', 300.00);
INSERT INTO orders2 (customer_id, product_id, quantity, order_date)
VALUES
((SELECT id FROM customers WHERE name = 'aptbtm'), (SELECT id FROM
products2 WHERE name = 'Product A'), 5, '2022-01-01'),
((SELECT id FROM customers WHERE name = 'kumar'), (SELECT id FROM
products2 WHERE name = 'Product B'), 10, '2022-01-02');
TODAY TASK
DATE FUNCTION
how you can use aggregate function in multiple subqueries
how to use logical operators to check conditions in multiple queries:
The query is selecting all columns from the "orders3" table where the
customer_id is either 1 or 2, the total_amount is greater than 100, and the
status is either "shipped" or "delivered".
JOIN
View
Definition:
It allows you to create a named, reusable query that can be treated like a
table.
Views are useful for simplifying complex queries,
abstracting the underlying table structure,
Syntax
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Step-1
Create table
CREATE TABLE original_table (
id INT PRIMARY KEY,
name VARCHAR(50)
);
Step-2
Insert
INSERT INTO original_table (id, name) VALUES (1, 'John'), (2, 'Jane');
Step-3
Select * from original_table
Step-4
Create view
CREATE VIEW insertable_view AS
SELECT id, name
FROM original_table
WHERE id > 1;
Question
We want to create a view that includes the full names and salaries of
employees with a salary greater than $50,000.
Normalization:
Normalization is process of organizing the data in database to avoid
Data redundancy,
Insertion, update, deletion anomaly.
First Normal Form (1NF):
1.It should only have single(atomic) valued attributes.
2. value stored in a column should be of the same domain
3. All the column in a table should have unique names.
4. the order in which data is store no matter
Rollno Name subject
101 raj os
101 Raj cn
102 ram java
103 bob C,c++
Second Normal Form (2NF):
Table should be in 1 NF
There should not be any partial dependency.
Scoreid Studentid Subid Mark teacher
1 10 1 60 Raj
2 10 2 68 Ram
3 11 1 72 Raj
4 11 2 81 Ram
5 11 4 98 sam
It eliminates partial dependencies by moving them to separate tables.
Third Normal Form (3NF)
1. The table should be in 2nf
2. It should not contain transitive dependency.
EMPID EMPNAME EMP-ZIP EMPSTATE EMPCITY
222 ANIL 201010 UP NOIADA
333 VIJAY 022203 US BESTON
444 RAM 600007 US CHICAGO
555 RAJESH 462007 MP BHOPAL
Boyce-Codd Normal Form (BCNF)
Table should be in 3rd NF
There should not be reverse dependency.
STUDENTID SUBJECT PROFESSOR
101 JAVA RAJ
101 C++ RAM
102 JAVA KUMAR
103 C# LAXMAN
TCL
Commit
set autocommit=0;
INSERT INTO class VALUES(5, 'Rahul');
COMMIT;
Rollback
ROLLBACK statement is used to undo changes made within an ongoing
transaction
To roll back to a savepoint, you can use the ROLLBACK TO SAVEPOINT
Interview question
Theory
practical
SELECT * FROM orders3
WHERE (customer_id = 1 OR customer_id = 2)
AND total_amount > 100
AND (status = 'shipped' OR status = 'delivered');
Task
Join table 1 customer table-orders
1. Retrieve all customers and all orders, including those that do not have
matching records in the other table.--- full join ,
2. Retrieve all orders and the corresponding customer information, even
if there are no matching customer records. right join
3. Retrieve all customers and the number of orders they have placed,
even if they have not placed any orders.--- left join
4. Retrieve all orders and the corresponding customer information for
customers who have placed at least one order.---
1. What is MySQL? MySQL is a database management system for web
servers. It can grow with the website as it is highly
scalable. Most of the websites today are powered by
MySQL.
2. 2. What are some of the advantages Flexibility: MySQL runs on all operating
of using MySQL? systems
3. How can you interact with MySQL? using a command line
via a web interface
through a programming language
4. How do you remove a column from a ALTER TABLE classics DROP pages;
database?
5. How to add users in MySQL? CREATE USER ‘testuser’ IDENTIFIED BY ‘sample
password’;
6. What do DDL, DML, and DCL stand DDL-CREATE,ALTER,DROP,RENAME,TRUNCATE
for?
DML-SELECT,INSERT, UPDATE, DELETE.
DCL-GRANT, REVOKE.
TCL-COMMIT,ROLLBACK, SAVEPOINT.
7. What is a join in MySQL?
8. How can a user get the current SQL SELECT VERSION ();
version?
9. What is the difference between The primary key does not allow ‘NULL’, but the
primary key and unique key? unique key does.
While both are used to enforce the uniqueness of
the column defined,
10. What is the difference between the
DELETE TABLE and TRUNCATE TABLE
commands in MySQL?
11. Can you use MySQL with Linux Yes. The syntax for using MySQL with Linux
operating system? operating system is as follows:
etc/init.d/mysqlstart
What are the differences between a primary The primary key uniquely identifies a record,
key and a foreign key? whereas foreign key refers to the primary
key of another table.
The primary key can never accept a NULL
value but foreign key accepts a NULL value.
How can you filter the duplicate data while A DISTINCT keyword is used to filter the
retrieving records from the table? duplicate data from the table while
retrieving the records from a table.
What is the difference between NOW() and Both NOW() and CURRENT_DATE() are
CURRENT_DATE()? built-in MySQL methods. NOW() is used to
show the current date and time of the
server and CURRENT_DATE() is used to
show only the date of the server.
How can you change the name of any existing RENAME TABLE table_name TO new_name
table by using the SQL statement?
How can you retrieve a particular number of LIMIT clause is used with the SQL statement
records from a table? to retrieve a particular number of records
from a table.
How can you calculate the sum of any column SUM() function is used to calculate the sum
of a table? of any column.
How can you count the total number of COUNT() function is used to count the total
records of any table? number of records of any table.
What are the functions of commit and rollback Answer: Commit is a transaction command that
statements? executes when all the tasks of a transaction are
completed successfully. It will modify the database
permanently to confirm the transaction.
Syntax:
COMMIT;
Rollback is another transactional command that
executes when any of the transactional tasks
become unsuccessful and undoes all the changes
that are made by any transactional task to make the
transaction unsuccessful.
Syntax:
ROLLBACK;