0% found this document useful (0 votes)
6 views91 pages

MySQL Sessions

The document provides an overview of MySQL sessions, focusing on the creation and management of tables in a relational database. It explains the concepts of entities, attributes, and relationships, along with how to represent them in an ER diagram. Additionally, it includes practical examples of SQL commands for creating tables and querying data.

Uploaded by

Riya Yohannan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views91 pages

MySQL Sessions

The document provides an overview of MySQL sessions, focusing on the creation and management of tables in a relational database. It explains the concepts of entities, attributes, and relationships, along with how to represent them in an ER diagram. Additionally, it includes practical examples of SQL commands for creating tables and querying data.

Uploaded by

Riya Yohannan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 91

MySQL Sessions

Session1: Date 21st March 2023

MySQL is a database. We store data in the form of tables. Table is a collection of rows and
columns. RDBMS stands for relational database management system. Relation means table. All
data is stored in the tables. Before we create tables, we have to look at the ER diagram or we
have to prepare the ER diagram. ER diagram stands for Entity Relationship diagram. Entity
means anything that you see/feel is an entity.

Entity can be

1. Concrete: example Book

2. Abstract: example Saving Account

In ER diagram, entities are represented using a rectangle.

1. Single sided rectangle

2. Double sided rectangle

Relationship means how they are connected

Example: We have two entities: student and Course

Relationship is represented using a diamond.

Types of relationships

1. One to One

2. One to Many

3. Many to One

4. Many to Many
Student M Enro M Course
lls

Loan has EMI

Loan Has EMI

Here, EMI is a weak entity. It cannot exist without a loan.

Loan is a strong entity.

Each entity has got an attribute

Attribute describes the entity

Example : Student has attribute student_id, first_name, last_name, phone etc

Types of attributes

1. Simple : Example rollno , contains only one value. Is represented using Ellipse

Roll No

2. Composite :Example Name contains first name, middle name and last name

Middle
Name
First Name
Last Name

Name

3. Derived: It depends on another attribute. Example age depends on date of birth

Age

4. Multi-valued attribute: Will take multiple values. Example : phone number


Phone Number

 Program is a strong entity, with the identifier program_id as the primary key used to
distinguish between programs.
 Each student must be enrolled in a program, so the Student entity participates
totally in the many-to-one EnrollsIn relationship with Program. A program can
exist without having any enrolled students, so it participates partially in this
relationship.
 A Course has meaning only in the context of a Program, so it’s a weak entity, with
course_id as a weak key. This means that a Course is uniquely identified using its
course_id and the program_id of its owning program.
 As a weak entity, Course participates totally in the many-to-one identifying relationship
with its owning Program. This relationship has Year and Semester attributes
that identify its sequence position.
 Student and Course are related through the many-to-many Attempts relationships;
a course can exist without a student, and a student can be enrolled without attempting any
courses, so the participation is not total.
 When a student attempts a course, there are attributes to capture the Year and
Semester, and the Mark and Grade.

How tables are created using ER?

1. One to One: Create two separate tables.

2. One to Many: Primary key of One in table of Many

3. Many to One: Primary key of One in table of Many

4. Many to Many: Create a third table of the relationship and put primary keys of both tables in
this third table.

Student M Enro M Course


lls

Here we will have the “Enrolls” table with primary keys of both entities like student_id and
course_id.

Session2
Date 23rd March 2023

mysql> use test;

mysql> show tables;


+----------------+
| Tables_in_test |
+----------------+
| gm_employee |
+----------------+
1 row in set (0.00 sec)

mysql> create table gm_department


-> (
-> department_id integer,
-> department_name varchar(20)
-> );
Query OK, 0 rows affected (0.27 sec)

mysql> show tables;


+----------------+
| Tables_in_test |
+----------------+
| gm_department |
| gm_employee |
+----------------+
2 rows in set (0.00 sec)

mysql> show columns from gm_employee;


+-------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| employee_id | int(11) | YES | | NULL | |
| first_name | varchar(20) | YES | | NULL | |
| last_name | varchar(20) | YES | | NULL | |
| salary | int(11) | YES | | NULL | |
+-------------+-------------+------+-----+---------+-------+
4 rows in set (0.08 sec)

mysql> create table gm_location


-> (location_id integer(2),
-> location_name varchar(20)
-> );
Query OK, 0 rows affected (0.23 sec)

mysql> show columns from gm_location;


+---------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------+-------------+------+-----+---------+-------+
| location_id | int(2) | YES | | NULL | |
| location_name | varchar(20) | YES | | NULL | |
+---------------+-------------+------+-----+---------+-------+
2 rows in set (0.04 sec)

mysql> desc gm_location;


+---------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------+-------------+------+-----+---------+-------+
| location_id | int(2) | YES | | NULL | |
| location_name | varchar(20) | YES | | NULL | |
+---------------+-------------+------+-----+---------+-------+
2 rows in set (0.04 sec)

mysql> create table gm_region


-> (region_id integer default 10,
-> region_name varchar(20)
-> );
Query OK, 0 rows affected (0.25 sec)

mysql> desc gm_region;


+-------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| region_id | int(11) | YES | | 10 | |
| region_name | varchar(20) | YES | | NULL | |
+-------------+-------------+------+-----+---------+-------+
2 rows in set (0.06 sec)

mysql> insert into gm_region values(200,'Pune');


Query OK, 1 row affected (0.04 sec)

mysql> select * from gm_region;


+-----------+-------------+
| region_id | region_name |
+-----------+-------------+
| 200 | Pune |
+-----------+-------------+
1 row in set (0.01 sec)

mysql> insert into gm_region values(default,'Mumbai');


Query OK, 1 row affected (0.04 sec)

mysql> select * from gm_region;


+-----------+-------------+
| region_id | region_name |
+-----------+-------------+
| 200 | Pune |
| 10 | Mumbai |
+-----------+-------------+
2 rows in set (0.00 sec)

mysql> insert into gm_region(region_id) values(400);


Query OK, 1 row affected (0.03 sec)

mysql> select * from gm_region;


+-----------+-------------+
| region_id | region_name |
+-----------+-------------+
| 200 | Pune |
| 10 | Mumbai |
| 400 | NULL |
+-----------+-------------+
3 rows in set (0.00 sec)
mysql> insert into gm_region(region_name) values('Hyderabad');
Query OK, 1 row affected (0.03 sec)

mysql> select * from gm_region;


+-----------+-------------+
| region_id | region_name |
+-----------+-------------+
| 200 | Pune |
| 10 | Mumbai |
| 400 | NULL |
| 10 | Hyderabad |
+-----------+-------------+
4 rows in set (0.00 sec)

mysql> insert into gm_region(region_id,region_name) values(500,'Chennai');


Query OK, 1 row affected (0.04 sec)

mysql> select region_name


-> from gm_regions;
ERROR 1146 (42S02): Table 'test.gm_regions' doesn't exist
mysql> select region_name
-> from gm_region;
+-------------+
| region_name |
+-------------+
| Pune |
| Mumbai |
| NULL |
| Hyderabad |
| Chennai |
+-------------+
5 rows in set (0.00 sec)

mysql> desc gm_region;


+-------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| region_id | int(11) | YES | | 10 | |
| region_name | varchar(20) | YES | | NULL | |
+-------------+-------------+------+-----+---------+-------+
2 rows in set (0.05 sec)

mysql> select *
-> from gm_region
-> where region_id = 200;
+-----------+-------------+
| region_id | region_name |
+-----------+-------------+
| 200 | Pune |
+-----------+-------------+
1 row in set (0.00 sec)

mysql> select *
-> from gm_region
-> where region_id = 2000;
Empty set (0.00 sec)

mysql> select *
-> from gm_region
-> where region_name='Pune';
+-----------+-------------+
| region_id | region_name |
+-----------+-------------+
| 200 | Pune |
+-----------+-------------+
1 row in set (0.00 sec)

mysql> select *
-> from gm_region
-> where region_id >200;
+-----------+-------------+
| region_id | region_name |
+-----------+-------------+
| 400 | NULL |
| 500 | Chennai |
+-----------+-------------+
2 rows in set (0.00 sec)

mysql> select *
-> from gm_region
-> where region_id < 200;
+-----------+-------------+
| region_id | region_name |
+-----------+-------------+
| 10 | Mumbai |
| 10 | Hyderabad |
+-----------+-------------+
2 rows in set (0.00 sec)

mysql> select region_name


-> from gm_region
-> where region_id < 200;
+-------------+
| region_name |
+-------------+
| Mumbai |
| Hyderabad |
+-------------+
2 rows in set (0.00 sec)

mysql> select *
-> from gm_region
-> where region_id between 200 and 500;
+-----------+-------------+
| region_id | region_name |
+-----------+-------------+
| 200 | Pune |
| 400 | NULL |
| 500 | Chennai |
+-----------+-------------+
3 rows in set (0.00 sec)

mysql> insert into gm_region(region_id,region_name) values(501,'Calcutta');


Query OK, 1 row affected (0.03 sec)

mysql> insert into gm_region(region_id,region_name) values(501,'Coimbatore');


Query OK, 1 row affected (0.04 sec)

mysql> insert into gm_region(region_id,region_name) values(502,'Coimbatore');


Query OK, 1 row affected (0.03 sec)

mysql> select *
-> from gm_region
-> where region_name like 'P%';
+-----------+-------------+
| region_id | region_name |
+-----------+-------------+
| 200 | Pune |
+-----------+-------------+
1 row in set (0.00 sec)

mysql> select *
-> from gm_region
-> where region_name like 'C%';
+-----------+-------------+
| region_id | region_name |
+-----------+-------------+
| 500 | Chennai |
| 501 | Calcutta |
| 501 | Coimbatore |
| 502 | Coimbatore |
+-----------+-------------+
4 rows in set (0.00 sec)

mysql> select *
-> from gm_region
-> where region_name like 'C%a';
+-----------+-------------+
| region_id | region_name |
+-----------+-------------+
| 501 | Calcutta |
+-----------+-------------+
1 row in set (0.00 sec)

mysql> select *
-> from gm_region
-> where region_name like '%e';
+-----------+-------------+
| region_id | region_name |
+-----------+-------------+
| 200 | Pune |
| 501 | Coimbatore |
| 502 | Coimbatore |
+-----------+-------------+
3 rows in set (0.00 sec)

mysql> select *
-> from gm_region
-> where region_name like '%E';
+-----------+-------------+
| region_id | region_name |
+-----------+-------------+
| 200 | Pune |
| 501 | Coimbatore |
| 502 | Coimbatore |
+-----------+-------------+
3 rows in set (0.00 sec)

mysql> select *
-> from gm_region
-> where region_name in ('Pune','Chennai');
+-----------+-------------+
| region_id | region_name |
+-----------+-------------+
| 200 | Pune |
| 500 | Chennai |
+-----------+-------------+
2 rows in set (0.00 sec)

mysql> select *
-> from gm_region
-> where region_name like 'P___';
+-----------+-------------+
| region_id | region_name |
+-----------+-------------+
| 200 | Pune |
+-----------+-------------+
1 row in set (0.00 sec)

mysql> select *
-> from gm_region
-> where region_name like 'P__e';
+-----------+-------------+
| region_id | region_name |
+-----------+-------------+
| 200 | Pune |
+-----------+-------------+
1 row in set (0.00 sec)

mysql> select *
-> from gm_region
-> where region_name like 'P%e';
+-----------+-------------+
| region_id | region_name |
+-----------+-------------+
| 200 | Pune |
+-----------+-------------+
1 row in set (0.00 sec)

mysql> select *
-> from gm_region
-> where region_name like 'P%n%';
+-----------+-------------+
| region_id | region_name |
+-----------+-------------+
| 200 | Pune |
+-----------+-------------+
1 row in set (0.00 sec)
mysql> insert into gm_region(region_id,region_name) values(503,'Punawale');
Query OK, 1 row affected (0.04 sec)

mysql> commit;
Query OK, 0 rows affected (0.00 sec)

mysql> select *
-> from gm_region
-> where region_name like 'P%n%';
+-----------+-------------+
| region_id | region_name |
+-----------+-------------+
| 200 | Pune |
| 503 | Punawale |
+-----------+-------------+
2 rows in set (0.00 sec)

mysql> select *
-> from gm_region
-> where region_id like '5%';
+-----------+-------------+
| region_id | region_name |
+-----------+-------------+
| 500 | Chennai |
| 501 | Calcutta |
| 501 | Coimbatore |
| 502 | Coimbatore |
| 503 | Punawale |
+-----------+-------------+
5 rows in set (0.00 sec)

mysql> select *
-> from gm_region
-> where region_id = 200 and region_name='Pune';
+-----------+-------------+
| region_id | region_name |
+-----------+-------------+
| 200 | Pune |
+-----------+-------------+
1 row in set (0.00 sec)

mysql> select *
-> from gm_region
-> where region_id > 200 and region_name like 'C%';
+-----------+-------------+
| region_id | region_name |
+-----------+-------------+
| 500 | Chennai |
| 501 | Calcutta |
| 501 | Coimbatore |
| 502 | Coimbatore |
+-----------+-------------+
4 rows in set (0.00 sec)

mysql> select *
-> from gm_region
-> where region_id > 200 and region_name like 'C%';
+-----------+-------------+
| region_id | region_name |
+-----------+-------------+
| 500 | Chennai |
| 501 | Calcutta |
| 501 | Coimbatore |
| 502 | Coimbatore |
+-----------+-------------+
4 rows in set (0.00 sec)

mysql> select *
-> from gm_region
-> where region_id > 200 or region_name like 'C%';
+-----------+-------------+
| region_id | region_name |
+-----------+-------------+
| 400 | NULL |
| 500 | Chennai |
| 501 | Calcutta |
| 501 | Coimbatore |
| 502 | Coimbatore |
| 503 | Punawale |
+-----------+-------------+
6 rows in set (0.00 sec)

mysql> select *
-> from gm_region
-> where not(region_id > 200);
+-----------+-------------+
| region_id | region_name |
+-----------+-------------+
| 200 | Pune |
| 10 | Mumbai |
| 10 | Hyderabad |
+-----------+-------------+
3 rows in set (0.00 sec)

mysql> select *
-> from gm_region
-> where not(region_id <= 200);
+-----------+-------------+
| region_id | region_name |
+-----------+-------------+
| 400 | NULL |
| 500 | Chennai |
| 501 | Calcutta |
| 501 | Coimbatore |
| 502 | Coimbatore |
| 503 | Punawale |
+-----------+-------------+
6 rows in set (0.00 sec)

mysql> select *
-> from gm_region
-> where not(region_id >= 200);
+-----------+-------------+
| region_id | region_name |
+-----------+-------------+
| 10 | Mumbai |
| 10 | Hyderabad |
+-----------+-------------+
2 rows in set (0.00 sec)

mysql> select *
-> from gm_region
-> where region_id >= 200;
+-----------+-------------+
| region_id | region_name |
+-----------+-------------+
| 200 | Pune |
| 400 | NULL |
| 500 | Chennai |
| 501 | Calcutta |
| 501 | Coimbatore |
| 502 | Coimbatore |
| 503 | Punawale |
+-----------+-------------+
7 rows in set (0.00 sec)

Session 4 Date : 6th April 2023


Setting environment for using XAMPP for Windows.
TrainingLab@TRAININGLAB-PC d:\xampp
# mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.6.21 MySQL Community Server (GPL)

Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its


affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> create table fruits


-> (
-> fruit_name enum('Apple','Orange','Pear')
-> );
ERROR 1046 (3D000): No database selected
mysql> use test;
Database changed
mysql> create table fruits
-> (
-> fruit_name enum('Apple','Orange','Pear')
-> );
Query OK, 0 rows affected (0.26 sec)

mysql> insert into fruits values('Apple');


Query OK, 1 row affected (0.03 sec)

mysql> insert into fruits values('Banana');


Query OK, 1 row affected, 1 warning (0.03 sec)

mysql> show marnings


-> ;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near 'marni
ngs' at line 1
mysql> show marning;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near 'marni
ng' at line 1
mysql> show warnings;
+-------+------+----------------------------------------------------------------
--------------------------------------------------------------------------------
-----------+
| Level | Code | Message

|
+-------+------+----------------------------------------------------------------
--------------------------------------------------------------------------------
-----------+
| Error | 1064 | You have an error in your SQL syntax; check the manual that cor
responds to your MySQL server version for the right syntax to use near 'marning'
at line 1 |
+-------+------+----------------------------------------------------------------
--------------------------------------------------------------------------------
-----------+
1 row in set (0.00 sec)

mysql> insert into fruits values('Pear');


Query OK, 1 row affected (0.03 sec)

mysql> select *
-> from fruits;
+------------+
| fruit_name |
+------------+
| Apple |
| |
| Pear |
+------------+
3 rows in set (0.00 sec)

mysql> create table fruits1


-> (
-> fruit_name set('Apple','Orange','Pear')
-> );
Query OK, 0 rows affected (0.22 sec)

mysql> insert into fruits1 values('Orange,Pear');


Query OK, 1 row affected (0.02 sec)

mysql> insert into fruits values('Orange,Pear');


Query OK, 1 row affected, 1 warning (0.03 sec)

mysql> select * from fruits;


+------------+
| fruit_name |
+------------+
| Apple |
| |
| Pear |
| |
+------------+
4 rows in set (0.00 sec)

mysql> select * from fruits1;


+-------------+
| fruit_name |
+-------------+
| Orange,Pear |
+-------------+
1 row in set (0.00 sec)

mysql> insert into fruits1 values('Peach');


Query OK, 1 row affected, 1 warning (0.02 sec)

mysql> select * from fruits1;


+-------------+
| fruit_name |
+-------------+
| Orange,Pear |
| |
+-------------+
2 rows in set (0.00 sec)

mysql> insert into fruits values('Peach');


Query OK, 1 row affected, 1 warning (0.03 sec)

mysql> select * from fruits;


+------------+
| fruit_name |
+------------+
| Apple |
| |
| Pear |
| |
| |
+------------+
5 rows in set (0.00 sec)

mysql> create table Books


-> (book_id smallint,
-> book_name varchar(10),
-> primary key(book_id)
-> );
Query OK, 0 rows affected (0.32 sec)

mysql> insert into Books values(1.'C');


ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near ''C')'
at line 1
mysql> insert into Books values(1,'C');
Query OK, 1 row affected (0.03 sec)

mysql> insert into Books values(1,'C');


ERROR 1062 (23000): Duplicate entry '1' for key 'PRIMARY'
mysql> insert into Books values(Null,'C');
ERROR 1048 (23000): Column 'book_id' cannot be null
mysql> create table Books1
-> (book_id smallint,
-> book_name varchar(10),
-> primary key(book_id,book_name)
-> );
Query OK, 0 rows affected (0.30 sec)

mysql> insert into Books2 values(1,'C');


ERROR 1146 (42S02): Table 'test.books2' doesn't exist
mysql> insert into Books1 values(1,'C');
Query OK, 1 row affected (0.04 sec)

mysql> insert into Books1 values(1,'C++');


Query OK, 1 row affected (0.03 sec)

mysql> insert into Books1 values(2,'C++');


Query OK, 1 row affected (0.03 sec)

mysql> insert into Books1 values(2,'C');


Query OK, 1 row affected (0.03 sec)

mysql> select * from Books;


+---------+-----------+
| book_id | book_name |
+---------+-----------+
| 1|C |
+---------+-----------+
1 row in set (0.00 sec)

mysql> select * from Books1;


+---------+-----------+
| book_id | book_name |
+---------+-----------+
| 1|C |
| 1 | C++ |
| 2|C |
| 2 | C++ |
+---------+-----------+
4 rows in set (0.00 sec)

mysql> insert into Books1 values(2,'C');


ERROR 1062 (23000): Duplicate entry '2-C' for key 'PRIMARY'
mysql> insert into Books1 values(Null,Null);
ERROR 1048 (23000): Column 'book_id' cannot be null

mysql> CREATE TABLE customer (


cust_id INT(4) NOT NULL DEFAULT 0,
firstname CHAR(50),
secondname CHAR(50),
surname CHAR(50),
PRIMARY KEY (cust_id),
KEY names (firstname, secondname, surname));
You can see that we’ve added a primary key index on the cust_id identifier column,
and we’ve also added another index—called names—that includes the firstname,
secondname, and surname columns in this order.

mysql> select * from customer where firstname='Shravan';


Empty set (0.00 sec)

Date : 11th April 2023

mysql> use test;


Database changed
mysql> CREATE TABLE artist (
-> artist_id SMALLINT(5) NOT NULL AUTO_INCREMENT,
-> artist_name CHAR(128) DEFAULT NULL,
-> PRIMARY KEY (artist_id)
-> );
Query OK, 0 rows affected (0.22 sec)

mysql> INSERT INTO artist VALUES (NULL, "The Shamen");


Query OK, 1 row affected (0.02 sec)

mysql> INSERT INTO artist VALUES (NULL, "Probot");


Query OK, 1 row affected (0.02 sec)
mysql> INSERT INTO artist VALUES (NULL, "The Cult");
Query OK, 1 row affected (0.03 sec)

mysql> select * from artist;


+-----------+-------------+
| artist_id | artist_name |
+-----------+-------------+
| 1 | The Shamen |
| 2 | Probot |
| 3 | The Cult |
+-----------+-------------+
3 rows in set (0.00 sec)
mysql> CREATE TABLE album (
-> artist_id INT(5) NOT NULL AUTO_INCREMENT,
-> album_id INT(4) NOT NULL ,
-> album_name CHAR(128) DEFAULT NULL,
-> PRIMARY KEY (artist_id, album_id)
-> );
Query OK, 0 rows affected (0.22 sec)
mysql> CREATE TABLE album2 (
->
-> album_id INT(4) NOT NULL AUTO_INCREMENT,
-> artist_id INT(5) NOT NULL ,
-> album_name CHAR(128) DEFAULT NULL,
-> PRIMARY KEY (album_id,artist_id)
-> );
Query OK, 0 rows affected (0.23 sec)
mysql> INSERT INTO album VALUES (1, 10, "Boss Drum");
Query OK, 1 row affected (0.02 sec)

mysql> INSERT INTO album VALUES (3, 10, "Electric");


Query OK, 1 row affected (0.02 sec)

mysql> select * from album;


+-----------+----------+------------+
| artist_id | album_id | album_name |
+-----------+----------+------------+
| 1| 10 | Boss Drum |
| 3| 10 | Electric |
+-----------+----------+------------+
2 rows in set (0.00 sec)

mysql> desc album


-> ;
+------------+-----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+-----------+------+-----+---------+----------------+
| artist_id | int(5) | NO | PRI | NULL | auto_increment |
| album_id | int(4) | NO | PRI | NULL | |
| album_name | char(128) | YES | | NULL | |
+------------+-----------+------+-----+---------+----------------+
3 rows in set (0.06 sec)

mysql> desc album;


+------------+-----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+-----------+------+-----+---------+----------------+
| artist_id | int(5) | NO | PRI | NULL | auto_increment |
| album_id | int(4) | NO | PRI | NULL | |
| album_name | char(128) | YES | | NULL | |
+------------+-----------+------+-----+---------+----------------+
3 rows in set (0.06 sec)

mysql> alter table album


-> change album_name album_name2 char(200);
Query OK, 0 rows affected (0.54 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> desc album;


+-------------+-----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-----------+------+-----+---------+----------------+
| artist_id | int(5) | NO | PRI | NULL | auto_increment |
| album_id | int(4) | NO | PRI | NULL | |
| album_name2 | char(200) | YES | | NULL | |
+-------------+-----------+------+-----+---------+----------------+
3 rows in set (0.06 sec)

mysql> alter table album


-> change album_id album_id2 char(200);
Query OK, 0 rows affected (0.55 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> INSERT INTO album VALUES (3, 10, "Electric");


Query OK, 1 row affected (0.02 sec)

mysql> select * from albuml


-> ;
ERROR 1146 (42S02): Table 'test.albuml' doesn't exist
mysql> select * from album;
+-----------+-----------+-------------+
| artist_id | album_id2 | album_name2 |
+-----------+-----------+-------------+
| 3 | 10 | Electric |
+-----------+-----------+-------------+
1 row in set (0.00 sec)

mysql> alter table album


-> change album_id2 album_id3 int(5);
Query OK, 1 row affected (0.61 sec)
Records: 1 Duplicates: 0 Warnings: 0

mysql> desc album;


+-------------+-----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-----------+------+-----+---------+----------------+
| artist_id | int(5) | NO | PRI | NULL | auto_increment |
| album_id3 | int(5) | NO | PRI | 0 | |
| album_name2 | char(200) | YES | | NULL | |
+-------------+-----------+------+-----+---------+----------------+
3 rows in set (0.06 sec)

mysql> alter table album


-> change album_name2 album_name3 int(5);
Query OK, 1 row affected, 1 warning (1.49 sec)
Records: 1 Duplicates: 0 Warnings: 1

mysql> select * from album;


+-----------+-----------+-------------+
| artist_id | album_id3 | album_name3 |
+-----------+-----------+-------------+
| 3| 10 | 0|
+-----------+-----------+-------------+
1 row in set (0.00 sec)

mysql> ALTER TABLE artist ADD formed YEAR;


Query OK, 0 rows affected (0.47 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> desc artist;


+-------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+----------------+
| artist_id | smallint(5) | NO | PRI | NULL | auto_increment |
| artist_name | char(128) | YES | | NULL | |
| formed | year(4) | YES | | NULL | |
+-------------+-------------+------+-----+---------+----------------+
3 rows in set (0.04 sec)

mysql> ALTER TABLE artist ADD artist_title char(10) FIRST;


Query OK, 0 rows affected (0.52 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> desc artist;


+--------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+----------------+
| artist_title | char(10) | YES | | NULL | |
| artist_id | smallint(5) | NO | PRI | NULL | auto_increment |
| artist_name | char(128) | YES | | NULL | |
| formed | year(4) | YES | | NULL | |
+--------------+-------------+------+-----+---------+----------------+
4 rows in set (0.05 sec)

mysql> ALTER TABLE artist ADD formed2 YEAR AFTER artist_id;


Query OK, 0 rows affected (0.41 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> desc artist;


+--------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+----------------+
| artist_title | char(10) | YES | | NULL | |
| artist_id | smallint(5) | NO | PRI | NULL | auto_increment |
| formed2 | year(4) | YES | | NULL | |
| artist_name | char(128) | YES | | NULL | |
| formed | year(4) | YES | | NULL | |
+--------------+-------------+------+-----+---------+----------------+
5 rows in set (0.05 sec)

mysql> ALTER TABLE artist DROP formed;


Query OK, 0 rows affected (0.37 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> desc artist;


+--------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+----------------+
| artist_title | char(10) | YES | | NULL | |
| artist_id | smallint(5) | NO | PRI | NULL | auto_increment |
| formed2 | year(4) | YES | | NULL | |
| artist_name | char(128) | YES | | NULL | |
+--------------+-------------+------+-----+---------+----------------+
4 rows in set (0.04 sec)

mysql> ALTER TABLE artist ADD formed YEAR, MODIFY artist_name char(253);
Query OK, 3 rows affected (0.68 sec)
Records: 3 Duplicates: 0 Warnings: 0

mysql> desc artist;


+--------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+----------------+
| artist_title | char(10) | YES | | NULL | |
| artist_id | smallint(5) | NO | PRI | NULL | auto_increment |
| formed2 | year(4) | YES | | NULL | |
| artist_name | char(253) | YES | | NULL | |
| formed | year(4) | YES | | NULL | |
+--------------+-------------+------+-----+---------+----------------+
5 rows in set (0.06 sec)

mysql> ALTER TABLE artist ADD INDEX by_name (artist_name);


Query OK, 0 rows affected (0.31 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> desc artist;
+--------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+----------------+
| artist_title | char(10) | YES | | NULL | |
| artist_id | smallint(5) | NO | PRI | NULL | auto_increment |
| formed2 | year(4) | YES | | NULL | |
| artist_name | char(253) | YES | MUL | NULL | |
| formed | year(4) | YES | | NULL | |
+--------------+-------------+------+-----+---------+----------------+
5 rows in set (0.06 sec)

mysql> CREATE TABLE artist3 (


-> artist_id SMALLINT(5) NOT NULL AUTO_INCREMENT,
-> artist_name CHAR(128) DEFAULT NULL,
-> PRIMARY KEY (artist_id)
-> );
Query OK, 0 rows affected (0.21 sec)

mysql> desc artist3;


+-------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+----------------+
| artist_id | smallint(5) | NO | PRI | NULL | auto_increment |
| artist_name | char(128) | YES | | NULL | |
+-------------+-------------+------+-----+---------+----------------+
2 rows in set (0.06 sec)

mysql> ALTER TABLE artist DROP INDEX by_name;


Query OK, 0 rows affected (0.18 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> desc artist;


+--------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+----------------+
| artist_title | char(10) | YES | | NULL | |
| artist_id | smallint(5) | NO | PRI | NULL | auto_increment |
| formed2 | year(4) | YES | | NULL | |
| artist_name | char(253) | YES | | NULL | |
| formed | year(4) | YES | | NULL | |
+--------------+-------------+------+-----+---------+----------------+
5 rows in set (0.06 sec)

mysql> desc artist3;


+-------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+----------------+
| artist_id | smallint(5) | NO | PRI | NULL | auto_increment |
| artist_name | char(128) | YES | | NULL | |
+-------------+-------------+------+-----+---------+----------------+
2 rows in set (0.05 sec)

mysql> ALTER TABLE artist DROP artist_id;


Query OK, 3 rows affected (0.58 sec)
Records: 3 Duplicates: 0 Warnings: 0

Query OK, 0 rows affected (0.23 sec)

mysql> INSERT INTO album VALUES (1, NULL, "Boss Drum");


ERROR 1048 (23000): Column 'album_id' cannot be null
mysql> INSERT INTO album VALUES (1, 10, "Boss Drum");
Query OK, 1 row affected (0.02 sec)

mysql> INSERT INTO album VALUES (3, 10, "Electric");


Query OK, 1 row affected (0.02 sec)

mysql> select * from album;


+-----------+----------+------------+
| artist_id | album_id | album_name |
+-----------+----------+------------+
| 1| 10 | Boss Drum |
| 3| 10 | Electric |
+-----------+----------+------------+
2 rows in set (0.00 sec)

mysql> desc album


-> ;
+------------+-----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+-----------+------+-----+---------+----------------+
| artist_id | int(5) | NO | PRI | NULL | auto_increment |
| album_id | int(4) | NO | PRI | NULL | |
| album_name | char(128) | YES | | NULL | |
+------------+-----------+------+-----+---------+----------------+
3 rows in set (0.06 sec)

mysql> truncate table album;


Query OK, 0 rows affected (0.27 sec)

mysql> desc album;


+------------+-----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+-----------+------+-----+---------+----------------+
| artist_id | int(5) | NO | PRI | NULL | auto_increment |
| album_id | int(4) | NO | PRI | NULL | |
| album_name | char(128) | YES | | NULL | |
+------------+-----------+------+-----+---------+----------------+
3 rows in set (0.06 sec)

mysql> alter table album


-> change album_name album_name2 char(200);
Query OK, 0 rows affected (0.54 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> desc album;


+-------------+-----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-----------+------+-----+---------+----------------+
| artist_id | int(5) | NO | PRI | NULL | auto_increment |
| album_id | int(4) | NO | PRI | NULL | |
| album_name2 | char(200) | YES | | NULL | |
+-------------+-----------+------+-----+---------+----------------+
3 rows in set (0.06 sec)
mysql> alter table album
-> change album_id album_id2 char(200);
Query OK, 0 rows affected (0.55 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> INSERT INTO album VALUES (3, 10, "Electric");


Query OK, 1 row affected (0.02 sec)

mysql> select * from albuml


-> ;
ERROR 1146 (42S02): Table 'test.albuml' doesn't exist
mysql> select * from album;
+-----------+-----------+-------------+
| artist_id | album_id2 | album_name2 |
+-----------+-----------+-------------+
| 3 | 10 | Electric |
+-----------+-----------+-------------+
1 row in set (0.00 sec)

mysql> alter table album


-> change album_id2 album_id3 int(5);
Query OK, 1 row affected (0.61 sec)
Records: 1 Duplicates: 0 Warnings: 0

mysql> desc album;


+-------------+-----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-----------+------+-----+---------+----------------+
| artist_id | int(5) | NO | PRI | NULL | auto_increment |
| album_id3 | int(5) | NO | PRI | 0 | |
| album_name2 | char(200) | YES | | NULL | |
+-------------+-----------+------+-----+---------+----------------+
3 rows in set (0.06 sec)

mysql> alter table album


-> change album_name2 album_name3 int(5);
Query OK, 1 row affected, 1 warning (1.49 sec)
Records: 1 Duplicates: 0 Warnings: 1

mysql> select * from album;


+-----------+-----------+-------------+
| artist_id | album_id3 | album_name3 |
+-----------+-----------+-------------+
| 3| 10 | 0|
+-----------+-----------+-------------+
1 row in set (0.00 sec)
mysql> ALTER TABLE artist ADD formed YEAR;
Query OK, 0 rows affected (0.47 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> desc artist;


+-------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+----------------+
| artist_id | smallint(5) | NO | PRI | NULL | auto_increment |
| artist_name | char(128) | YES | | NULL | |
| formed | year(4) | YES | | NULL | |
+-------------+-------------+------+-----+---------+----------------+
3 rows in set (0.04 sec)

mysql> ALTER TABLE artist ADD artist_title char(10) FIRST;


Query OK, 0 rows affected (0.52 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> desc artist;


+--------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+----------------+
| artist_title | char(10) | YES | | NULL | |
| artist_id | smallint(5) | NO | PRI | NULL | auto_increment |
| artist_name | char(128) | YES | | NULL | |
| formed | year(4) | YES | | NULL | |
+--------------+-------------+------+-----+---------+----------------+
4 rows in set (0.05 sec)

mysql> ALTER TABLE artist ADD formed2 YEAR AFTER artist_id;


Query OK, 0 rows affected (0.41 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> desc artist;


+--------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+----------------+
| artist_title | char(10) | YES | | NULL | |
| artist_id | smallint(5) | NO | PRI | NULL | auto_increment |
| formed2 | year(4) | YES | | NULL | |
| artist_name | char(128) | YES | | NULL | |
| formed | year(4) | YES | | NULL | |
+--------------+-------------+------+-----+---------+----------------+
5 rows in set (0.05 sec)
mysql> ALTER TABLE artist DROP formed;
Query OK, 0 rows affected (0.37 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> desc artist;


+--------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+----------------+
| artist_title | char(10) | YES | | NULL | |
| artist_id | smallint(5) | NO | PRI | NULL | auto_increment |
| formed2 | year(4) | YES | | NULL | |
| artist_name | char(128) | YES | | NULL | |
+--------------+-------------+------+-----+---------+----------------+
4 rows in set (0.04 sec)

mysql> ALTER TABLE artist ADD formed YEAR, MODIFY artist_name char(256);
ERROR 1074 (42000): Column length too big for column 'artist_name' (max = 255);
use BLOB or TEXT instead
mysql> ALTER TABLE artist ADD formed YEAR, MODIFY artist_name char(253);
Query OK, 3 rows affected (0.68 sec)
Records: 3 Duplicates: 0 Warnings: 0

mysql> desc artist;


+--------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+----------------+
| artist_title | char(10) | YES | | NULL | |
| artist_id | smallint(5) | NO | PRI | NULL | auto_increment |
| formed2 | year(4) | YES | | NULL | |
| artist_name | char(253) | YES | | NULL | |
| formed | year(4) | YES | | NULL | |
+--------------+-------------+------+-----+---------+----------------+
5 rows in set (0.06 sec)

mysql> ALTER TABLE artist ADD INDEX by_name (artist_name);


Query OK, 0 rows affected (0.31 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> ALTER TABLE artist ADD PRIMARY KEY (artist_id);


ERROR 1068 (42000): Multiple primary key defined
mysql> ALTER TABLE artist ADD PRIMARY KEY (formed);
ERROR 1068 (42000): Multiple primary key defined
mysql> ALTER TABLE artist DROP PRIMARY KEY;
ERROR 1075 (42000): Incorrect table definition; there can be only one auto colum
n and it must be defined as a key
mysql> desc artist;
+--------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+----------------+
| artist_title | char(10) | YES | | NULL | |
| artist_id | smallint(5) | NO | PRI | NULL | auto_increment |
| formed2 | year(4) | YES | | NULL | |
| artist_name | char(253) | YES | MUL | NULL | |
| formed | year(4) | YES | | NULL | |
+--------------+-------------+------+-----+---------+----------------+
5 rows in set (0.06 sec)

mysql> CREATE TABLE artist3 (


-> artist_id SMALLINT(5) NOT NULL AUTO_INCREMENT,
-> artist_name CHAR(128) DEFAULT NULL,
-> PRIMARY KEY (artist_id)
-> );
Query OK, 0 rows affected (0.21 sec)

mysql> ALTER TABLE artist3 DROP PRIMARY KEY;


ERROR 1075 (42000): Incorrect table definition; there can be only one auto colum
n and it must be defined as a key
mysql> desc artist3;
+-------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+----------------+
| artist_id | smallint(5) | NO | PRI | NULL | auto_increment |
| artist_name | char(128) | YES | | NULL | |
+-------------+-------------+------+-----+---------+----------------+
2 rows in set (0.06 sec)

mysql> ALTER TABLE artist DROP INDEX by_name;


Query OK, 0 rows affected (0.18 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> ALTER TABLE artist DROP PRIMARY KEY;


ERROR 1075 (42000): Incorrect table definition; there can be only one auto colum
n and it must be defined as a key
mysql> ALTER TABLE artist ADD PRIMARY KEY (artist_id);
ERROR 1068 (42000): Multiple primary key defined
mysql> ALTER TABLE artist3 ADD PRIMARY KEY (artist_id);
ERROR 1068 (42000): Multiple primary key defined
mysql> ALTER TABLE artist DROP PRIMARY KEY;
ERROR 1075 (42000): Incorrect table definition; there can be only one auto colum
n and it must be defined as a key
mysql> desc artist;
+--------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+----------------+
| artist_title | char(10) | YES | | NULL | |
| artist_id | smallint(5) | NO | PRI | NULL | auto_increment |
| formed2 | year(4) | YES | | NULL | |
| artist_name | char(253) | YES | | NULL | |
| formed | year(4) | YES | | NULL | |
+--------------+-------------+------+-----+---------+----------------+
5 rows in set (0.06 sec)

mysql> desc artist3;


+-------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+----------------+
| artist_id | smallint(5) | NO | PRI | NULL | auto_increment |
| artist_name | char(128) | YES | | NULL | |
+-------------+-------------+------+-----+---------+----------------+
2 rows in set (0.05 sec)

mysql> ALTER TABLE artist DROP artist_id;


Query OK, 3 rows affected (0.58 sec)
Records: 3 Duplicates: 0 Warnings: 0

mysql> alter table artist


-> rename to artist10;
Query OK, 0 rows affected (0.11 sec)

mysql> select * from artist10;


+--------------+---------+-------------+--------+
| artist_title | formed2 | artist_name | formed |
+--------------+---------+-------------+--------+
| NULL | NULL | The Shamen | NULL |
| NULL | NULL | Probot | NULL |
| NULL | NULL | The Cult | NULL |
+--------------+---------+-------------+--------+
3 rows in set (0.01 sec)

mysql> select * from artist;


ERROR 1146 (42S02): Table 'test.artist' doesn't exist

13th April 2023


Aggregate Functions

mysql> select distinct Salary


-> from gm_employee;
mysql> select distinct Salary , manager_id
-> from gm_employee;

mysql> select sum(Salary)


-> from gm_employee;
+-------------+
| sum(Salary) |
+-------------+
| 1287560 |
+-------------+
1 row in set (0.00 sec)

mysql> select avg(Salary)


-> from gm_employee;
+-------------+
| avg(Salary) |
+-------------+
| 12623.1373 |
+-------------+
1 row in set (0.00 sec)

mysql> select sum(distinct Salary)


-> from gm_employee;
+----------------------+
| sum(distinct Salary) |
+----------------------+
| 956660 |
+----------------------+
1 row in set (0.00 sec)

mysql> select count(Salary)


-> from gm_employee;
+---------------+
| count(Salary) |
+---------------+
| 102 |
+---------------+
1 row in set (0.00 sec)

mysql> select count(first_name)


-> from gm_employee;
+-------------------+
| count(first_name) |
+-------------------+
| 102 |
+-------------------+
1 row in set (0.00 sec)

mysql> select count(hire_date)


-> from gm_employee;
+------------------+
| count(hire_date) |
+------------------+
| 102 |
+------------------+
1 row in set (0.00 sec)

mysql> select count(distinct first_name)


-> from gm_employee;
+----------------------------+
| count(distinct first_name) |
+----------------------------+
| 87 |
+----------------------------+
1 row in set (0.00 sec)

mysql> select count(distinct hire_date)


-> from gm_employee;
+---------------------------+
| count(distinct hire_date) |
+---------------------------+
| 1|
+---------------------------+
1 row in set (0.00 sec)

mysql> select min(salary)


-> from gm_employee;
+-------------+
| min(salary) |
+-------------+
| 2100 |
+-------------+
1 row in set (0.00 sec)

mysql> select max(salary)


-> from gm_employee;
+-------------+
| max(salary) |
+-------------+
| 495000 |
+-------------+
1 row in set (0.00 sec)

mysql> select min(first_name)


-> from gm_employee;
+-----------------+
| min(first_name) |
+-----------------+
| Abhijeet |
+-----------------+
1 row in set (0.00 sec)

mysql> select min(hire_date)


-> from gm_employee;
+----------------+
| min(hire_date) |
+----------------+
| 0000-00-00 |
+----------------+
1 row in set (0.00 sec)

mysql> select max(hire_date)


-> from gm_employee;
+----------------+
| max(hire_date) |
+----------------+
| 0000-00-00 |
+----------------+
1 row in set (0.00 sec)

mysql> select std(salary)


-> from gm_employee;
+--------------------+
| std(salary) |
+--------------------+
| 48999.882652528395 |
+--------------------+
1 row in set (0.00 sec)

mysql> select job_id, sum(Salary)


-> from gm_employee
-> group by job_id;
+------------+-------------+
| job_id | sum(Salary) |
+------------+-------------+
| AC_ACCOUNT | 8300 |
| AC_MGR | 12000 |
| AD_ASST | 136400 |
| AD_VP | 74800 |
| HR_REP | 6500 |
| IT_PROG | 527760 |
| MK_MAN | 13000 |
| MK_REP | 6000 |
| PR_REP | 10000 |
| PU_CLERK | 13900 |
| PU_MAN | 11000 |
| SA_MAN | 61000 |
| SA_REP | 250500 |
| SH_CLERK | 64300 |
| ST_CLERK | 55700 |
| ST_MAN | 36400 |
+------------+-------------+
16 rows in set (0.00 sec)

mysql> select job_id, sum(Salary)


-> from gm_employee
-> group by job_id;
+------------+-------------+
| job_id | sum(Salary) |
+------------+-------------+
| AC_ACCOUNT | 8300 |
| AC_MGR | 12000 |
| AD_ASST | 136400 |
| AD_VP | 74800 |
| HR_REP | 6500 |
| IT_PROG | 527760 |
| MK_MAN | 13000 |
| MK_REP | 6000 |
| PR_REP | 10000 |
| PU_CLERK | 13900 |
| PU_MAN | 11000 |
| SA_MAN | 61000 |
| SA_REP | 250500 |
| SH_CLERK | 64300 |
| ST_CLERK | 55700 |
| ST_MAN | 36400 |
+------------+-------------+
16 rows in set (0.00 sec)

mysql> select job_id, count(manager_id)


-> from gm_employee
-> group by job_id;
+------------+-------------------+
| job_id | count(manager_id) |
+------------+-------------------+
| AC_ACCOUNT | 1|
| AC_MGR | 1|
| AD_ASST | 2|
| AD_VP | 2|
| HR_REP | 1|
| IT_PROG | 5|
| MK_MAN | 1|
| MK_REP | 1|
| PR_REP | 1|
| PU_CLERK | 5|
| PU_MAN | 1|
| SA_MAN | 5|
| SA_REP | 30 |
| SH_CLERK | 20 |
| ST_CLERK | 20 |
| ST_MAN | 5|
+------------+-------------------+
16 rows in set (0.00 sec)

mysql> select job_id, count(job_id)


-> from gm_employee
-> group by job_id;
+------------+---------------+
| job_id | count(job_id) |
+------------+---------------+
| AC_ACCOUNT | 1|
| AC_MGR | 1|
| AD_ASST | 3|
| AD_VP | 2|
| HR_REP | 1|
| IT_PROG | 5|
| MK_MAN | 1|
| MK_REP | 1|
| PR_REP | 1|
| PU_CLERK | 5|
| PU_MAN | 1|
| SA_MAN | 5|
| SA_REP | 30 |
| SH_CLERK | 20 |
| ST_CLERK | 20 |
| ST_MAN | 5|
+------------+---------------+
16 rows in set (0.00 sec)
mysql> select manager_id, sum(salary)
-> from gm_employee
-> group by manager_id;
+------------+-------------+
| manager_id | sum(salary) |
+------------+-------------+
| NULL | 66000 |
| 100 | 262200 |
| 101 | 32900 |
| 102 | 495000 |
| 103 | 32760 |
| 114 | 13900 |
| 120 | 22100 |
| 121 | 25400 |
| 122 | 23600 |
| 123 | 25900 |
| 124 | 23000 |
| 145 | 51000 |
| 146 | 51000 |
| 147 | 46600 |
| 148 | 51900 |
| 149 | 50000 |
| 201 | 6000 |
| 205 | 8300 |
+------------+-------------+
18 rows in set (0.00 sec)

mysql> select job_id, sum(Salary)


-> from gm_employee
-> group by job_id
-> having sum(salary)> 50000;
+----------+-------------+
| job_id | sum(Salary) |
+----------+-------------+
| AD_ASST | 136400 |
| AD_VP | 74800 |
| IT_PROG | 527760 |
| SA_MAN | 61000 |
| SA_REP | 250500 |
| SH_CLERK | 64300 |
| ST_CLERK | 55700 |
+----------+-------------+
7 rows in set (0.00 sec)

18th April 2023


Foreign Key
In the above diagram , loc_id in location table is a primary key and loc_id in dept table is a
foreign key.
So loc_id value in the dept table should match with the any loc_id value in the location table.

Explain Foreign key in 1000 words


A foreign key is a concept in database design that establishes a relationship between two tables.
It is a field or set of fields in a table that references the primary key of another table, creating a
link between the two tables. In simpler terms, it is a way to connect one table to another table in
a relational database.

To understand foreign keys, we first need to understand primary keys. A primary key is a unique
identifier for each record in a table. It is used to ensure that each record is unique and to provide
a way to reference a specific record in the table. A primary key can be a single field or a
combination of fields that together uniquely identify each record in the table.

A foreign key is a field or set of fields in one table that references the primary key of another
table. It is used to create a link between the two tables, allowing you to retrieve data from both
tables at the same time. The foreign key is typically defined in the child table, which is the table
that references the primary key of the parent table.

For example, let's say we have two tables: Customers and Orders. The Customers table has a
primary key of CustomerID, and the Orders table has a foreign key of CustomerID that
references the CustomerID field in the Customers table. This creates a relationship between the
two tables, where each order belongs to a specific customer.

Foreign keys are important because they help maintain data integrity in a database. They ensure
that each record in the child table has a corresponding record in the parent table. This prevents
data inconsistencies and ensures that the data in the database is accurate and reliable.
Foreign keys also help enforce referential integrity, which means that the data in the database is
consistent and conforms to business rules. For example, if we try to insert a record into the
Orders table with a CustomerID that does not exist in the Customers table, the database will
reject the insert because the foreign key constraint has been violated.

Foreign keys can be defined as either NULL or NOT NULL. If a foreign key is defined as NOT
NULL, it means that each record in the child table must have a corresponding record in the
parent table. If a foreign key is defined as NULL, it means that some records in the child table
may not have a corresponding record in the parent table.

Foreign keys can also be cascading, which means that changes made to the parent table will
automatically be propagated to the child table. For example, if we delete a record from the
Customers table, all orders associated with that customer will also be deleted from the Orders
table.

In conclusion, foreign keys are an essential concept in database design that establishes
relationships between tables and ensures data integrity and referential integrity. They help
maintain the accuracy and reliability of data in a database and ensure that the data conforms to
business rules.

mysql> use test;


Database changed
mysql> create table locations
-> (loc_id integer,
-> loc_name varchar(20)
-> );
Query OK, 0 rows affected (0.27 sec)

mysql> alter table locations


-> add primary key(loc_id);
Query OK, 0 rows affected (0.56 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> insert into locations values (1,'Pune');


Query OK, 1 row affected (0.02 sec)

mysql> insert into locations values (2,'Chennai');


Query OK, 1 row affected (0.04 sec)

mysql> insert into locations values (3,'Mumbai');


Query OK, 1 row affected (0.02 sec)

mysql> insert into locations values (5,'Delhi');


Query OK, 1 row affected (0.04 sec)
mysql> create table depts
-> (dept_id integer,
-> dept_name varchar(20),
-> loc_id integer);
Query OK, 0 rows affected (0.27 sec)

Adding a foreign key to the dept table: Syntax


mysql> alter table depts
-> add constraint loc_fk foreign key(loc_id) references locations(loc_id);

loc_fk is the name of the foreign key.

Query OK, 0 rows affected (0.60 sec)


Records: 0 Duplicates: 0 Warnings: 0

mysql> select *
-> from locations;
+--------+----------+
| loc_id | loc_name |
+--------+----------+
| 1 | Pune |
| 2 | Chennai |
| 3 | Mumbai |
| 5 | Delhi |
+--------+----------+
4 rows in set (0.00 sec)

mysql> select * from depts;


Empty set (0.00 sec)

mysql> desc depts;


+-----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| dept_id | int(11) | YES | | NULL | |
| dept_name | varchar(20) | YES | | NULL | |
| loc_id | int(11) | YES | MUL | NULL | |
+-----------+-------------+------+-----+---------+-------+
3 rows in set (0.06 sec)

mysql> insert into depts values(1,'HR',1);


Query OK, 1 row affected (0.03 sec)

mysql> insert into depts values(2,'IT',5);


Query OK, 1 row affected (0.04 sec)
mysql> insert into depts values(3,'Mktg',50);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint f
ails (`test`.`depts`, CONSTRAINT `loc_fk` FOREIGN KEY (`loc_id`) REFERENCES `loc
ations` (`loc_id`))

mysql> delete from locations where loc_id = 1;


ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constrai
nt fails (`test`.`depts`, CONSTRAINT `loc_fk` FOREIGN KEY (`loc_id`) REFERENCES
`locations` (`loc_id`))

mysql> delete from depts where dept_id = 1;


Query OK, 1 row affected (0.04 sec)

mysql> create table dept2


-> (
-> dept_id integer,
-> dept_name varchar(20),
-> loc_id integer,
-> constraint foreign key(loc_id) references locations(loc_id)
-> );
Query OK, 0 rows affected (0.30 sec)

mysql> update locations


-> set loc_id = 10
-> where loc_id = 1;
Query OK, 1 row affected (0.05 sec)
Rows matched: 1 Changed: 1 Warnings: 0

mysql> select * from depts;


+---------+-----------+--------+
| dept_id | dept_name | loc_id |
+---------+-----------+--------+
| 2 | IT | 5|
+---------+-----------+--------+
1 row in set (0.00 sec)

mysql> create table product


-> ( prod_id integer,
-> prod_name varchar(20)
-> );
Query OK, 0 rows affected (0.28 sec)

mysql> alter table product


-> add primary key (prod_id);
Query OK, 0 rows affected (0.58 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> create table dept3


-> (dept_id integer,
-> dept_name varchar(20),
-> loc_id integer,
-> prod_id integer,
-> constraint foreign key(loc_id) references locations(loc_id),
-> constraint foreign key(prod_id) references product(prod_id)
-> );
Query OK, 0 rows affected (0.43 sec)

mysql> insert into product values(10,'Alexa');


Query OK, 1 row affected (0.03 sec)

mysql> insert into product values(20,'Siri');


Query OK, 1 row affected (0.03 sec)

mysql> insert into product values(30,'AI');


Query OK, 1 row affected (0.03 sec)

mysql> insert into dept3 values(1,'IT',5,10);


Query OK, 1 row affected (0.03 sec)

mysql> select *
-> from dept3;
+---------+-----------+--------+---------+
| dept_id | dept_name | loc_id | prod_id |
+---------+-----------+--------+---------+
| 1 | IT | 5 | 10 |
+---------+-----------+--------+---------+
1 row in set (0.00 sec)

mysql> create table emp18


-> (emp_id integer,
-> emp_name varchar(20),
-> mgr_id integer
-> );
Query OK, 0 rows affected (0.21 sec)

mysql> alter table emp18


-> add primary key(emp_id);
Query OK, 0 rows affected (0.54 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> alter table emp18


-> add constraint emp_fk foreign key (mgr_id) references emp18(emp_id);
Query OK, 0 rows affected (0.53 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> insert into emp18 values(1,'Shravan',Null);


Query OK, 1 row affected (0.03 sec)

mysql> insert into emp18 values(2,'Diksha',1);


Query OK, 1 row affected (0.04 sec)

mysql> insert into emp18 values(3,'Hemant',1);


Query OK, 1 row affected (0.03 sec)

mysql> insert into emp18 values(4,'Hema',2);


Query OK, 1 row affected (0.04 sec)

mysql> select *
-> from emp18;
+--------+----------+--------+
| emp_id | emp_name | mgr_id |
+--------+----------+--------+
| 1 | Shravan | NULL |
| 2 | Diksha | 1 |
| 3 | Hemant | 1 |
| 4 | Hema | 2 |
+--------+----------+--------+
4 rows in set (0.00 sec)

20th April 2023


Cartesian Product

The Inner Join


The INNER JOIN clause matches rows between two tables based on the criteria you provide in
the USING clause.

mysql> use test;


Database changed

mysql> select * from locations;


+--------+----------+
| loc_id | loc_name |
+--------+----------+
| 2 | Chennai |
| 3 | Mumbai |
| 5 | Delhi |
| 10 | Pune |
+--------+----------+
4 rows in set (0.02 sec)

mysql> select * from depts;


+---------+-----------+--------+
| dept_id | dept_name | loc_id |
+---------+-----------+--------+
| 2 | IT | 5|
+---------+-----------+--------+
1 row in set (0.04 sec)

mysql> insert into depts values (


10,'HR',5);
Query OK, 1 row affected (0.03 sec)

mysql> insert into depts values (


30,'Marketing',10);
Query OK, 1 row affected (0.07 sec)

mysql> select * from locations;


+--------+----------+
| loc_id | loc_name |
+--------+----------+
| 2 | Chennai |
| 3 | Mumbai |
| 5 | Delhi |
| 10 | Pune |
+--------+----------+
4 rows in set (0.00 sec)

mysql> select * from depts;


+---------+-----------+--------+
| dept_id | dept_name | loc_id |
+---------+-----------+--------+
| 2 | IT | 5|
| 10 | HR | 5|
| 30 | Marketing | 10 |
+---------+-----------+--------+
3 rows in set (0.00 sec)

mysql> select *
-> from depts, locations;
+---------+-----------+--------+--------+----------+
| dept_id | dept_name | loc_id | loc_id | loc_name |
+---------+-----------+--------+--------+----------+
| 2 | IT | 5 | 2 | Chennai |
| 10 | HR | 5 | 2 | Chennai |
| 30 | Marketing | 10 | 2 | Chennai |
| 2 | IT | 5 | 3 | Mumbai |
| 10 | HR | 5 | 3 | Mumbai |
| 30 | Marketing | 10 | 3 | Mumbai |
| 2 | IT | 5 | 5 | Delhi |
| 10 | HR | 5| 5 | Delhi |
| 30 | Marketing | 10 | 5 | Delhi |
| 2 | IT | 5 | 10 | Pune |
| 10 | HR | 5 | 10 | Pune |
| 30 | Marketing | 10 | 10 | Pune |
+---------+-----------+--------+--------+----------+
12 rows in set (0.00 sec)

mysql> select dept_name, loc_name


-> from depts inner join locations using(loc_id);
+-----------+----------+
| dept_name | loc_name |
+-----------+----------+
| IT | Delhi |
| HR | Delhi |
| Marketing | Pune |
+-----------+----------+
3 rows in set (0.00 sec)

mysql> insert into depts values ( 30,'Finance', Null);


Query OK, 1 row affected (0.04 sec)

mysql> select dept_name, loc_name


-> from depts inner join locations using(loc_id);
+-----------+----------+
| dept_name | loc_name |
+-----------+----------+
| IT | Delhi |
| HR | Delhi |
| Marketing | Pune |
+-----------+----------+
3 rows in set (0.00 sec)

mysql> select dept_name, loc_name,dept_id


-> from locations inner join depts using(loc_id);
+-----------+----------+---------+
| dept_name | loc_name | dept_id |
+-----------+----------+---------+
| IT | Delhi | 2|
| HR | Delhi | 10 |
| Marketing | Pune | 30 |
+-----------+----------+---------+
3 rows in set (0.00 sec)

mysql> select dept_name, loc_name,dept_id,loc_id


-> from locations inner join depts using(loc_id);
+-----------+----------+---------+--------+
| dept_name | loc_name | dept_id | loc_id |
+-----------+----------+---------+--------+
| IT | Delhi | 2| 5|
| HR | Delhi | 10 | 5 |
| Marketing | Pune | 30 | 10 |
+-----------+----------+---------+--------+
3 rows in set (0.00 sec)

mysql> desc product;


+-----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| prod_id | int(11) | NO | PRI | 0 | |
| prod_name | varchar(20) | YES | | NULL | |
+-----------+-------------+------+-----+---------+-------+
2 rows in set (0.12 sec)

mysql> desc dept3;


+-----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| dept_id | int(11) | YES | | NULL | |
| dept_name | varchar(20) | YES | | NULL | |
| loc_id | int(11) | YES | MUL | NULL | |
| prod_id | int(11) | YES | MUL | NULL | |
+-----------+-------------+------+-----+---------+-------+
4 rows in set (0.06 sec)

mysql> select * from product;


+---------+-----------+
| prod_id | prod_name |
+---------+-----------+
| 10 | Alexa |
| 20 | Siri |
| 30 | AI |
+---------+-----------+
3 rows in set (0.02 sec)

mysql> select * from dept3;


+---------+-----------+--------+---------+
| dept_id | dept_name | loc_id | prod_id |
+---------+-----------+--------+---------+
| 1 | IT | 5 | 10 |
+---------+-----------+--------+---------+
1 row in set (0.03 sec)

mysql> insert into dept3 values(100,'HR',10,20);


Query OK, 1 row affected (0.05 sec)

mysql> select * from dept3;


+---------+-----------+--------+---------+
| dept_id | dept_name | loc_id | prod_id |
+---------+-----------+--------+---------+
| 1 | IT | 5 | 10 |
| 100 | HR | 10 | 20 |
+---------+-----------+--------+---------+
2 rows in set (0.00 sec)

mysql> select loc_name, prod_name,dept_name


-> from dept3 inner join locations using(loc_id)
-> inner join product using (prod_id);
+----------+-----------+-----------+
| loc_name | prod_name | dept_name |
+----------+-----------+-----------+
| Delhi | Alexa | IT |
| Pune | Siri | HR |
+----------+-----------+-----------+
2 rows in set (0.00 sec)

mysql> select loc_name, prod_name,dept_name


-> from dept3 d, locations l , product p
-> where l.loc_id = d.loc_id
-> and d.prod_id = p.prod_id;
+----------+-----------+-----------+
| loc_name | prod_name | dept_name |
+----------+-----------+-----------+
| Delhi | Alexa | IT |
| Pune | Siri | HR |
+----------+-----------+-----------+
2 rows in set (0.00 sec)

mysql> select loc_name, prod_name,dept_name


-> from dept3 , locations , product
-> where dept3.loc_id = locations.loc_id
-> and dept3.prod_id = product.prod_id;
+----------+-----------+-----------+
| loc_name | prod_name | dept_name |
+----------+-----------+-----------+
| Delhi | Alexa | IT |
| Pune | Siri | HR |
+----------+-----------+-----------+
2 rows in set (0.00 sec)

Date : 1st May 2023

Union, Left Join, Right Join, Natural Join


mysql> use test;
Database changed
mysql> select * from locations;
+--------+----------+
| loc_id | loc_name |
+--------+----------+
| 2 | Chennai |
| 3 | Mumbai |
| 5 | Delhi |
| 10 | Pune |
+--------+----------+
4 rows in set (0.02 sec)

mysql> select * from depts;


+---------+-----------+--------+
| dept_id | dept_name | loc_id |
+---------+-----------+--------+
| 2 | IT | 5|
| 10 | HR | 5|
| 30 | Marketing | 10 |
| 30 | Finance | NULL |
+---------+-----------+--------+
4 rows in set (0.03 sec)

mysql> select * from depts inner join locations using(loc_id);


+--------+---------+-----------+----------+
| loc_id | dept_id | dept_name | loc_name |
+--------+---------+-----------+----------+
| 5| 2 | IT | Delhi |
| 5 | 10 | HR | Delhi |
| 10 | 30 | Marketing | Pune |
+--------+---------+-----------+----------+
3 rows in set (0.00 sec)
mysql> select loc_id,loc_name from locations
-> union
-> select dept_id,dept_name from depts
-> ;
+--------+-----------+
| loc_id | loc_name |
+--------+-----------+
| 2 | Chennai |
| 3 | Mumbai |
| 5 | Delhi |
| 10 | Pune |
| 2 | IT |
| 10 | HR |
| 30 | Marketing |
| 30 | Finance |
+--------+-----------+
8 rows in set (0.00 sec)

mysql> select loc_name from locations


-> union
-> select dept_name from depts;
+-----------+
| loc_name |
+-----------+
| Chennai |
| Mumbai |
| Delhi |
| Pune |
| IT |
| HR |
| Marketing |
| Finance |
+-----------+
8 rows in set (0.00 sec)

mysql> select * from depts left join locations using(loc_id);


+--------+---------+-----------+----------+
| loc_id | dept_id | dept_name | loc_name |
+--------+---------+-----------+----------+
| 5| 2 | IT | Delhi |
| 5 | 10 | HR | Delhi |
| 10 | 30 | Marketing | Pune |
| NULL | 30 | Finance | NULL |
+--------+---------+-----------+----------+
4 rows in set (0.00 sec)
mysql> select * from locations left join depts using(loc_id);
+--------+----------+---------+-----------+
| loc_id | loc_name | dept_id | dept_name |
+--------+----------+---------+-----------+
| 5 | Delhi | 2 | IT |
| 5 | Delhi | 10 | HR |
| 10 | Pune | 30 | Marketing |
| 2 | Chennai | NULL | NULL |
| 3 | Mumbai | NULL | NULL |
+--------+----------+---------+-----------+
5 rows in set (0.00 sec)

mysql> select * from depts right join locations using(loc_id);


+--------+----------+---------+-----------+
| loc_id | loc_name | dept_id | dept_name |
+--------+----------+---------+-----------+
| 5 | Delhi | 2 | IT |
| 5 | Delhi | 10 | HR |
| 10 | Pune | 30 | Marketing |
| 2 | Chennai | NULL | NULL |
| 3 | Mumbai | NULL | NULL |
+--------+----------+---------+-----------+
5 rows in set (0.00 sec)

mysql> select * from locations right join depts using(loc_id);


+--------+---------+-----------+----------+
| loc_id | dept_id | dept_name | loc_name |
+--------+---------+-----------+----------+
| 5| 2 | IT | Delhi |
| 5 | 10 | HR | Delhi |
| 10 | 30 | Marketing | Pune |
| NULL | 30 | Finance | NULL |
+--------+---------+-----------+----------+
4 rows in set (0.00 sec)

mysql> select * from locations natural join depts;


+--------+----------+---------+-----------+
| loc_id | loc_name | dept_id | dept_name |
+--------+----------+---------+-----------+
| 5 | Delhi | 2 | IT |
| 5 | Delhi | 10 | HR |
| 10 | Pune | 30 | Marketing |
+--------+----------+---------+-----------+
3 rows in set (0.00 sec)
mysql> select * from depts natural join locations;
+--------+---------+-----------+----------+
| loc_id | dept_id | dept_name | loc_name |
+--------+---------+-----------+----------+
| 5| 2 | IT | Delhi |
| 5 | 10 | HR | Delhi |
| 10 | 30 | Marketing | Pune |
+--------+---------+-----------+----------+
3 rows in set (0.00 sec)

mysql> select loc_id,dept_name from depts natural join locations;


+--------+-----------+
| loc_id | dept_name |
+--------+-----------+
| 5 | IT |
| 5 | HR |
| 10 | Marketing |
+--------+-----------+
3 rows in set (0.00 sec)

Date: 9th May 2023


Subqueries

Query inside a query is called as a Subquery.


Outer Query(Inner Query)
Inner query executes first and sends output to the outer query.
Based on this output, outer query will give the result.

Single Row Subquery


Inner query gives output as one row only.

Single Row Subquery Operators


< , > , <= , >= , =, <>

Name of the department located in Delhi


1. Find loc_id of Delhi
2. Find department_name based on loc_id

mysql> select * from locations;


+--------+----------+
| loc_id | loc_name |
+--------+----------+
| 2 | Chennai |
| 3 | Mumbai |
| 5 | Delhi |
| 10 | Pune |
+--------+----------+
4 rows in set (0.04 sec)

mysql> select * from depts;


+---------+-----------+--------+
| dept_id | dept_name | loc_id |
+---------+-----------+--------+
| 2 | IT | 5|
| 10 | HR | 5|
| 30 | Marketing | 10 |
| 30 | Finance | NULL |
+---------+-----------+--------+
4 rows in set (0.01 sec)

mysql> select dept_name


-> from depts
-> where loc_id = ( select loc_id from locations where loc_name='Delhi');
+-----------+
| dept_name |
+-----------+
| IT |
| HR |
+-----------+
2 rows in set (0.00 sec)

mysql> select dept_name


-> from depts
-> where loc_id != ( select loc_id from locations where loc_name='Delhi');
+-----------+
| dept_name |
+-----------+
| Marketing |
+-----------+
1 row in set (0.00 sec)

Multiple Row Subquery Operators


IN, ANY, ALL

mysql> select * from locations;


+--------+----------+
| loc_id | loc_name |
+--------+----------+
| 2 | Chennai |
| 3 | Mumbai |
| 5 | Delhi |
| 10 | Pune |
+--------+----------+
4 rows in set (0.04 sec)

mysql> select * from depts;


+---------+-----------+--------+
| dept_id | dept_name | loc_id |
+---------+-----------+--------+
| 2 | IT | 5|
| 10 | HR | 5|
| 30 | Marketing | 10 |
| 30 | Finance | NULL |
+---------+-----------+--------+
4 rows in set (0.01 sec)

mysql> select dept_name


-> from depts
-> where loc_id IN ( select loc_id from locations where loc_name='Delhi' or
loc_name='Pune');
+-----------+
| dept_name |
+-----------+
| IT |
| HR |
| Marketing |
+-----------+
3 rows in set (0.00 sec)

mysql> select dept_id,dept_name


-> from depts
-> where loc_id IN ( select loc_id from locations where loc_name='Delhi' or
loc_name='Pune');
+---------+-----------+
| dept_id | dept_name |
+---------+-----------+
| 2 | IT |
| 10 | HR |
| 30 | Marketing |
+---------+-----------+
3 rows in set (0.00 sec)

mysql> select dept_name


-> from depts
-> where loc_id < any ( select loc_id from locations where loc_name='Delhi'
or loc_name='Pune');
+-----------+
| dept_name |
+-----------+
| IT |
| HR |
+-----------+
2 rows in set (0.00 sec)

mysql> select dept_name


-> from depts
-> where loc_id < all ( select loc_id from locations where loc_name='Delhi'
or loc_name='Pune');
Empty set (0.00 sec)

mysql> select dept_name


-> from depts
-> where loc_id < some ( select loc_id from locations where loc_name='Delhi'
or loc_name='Pune');
+-----------+
| dept_name |
+-----------+
| IT |
| HR |
+-----------+
2 rows in set (0.00 sec)

EXISTS AND NOT EXISTS


Exists returns true if the Inner query gives output else it returns FALSE

Not Exists returns true if the Inner query does not give output else it returns FALSE

mysql> select dept_name


-> from depts
-> where exists ( select loc_id from locations where loc_name='Delhi' or loc
_name='Pune');
+-----------+
| dept_name |
+-----------+
| IT |
| HR |
| Marketing |
| Finance |
+-----------+
4 rows in set (0.00 sec)

mysql> select dept_name


-> from depts
-> where exists ( select loc_id from locations where loc_name='Delhi1' or lo
c_name='Pune1');
Empty set (0.00 sec)

mysql> select dept_name


-> from depts
-> where not exists ( select loc_id from locations where loc_name='Delhi1' o
r loc_name='Pune1');
+-----------+
| dept_name |
+-----------+
| IT |
| HR |
| Marketing |
| Finance |
+-----------+
4 rows in set (0.00 sec)

mysql> select dept_name


-> from depts
-> where not exists ( select loc_id from locations where loc_name='Delhi' or
loc_name='Pune');
Empty set (0.00 sec)

# mysql -u root
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 12
Server version: 10.4.27-MariaDB mariadb.org binary distribution

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> use test;


Database changed
MariaDB [test]> select * from gm_employee;
ERROR 1146 (42S02): Table 'test.gm_employee' doesn't exist
MariaDB [test]> Create table GM_Employee
-> (
-> Employee_ID integer,
-> First_Name varchar(20),
-> Last_name varchar(25),
-> Email varchar(25),
-> Phone_number varchar(20),
-> Hire_Date Date,
-> Job_id varchar(10),
-> Salary integer,
-> Commission_pct integer,
-> Manager_id integer,
-> Department_id integer,
-> Department_name varchar(30)
-> );
Query OK, 0 rows affected (0.381 sec)

MariaDB [test]> Insert into GM_EMPLOYEE


-> (EMPLOYEE_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER,
HIRE_DATE, JOB_ID, SALARY, COMMISSION_PCT, DEPARTMENT_ID,
DEPARTMENT_NAME)
-> Values
-> (100, 'Steven', 'King', 'SKING', '515.123.4567', '2019-02-22', 'AD_ASST', 66000, 0, 90,
'Executive');
Query OK, 1 row affected (0.200 sec)

MariaDB [test]> Insert into GM_EMPLOYEE


-> (EMPLOYEE_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER,
HIRE_DATE, JOB_ID, SALARY, COMMISSION_PCT, MANAGER_ID,
DEPARTMENT_ID, DEPARTMENT_NAME)
-> Values
-> (101, 'Abhijeet', 'Kochhar', 'NKOCHHAR', '515.123.4568', 2019-02-28, 'AD_VP', 37400,
0, 100, 90, 'Executive');
Query OK, 1 row affected, 1 warning (0.035 sec)

MariaDB [test]> Insert into GM_EMPLOYEE


-> (EMPLOYEE_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER,
HIRE_DATE, JOB_ID, SALARY, COMMISSION_PCT, MANAGER_ID,
DEPARTMENT_ID, DEPARTMENT_NAME)
-> Values
-> (102, 'priya', 'De Haan', 'LDEHAAN', '515.123.4569', '2020-02-28', 'AD_VP', 37400, 0,
100, 90, 'Executive');
Query OK, 1 row affected (0.062 sec)

MariaDB [test]> Insert into GM_EMPLOYEE


-> (EMPLOYEE_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER,
HIRE_DATE, JOB_ID, SALARY, COMMISSION_PCT, MANAGER_ID,
DEPARTMENT_ID, DEPARTMENT_NAME)
-> Values
-> (103, 'Alexander', 'Hunold', 'AHUNOLD', '590.423.4567', '2020-02-28', 'IT_PROG',
495000, 0, 102, 60, 'FORD');
Query OK, 1 row affected (0.022 sec)
MariaDB [test]> Insert into GM_EMPLOYEE
-> (EMPLOYEE_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER,
HIRE_DATE, JOB_ID, SALARY, COMMISSION_PCT, MANAGER_ID,
DEPARTMENT_ID)
-> Values
-> (104, 'Bruce', 'Ernst', 'BERNST', '590.423.4568', '2020-02-28', 'IT_PROG', 13200, 0,
103, 22);
Query OK, 1 row affected (0.067 sec)

MariaDB [test]> commit;


Query OK, 0 rows affected (0.000 sec)

MariaDB [test]> select * from gm_employee;


+-------------+------------+-----------+----------+--------------+------------+---------+--------+------------
----+------------+---------------+-----------------+
| Employee_ID | First_Name | Last_name | Email | Phone_number | Hire_Date | Job_id |
Salary | Commission_pct | Manager_id | Department_id | Department_name |
+-------------+------------+-----------+----------+--------------+------------+---------+--------+------------
----+------------+---------------+-----------------+
| 100 | Steven | King | SKING | 515.123.4567 | 2019-02-22 | AD_ASST | 66000 |
0| NULL | 90 | Executive |
| 101 | Abhijeet | Kochhar | NKOCHHAR | 515.123.4568 | 0000-00-00 | AD_VP |
37400 | 0| 100 | 90 | Executive |
| 102 | priya | De Haan | LDEHAAN | 515.123.4569 | 2020-02-28 | AD_VP | 37400 |
0| 100 | 90 | Executive |
| 103 | Alexander | Hunold | AHUNOLD | 590.423.4567 | 2020-02-28 | IT_PROG |
495000 | 0| 102 | 60 | FORD |
| 104 | Bruce | Ernst | BERNST | 590.423.4568 | 2020-02-28 | IT_PROG | 13200 |
0| 103 | 22 | NULL |
+-------------+------------+-----------+----------+--------------+------------+---------+--------+------------
----+------------+---------------+-----------------+
5 rows in set (0.033 sec)

MariaDB [test]> select *


-> from gm_employee
-> where first_name REGEXP '^A';
+-------------+------------+-----------+----------+--------------+------------+---------+--------+------------
----+------------+---------------+-----------------+
| Employee_ID | First_Name | Last_name | Email | Phone_number | Hire_Date | Job_id |
Salary | Commission_pct | Manager_id | Department_id | Department_name |
+-------------+------------+-----------+----------+--------------+------------+---------+--------+------------
----+------------+---------------+-----------------+
| 101 | Abhijeet | Kochhar | NKOCHHAR | 515.123.4568 | 0000-00-00 | AD_VP |
37400 | 0| 100 | 90 | Executive |
| 103 | Alexander | Hunold | AHUNOLD | 590.423.4567 | 2020-02-28 | IT_PROG |
495000 | 0| 102 | 60 | FORD |
+-------------+------------+-----------+----------+--------------+------------+---------+--------+------------
----+------------+---------------+-----------------+
2 rows in set (0.070 sec)

MariaDB [test]> select *


-> from gm_employee
-> where first_name REGEXP 'n$';
+-------------+------------+-----------+-------+--------------+------------+---------+--------+---------------
-+------------+---------------+-----------------+
| Employee_ID | First_Name | Last_name | Email | Phone_number | Hire_Date | Job_id | Salary |
Commission_pct | Manager_id | Department_id | Department_name |
+-------------+------------+-----------+-------+--------------+------------+---------+--------+---------------
-+------------+---------------+-----------------+
| 100 | Steven | King | SKING | 515.123.4567 | 2019-02-22 | AD_ASST | 66000 |
0| NULL | 90 | Executive |
+-------------+------------+-----------+-------+--------------+------------+---------+--------+---------------
-+------------+---------------+-----------------+
1 row in set (0.001 sec)

MariaDB [test]> select *


-> from gm_employee
-> where first_name REGEXP 'en$';
+-------------+------------+-----------+-------+--------------+------------+---------+--------+---------------
-+------------+---------------+-----------------+
| Employee_ID | First_Name | Last_name | Email | Phone_number | Hire_Date | Job_id | Salary |
Commission_pct | Manager_id | Department_id | Department_name |
+-------------+------------+-----------+-------+--------------+------------+---------+--------+---------------
-+------------+---------------+-----------------+
| 100 | Steven | King | SKING | 515.123.4567 | 2019-02-22 | AD_ASST | 66000 |
0| NULL | 90 | Executive |
+-------------+------------+-----------+-------+--------------+------------+---------+--------+---------------
-+------------+---------------+-----------------+
1 row in set (0.001 sec)

MariaDB [test]> select *


-> from gm_employee
-> where first_name REGEXP 'AD?';
+-------------+------------+-----------+----------+--------------+------------+---------+--------+------------
----+------------+---------------+-----------------+
| Employee_ID | First_Name | Last_name | Email | Phone_number | Hire_Date | Job_id |
Salary | Commission_pct | Manager_id | Department_id | Department_name |
+-------------+------------+-----------+----------+--------------+------------+---------+--------+------------
----+------------+---------------+-----------------+
| 101 | Abhijeet | Kochhar | NKOCHHAR | 515.123.4568 | 0000-00-00 | AD_VP |
37400 | 0| 100 | 90 | Executive |
| 102 | priya | De Haan | LDEHAAN | 515.123.4569 | 2020-02-28 | AD_VP | 37400 |
0| 100 | 90 | Executive |
| 103 | Alexander | Hunold | AHUNOLD | 590.423.4567 | 2020-02-28 | IT_PROG |
495000 | 0| 102 | 60 | FORD |
+-------------+------------+-----------+----------+--------------+------------+---------+--------+------------
----+------------+---------------+-----------------+
3 rows in set (0.001 sec)

MariaDB [test]> select *


-> from gm_employee
-> where first_name REGEXP 'bhi | ven';
Empty set (0.001 sec)

MariaDB [test]> select *


-> from gm_employee
-> where first_name REGEXP 'bhi|ven';
+-------------+------------+-----------+----------+--------------+------------+---------+--------+------------
----+------------+---------------+-----------------+
| Employee_ID | First_Name | Last_name | Email | Phone_number | Hire_Date | Job_id |
Salary | Commission_pct | Manager_id | Department_id | Department_name |
+-------------+------------+-----------+----------+--------------+------------+---------+--------+------------
----+------------+---------------+-----------------+
| 100 | Steven | King | SKING | 515.123.4567 | 2019-02-22 | AD_ASST | 66000 |
0| NULL | 90 | Executive |
| 101 | Abhijeet | Kochhar | NKOCHHAR | 515.123.4568 | 0000-00-00 | AD_VP |
37400 | 0| 100 | 90 | Executive |
+-------------+------------+-----------+----------+--------------+------------+---------+--------+------------
----+------------+---------------+-----------------+
2 rows in set (0.001 sec)

MariaDB [test]> select *


-> from gm_employee
-> where first_name REGEXP '[B-G]';
+-------------+------------+-----------+----------+--------------+------------+---------+--------+------------
----+------------+---------------+-----------------+
| Employee_ID | First_Name | Last_name | Email | Phone_number | Hire_Date | Job_id |
Salary | Commission_pct | Manager_id | Department_id | Department_name |
+-------------+------------+-----------+----------+--------------+------------+---------+--------+------------
----+------------+---------------+-----------------+
| 100 | Steven | King | SKING | 515.123.4567 | 2019-02-22 | AD_ASST | 66000 |
0| NULL | 90 | Executive |
| 101 | Abhijeet | Kochhar | NKOCHHAR | 515.123.4568 | 0000-00-00 | AD_VP |
37400 | 0| 100 | 90 | Executive |
| 103 | Alexander | Hunold | AHUNOLD | 590.423.4567 | 2020-02-28 | IT_PROG |
495000 | 0| 102 | 60 | FORD |
| 104 | Bruce | Ernst | BERNST | 590.423.4568 | 2020-02-28 | IT_PROG | 13200 |
0| 103 | 22 | NULL |
+-------------+------------+-----------+----------+--------------+------------+---------+--------+------------
----+------------+---------------+-----------------+
4 rows in set (0.001 sec)

MariaDB [test]> select *


-> from gm_employee
-> where first_name REGEXP 'n[[:>:]]';
+-------------+------------+-----------+-------+--------------+------------+---------+--------+---------------
-+------------+---------------+-----------------+
| Employee_ID | First_Name | Last_name | Email | Phone_number | Hire_Date | Job_id | Salary |
Commission_pct | Manager_id | Department_id | Department_name |
+-------------+------------+-----------+-------+--------------+------------+---------+--------+---------------
-+------------+---------------+-----------------+
| 100 | Steven | King | SKING | 515.123.4567 | 2019-02-22 | AD_ASST | 66000 |
0| NULL | 90 | Executive |
+-------------+------------+-----------+-------+--------------+------------+---------+--------+---------------
-+------------+---------------+-----------------+
1 row in set (0.001 sec)

MariaDB [test]> select *


-> from gm_employee
-> where first_name REGEXP 'St[[:<:]]';
Empty set (0.001 sec)

MariaDB [test]> select *


-> from gm_employee
-> where first_name REGEXP 'S[[:<:]]';
Empty set (0.001 sec)

MariaDB [test]> select *


-> from gm_employee
-> where first_name REGEXP '[[:<:]]St';
+-------------+------------+-----------+-------+--------------+------------+---------+--------+---------------
-+------------+---------------+-----------------+
| Employee_ID | First_Name | Last_name | Email | Phone_number | Hire_Date | Job_id | Salary |
Commission_pct | Manager_id | Department_id | Department_name |
+-------------+------------+-----------+-------+--------------+------------+---------+--------+---------------
-+------------+---------------+-----------------+
| 100 | Steven | King | SKING | 515.123.4567 | 2019-02-22 | AD_ASST | 66000 |
0| NULL | 90 | Executive |
+-------------+------------+-----------+-------+--------------+------------+---------+--------+---------------
-+------------+---------------+-----------------+
1 row in set (0.001 sec)
MariaDB [test]> select *
-> from gm_employee
-> where first_name REGEXP '[[:<:]]St' or SALARY REGEXP '[0..5]';
+-------------+------------+-----------+----------+--------------+------------+---------+--------+------------
----+------------+---------------+-----------------+
| Employee_ID | First_Name | Last_name | Email | Phone_number | Hire_Date | Job_id |
Salary | Commission_pct | Manager_id | Department_id | Department_name |
+-------------+------------+-----------+----------+--------------+------------+---------+--------+------------
----+------------+---------------+-----------------+
| 100 | Steven | King | SKING | 515.123.4567 | 2019-02-22 | AD_ASST | 66000 |
0| NULL | 90 | Executive |
| 101 | Abhijeet | Kochhar | NKOCHHAR | 515.123.4568 | 0000-00-00 | AD_VP |
37400 | 0| 100 | 90 | Executive |
| 102 | priya | De Haan | LDEHAAN | 515.123.4569 | 2020-02-28 | AD_VP | 37400 |
0| 100 | 90 | Executive |
| 103 | Alexander | Hunold | AHUNOLD | 590.423.4567 | 2020-02-28 | IT_PROG |
495000 | 0| 102 | 60 | FORD |
| 104 | Bruce | Ernst | BERNST | 590.423.4568 | 2020-02-28 | IT_PROG | 13200 |
0| 103 | 22 | NULL |
+-------------+------------+-----------+----------+--------------+------------+---------+--------+------------
----+------------+---------------+-----------------+
5 rows in set (0.025 sec)

MariaDB [test]> select *


-> from gm_employee
-> where first_name REGEXP '[[:<:]]St' or SALARY REGEXP '[0..2]';
+-------------+------------+-----------+----------+--------------+------------+---------+--------+------------
----+------------+---------------+-----------------+
| Employee_ID | First_Name | Last_name | Email | Phone_number | Hire_Date | Job_id |
Salary | Commission_pct | Manager_id | Department_id | Department_name |
+-------------+------------+-----------+----------+--------------+------------+---------+--------+------------
----+------------+---------------+-----------------+
| 100 | Steven | King | SKING | 515.123.4567 | 2019-02-22 | AD_ASST | 66000 |
0| NULL | 90 | Executive |
| 101 | Abhijeet | Kochhar | NKOCHHAR | 515.123.4568 | 0000-00-00 | AD_VP |
37400 | 0| 100 | 90 | Executive |
| 102 | priya | De Haan | LDEHAAN | 515.123.4569 | 2020-02-28 | AD_VP | 37400 |
0| 100 | 90 | Executive |
| 103 | Alexander | Hunold | AHUNOLD | 590.423.4567 | 2020-02-28 | IT_PROG |
495000 | 0| 102 | 60 | FORD |
| 104 | Bruce | Ernst | BERNST | 590.423.4568 | 2020-02-28 | IT_PROG | 13200 |
0| 103 | 22 | NULL |
+-------------+------------+-----------+----------+--------------+------------+---------+--------+------------
----+------------+---------------+-----------------+
5 rows in set (0.001 sec)
MariaDB [test]> select *
-> from gm_employee
-> where first_name REGEXP '[[:<:]]St' or SALARY REGEXP '[1..2]';
+-------------+------------+-----------+--------+--------------+------------+---------+--------+--------------
--+------------+---------------+-----------------+
| Employee_ID | First_Name | Last_name | Email | Phone_number | Hire_Date | Job_id | Salary
| Commission_pct | Manager_id | Department_id | Department_name |
+-------------+------------+-----------+--------+--------------+------------+---------+--------+--------------
--+------------+---------------+-----------------+
| 100 | Steven | King | SKING | 515.123.4567 | 2019-02-22 | AD_ASST | 66000 |
0| NULL | 90 | Executive |
| 104 | Bruce | Ernst | BERNST | 590.423.4568 | 2020-02-28 | IT_PROG | 13200 |
0| 103 | 22 | NULL |
+-------------+------------+-----------+--------+--------------+------------+---------+--------+--------------
--+------------+---------------+-----------------+
2 rows in set (0.001 sec)

MariaDB [test]> select *


->
-> from gm_employee
-> where SALARY REGEXP '[1..2]';
+-------------+------------+-----------+--------+--------------+------------+---------+--------+--------------
--+------------+---------------+-----------------+
| Employee_ID | First_Name | Last_name | Email | Phone_number | Hire_Date | Job_id | Salary
| Commission_pct | Manager_id | Department_id | Department_name |
+-------------+------------+-----------+--------+--------------+------------+---------+--------+--------------
--+------------+---------------+-----------------+
| 104 | Bruce | Ernst | BERNST | 590.423.4568 | 2020-02-28 | IT_PROG | 13200 |
0| 103 | 22 | NULL |
+-------------+------------+-----------+--------+--------------+------------+---------+--------+--------------
--+------------+---------------+-----------------+
1 row in set (0.001 sec)

MariaDB [test]> select *


-> from gm_employee
-> where SALARY REGEXP '[1-2]';
+-------------+------------+-----------+--------+--------------+------------+---------+--------+--------------
--+------------+---------------+-----------------+
| Employee_ID | First_Name | Last_name | Email | Phone_number | Hire_Date | Job_id | Salary
| Commission_pct | Manager_id | Department_id | Department_name |
+-------------+------------+-----------+--------+--------------+------------+---------+--------+--------------
--+------------+---------------+-----------------+
| 104 | Bruce | Ernst | BERNST | 590.423.4568 | 2020-02-28 | IT_PROG | 13200 |
0| 103 | 22 | NULL |
+-------------+------------+-----------+--------+--------------+------------+---------+--------+--------------
--+------------+---------------+-----------------+
1 row in set (0.001 sec)

MariaDB [test]> select *


-> from gm_employee
-> where SALARY regexp '[1-2]';
+-------------+------------+-----------+--------+--------------+------------+---------+--------+--------------
--+------------+---------------+-----------------+
| Employee_ID | First_Name | Last_name | Email | Phone_number | Hire_Date | Job_id | Salary
| Commission_pct | Manager_id | Department_id | Department_name |
+-------------+------------+-----------+--------+--------------+------------+---------+--------+--------------
--+------------+---------------+-----------------+
| 104 | Bruce | Ernst | BERNST | 590.423.4568 | 2020-02-28 | IT_PROG | 13200 |
0| 103 | 22 | NULL |
+-------------+------------+-----------+--------+--------------+------------+---------+--------+--------------
--+------------+---------------+-----------------+
1 row in set (0.001 sec)

MariaDB [test]> select *


-> from gm_employee
-> where first_name REGEXP 'AD+';
Empty set (0.001 sec)

MariaDB [test]> select *


-> from gm_employee
-> where first_name REGEXP 'AD+|Ab+';
+-------------+------------+-----------+----------+--------------+------------+--------+--------+-------------
---+------------+---------------+-----------------+
| Employee_ID | First_Name | Last_name | Email | Phone_number | Hire_Date | Job_id | Salary
| Commission_pct | Manager_id | Department_id | Department_name |
+-------------+------------+-----------+----------+--------------+------------+--------+--------+-------------
---+------------+---------------+-----------------+
| 101 | Abhijeet | Kochhar | NKOCHHAR | 515.123.4568 | 0000-00-00 | AD_VP | 37400
| 0| 100 | 90 | Executive |
+-------------+------------+-----------+----------+--------------+------------+--------+--------+-------------
---+------------+---------------+-----------------+
1 row in set (0.001 sec)

MariaDB [test]> select *


-> from gm_employee
-> where first_name REGEXP 'Br+|Ab+';
+-------------+------------+-----------+----------+--------------+------------+---------+--------+------------
----+------------+---------------+-----------------+
| Employee_ID | First_Name | Last_name | Email | Phone_number | Hire_Date | Job_id |
Salary | Commission_pct | Manager_id | Department_id | Department_name |
+-------------+------------+-----------+----------+--------------+------------+---------+--------+------------
----+------------+---------------+-----------------+
| 101 | Abhijeet | Kochhar | NKOCHHAR | 515.123.4568 | 0000-00-00 | AD_VP |
37400 | 0| 100 | 90 | Executive |
| 104 | Bruce | Ernst | BERNST | 590.423.4568 | 2020-02-28 | IT_PROG | 13200 |
0| 103 | 22 | NULL |
+-------------+------------+-----------+----------+--------------+------------+---------+--------+------------
----+------------+---------------+-----------------+
2 rows in set (0.001 sec)

Creating Temporary table


MariaDB [test]> create temporary table MyEmp
-> (
-> empid integer,
-> fname varchar(10)
-> );
Query OK, 0 rows affected (0.035 sec)

MariaDB [test]> insert into MyEmp values(1,'Shravan');


Query OK, 1 row affected (0.001 sec)

MariaDB [test]> commit;


Query OK, 0 rows affected (0.000 sec)

MariaDB [test]> exit

Cloning a table
MariaDB [test]> select * from gm_employee;
+-------------+------------+-----------+----------+--------------+------------+---------+--------+------------
----+------------+---------------+-----------------+
| Employee_ID | First_Name | Last_name | Email | Phone_number | Hire_Date | Job_id |
Salary | Commission_pct | Manager_id | Department_id | Department_name |
+-------------+------------+-----------+----------+--------------+------------+---------+--------+------------
----+------------+---------------+-----------------+
| 100 | Steven | King | SKING | 515.123.4567 | 2019-02-22 | AD_ASST | 66000 |
0| NULL | 90 | Executive |
| 101 | Abhijeet | Kochhar | NKOCHHAR | 515.123.4568 | 0000-00-00 | AD_VP |
37400 | 0| 100 | 90 | Executive |
| 102 | priya | De Haan | LDEHAAN | 515.123.4569 | 2020-02-28 | AD_VP | 37400 |
0| 100 | 90 | Executive |
| 103 | Alexander | Hunold | AHUNOLD | 590.423.4567 | 2020-02-28 | IT_PROG |
495000 | 0| 102 | 60 | FORD |
| 104 | Bruce | Ernst | BERNST | 590.423.4568 | 2020-02-28 | IT_PROG | 13200 |
0| 103 | 22 | NULL |
+-------------+------------+-----------+----------+--------------+------------+---------+--------+------------
----+------------+---------------+-----------------+
5 rows in set (0.004 sec)
18th May 2023

-- DCL : data Control language


-- grant, revoke, create user, alter user
-- creating a user
create user shravan identified by shravan123;
grant resource to shravan;

-- granting permission to the user


grant create session to shravan;
grant insert, update, delete
on gm_employee
to shravan;

grant select
on gm_employee
to shravan;

-- Taking back the privilege


revoke update
on gm_employee
from shravan;

--to change the password


alter user shravan identified by shravan12;

-- TCL commands
-- commit
-- rollback

drop user shravan;

-- User shravan fires the commands

update apps.gm_employee
set salary = 90000
where employee_id = 120;

-- TCL command : commit : saves the data permanently in the database.


commit;

update apps.gm_employee
set salary = 50000
where employee_id = 121;
select * from apps.gm_employee where employee_id = 121;

-- rollback : undoes the transaction.


-- It will undo the changes that have not been committed.
rollback;

update apps.gm_employee
set salary = 50000
where employee_id = 121; -- "insufficient privileges"

-- Show user names


mysql> select user
-> from mysql.user;

mysql> show grants;


+--------------------------------------+
| Grants for @localhost |
+--------------------------------------+
| GRANT USAGE ON *.* TO ''@'localhost' |
+--------------------------------------+
1 row in set (0.00 sec)

-- Creating a dump
mysql> mysqldump --user=root --password=NO --result-file=test.sql test

-- Taking backup
mysql> mysqlhotcopy --user=root --password=NO test test_backup;

--Check status of a table


mysql> check table test.gm_employee;
+------------------+-------+----------+----------+
| Table | Op | Msg_type | Msg_text |
+------------------+-------+----------+----------+
| test.gm_employee | check | status | OK |
+------------------+-------+----------+----------+
1 row in set (0.02 sec)

MariaDB [test]> create table Sh_Employee as select * from gm_employee;


Query OK, 5 rows affected, 1 warning (0.277 sec)
Records: 5 Duplicates: 0 Warnings: 1

MariaDB [test]> select *


-> from Sh_employee;
+-------------+------------+-----------+----------+--------------+------------+---------+--------+------------
----+------------+---------------+-----------------+
| Employee_ID | First_Name | Last_name | Email | Phone_number | Hire_Date | Job_id |
Salary | Commission_pct | Manager_id | Department_id | Department_name |
+-------------+------------+-----------+----------+--------------+------------+---------+--------+------------
----+------------+---------------+-----------------+
| 100 | Steven | King | SKING | 515.123.4567 | 2019-02-22 | AD_ASST | 66000 |
0| NULL | 90 | Executive |
| 101 | Abhijeet | Kochhar | NKOCHHAR | 515.123.4568 | 0000-00-00 | AD_VP |
37400 | 0| 100 | 90 | Executive |
| 102 | priya | De Haan | LDEHAAN | 515.123.4569 | 2020-02-28 | AD_VP | 37400 |
0| 100 | 90 | Executive |
| 103 | Alexander | Hunold | AHUNOLD | 590.423.4567 | 2020-02-28 | IT_PROG |
495000 | 0| 102 | 60 | FORD |
| 104 | Bruce | Ernst | BERNST | 590.423.4568 | 2020-02-28 | IT_PROG | 13200 |
0| 103 | 22 | NULL |
+-------------+------------+-----------+----------+--------------+------------+---------+--------+------------
----+------------+---------------+-----------------+
5 rows in set (0.001 sec)

MariaDB [test]> create table Sh_Employee2 as select * from gm_employee where 1= 2;


Query OK, 0 rows affected (0.231 sec)
Records: 0 Duplicates: 0 Warnings: 0

MariaDB [test]> select *


-> from Sh_employee2;
Empty set (0.001 sec)

MariaDB [test]> desc Sh_employee2;


+-----------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+-------------+------+-----+---------+-------+
| Employee_ID | int(11) | YES | | NULL | |
| First_Name | varchar(20) | YES | | NULL | |
| Last_name | varchar(25) | YES | | NULL | |
| Email | varchar(25) | YES | | NULL | |
| Phone_number | varchar(20) | YES | | NULL | |
| Hire_Date | date | YES | | NULL | |
| Job_id | varchar(10) | YES | | NULL | |
| Salary | int(11) | YES | | NULL | |
| Commission_pct | int(11) | YES | | NULL | |
| Manager_id | int(11) | YES | | NULL | |
| Department_id | int(11) | YES | | NULL | |
| Department_name | varchar(30) | YES | | NULL | |
+-----------------+-------------+------+-----+---------+-------+
12 rows in set (0.088 sec)
MariaDB [test]> create table Sh_Employee3 as select employee_id, first_name, salary from
gm_employee where 1= 2;
Query OK, 0 rows affected (0.242 sec)
Records: 0 Duplicates: 0 Warnings: 0

MariaDB [test]> desc Sh_employee3;


+-------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| employee_id | int(11) | YES | | NULL | |
| first_name | varchar(20) | YES | | NULL | |
| salary | int(11) | YES | | NULL | |
+-------------+-------------+------+-----+---------+-------+
3 rows in set (0.006 sec)

MariaDB [test]> select *


-> from Sh_employee3;
Empty set (0.001 sec)

Date and Time Functions


29th May 2023

mysql> use test;


Database changed
mysql> SELECT DAYOFMONTH('2001-11-00'), MONTH('2005-00-00');
+--------------------------+---------------------+
| DAYOFMONTH('2001-11-00') | MONTH('2005-00-00') |
+--------------------------+---------------------+
| 0| 0|
+--------------------------+---------------------+
1 row in set (0.00 sec)

mysql> SELECT DAYOFMONTH('2001-11-12'), MONTH('2005-00-02');


+--------------------------+---------------------+
| DAYOFMONTH('2001-11-12') | MONTH('2005-00-02') |
+--------------------------+---------------------+
| 12 | 0|
+--------------------------+---------------------+
1 row in set (0.00 sec)

mysql> SELECT DAYOFMONTH('2001-11-12'), MONTH('2005-10-02');


+--------------------------+---------------------+
| DAYOFMONTH('2001-11-12') | MONTH('2005-10-02') |
+--------------------------+---------------------+
| 12 | 10 |
+--------------------------+---------------------+
1 row in set (0.00 sec)

mysql> SELECT DATE_ADD('2006-05-00',INTERVAL 1 DAY);


+---------------------------------------+
| DATE_ADD('2006-05-00',INTERVAL 1 DAY) |
+---------------------------------------+
| NULL |
+---------------------------------------+
1 row in set, 1 warning (0.00 sec)

mysql> SELECT DATE_ADD('2006-05-00',INTERVAL 31 DAY);


+----------------------------------------+
| DATE_ADD('2006-05-00',INTERVAL 31 DAY) |
+----------------------------------------+
| NULL |
+----------------------------------------+
1 row in set, 1 warning (0.00 sec)

mysql> SELECT DATE_ADD('2006-05-01',INTERVAL 31 DAY);


+----------------------------------------+
| DATE_ADD('2006-05-01',INTERVAL 31 DAY) |
+----------------------------------------+
| 2006-06-01 |
+----------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT ADDTIME('2007-12-31 23:59:59.999999', '1 1:1:1.000002');


+---------------------------------------------------------+
| ADDTIME('2007-12-31 23:59:59.999999', '1 1:1:1.000002') |
+---------------------------------------------------------+
| 2008-01-02 01:01:01.000001 |
+---------------------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT CURDATE();


+------------+
| CURDATE() |
+------------+
| 2023-05-29 |
+------------+
1 row in set (0.00 sec)

mysql> SELECT CURTIME();


+-----------+
| CURTIME() |
+-----------+
| 20:04:19 |
+-----------+
1 row in set (0.00 sec)

mysql> SELECT DATE('2003-12-31 01:02:03');


+-----------------------------+
| DATE('2003-12-31 01:02:03') |
+-----------------------------+
| 2003-12-31 |
+-----------------------------+
1 row in set (0.00 sec)

mysql> SELECT DATEDIFF('2007-12-31 23:59:59','2007-12-30');


+----------------------------------------------+
| DATEDIFF('2007-12-31 23:59:59','2007-12-30') |
+----------------------------------------------+
| 1|
+----------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT DATEDIFF('2007-12-31','2007-12-30');


+-------------------------------------+
| DATEDIFF('2007-12-31','2007-12-30') |
+-------------------------------------+
| 1|
+-------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT DATEDIFF('2007-11-31','2007-12-30');


+-------------------------------------+
| DATEDIFF('2007-11-31','2007-12-30') |
+-------------------------------------+
| NULL |
+-------------------------------------+
1 row in set, 1 warning (0.00 sec)

mysql> SELECT DATEDIFF('2007-11-30','2007-12-30');


+-------------------------------------+
| DATEDIFF('2007-11-30','2007-12-30') |
+-------------------------------------+
| -30 |
+-------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT DATE_SUB('2018-05-01',INTERVAL 1 YEAR);


+----------------------------------------+
| DATE_SUB('2018-05-01',INTERVAL 1 YEAR) |
+----------------------------------------+
| 2017-05-01 |
+----------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT DATE_ADD('2018-05-01',INTERVAL 1 DAY);


+---------------------------------------+
| DATE_ADD('2018-05-01',INTERVAL 1 DAY) |
+---------------------------------------+
| 2018-05-02 |
+---------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT DATE_FORMAT('2009-10-04 22:23:00', '%W %M %Y');


+------------------------------------------------+
| DATE_FORMAT('2009-10-04 22:23:00', '%W %M %Y') |
+------------------------------------------------+
| Sunday October 2009 |
+------------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT DATE_FORMAT('2009-10-04 22:23:00', '%W %M %Y');


+------------------------------------------------+
| DATE_FORMAT('2009-10-04 22:23:00', '%W %M %Y') |
+------------------------------------------------+
| Sunday October 2009 |
+------------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT DATE_FORMAT('1997-10-04 22:23:00','%H %k %I %r %T %S %w');


+-----------------------------------------------------------+
| DATE_FORMAT('1997-10-04 22:23:00','%H %k %I %r %T %S %w') |
+-----------------------------------------------------------+
| 22 22 10 10:23:00 PM 22:23:00 00 6 |
+-----------------------------------------------------------+
1 row in set (0.00 sec)

| 157 |
+-------------------------+
1 row in set (0.00 sec)
6th June 2023

mysql> SELECT EXTRACT(YEAR FROM '2019-07-02');


+---------------------------------+
| EXTRACT(YEAR FROM '2019-07-02') |
+---------------------------------+
| 2019 |
+---------------------------------+
1 row in set (0.00 sec)

mysql> SELECT EXTRACT(YEAR_MONTH FROM '2019-07-02 01:02:03');


+------------------------------------------------+
| EXTRACT(YEAR_MONTH FROM '2019-07-02 01:02:03') |
+------------------------------------------------+
| 201907 |
+------------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT FROM_DAYS(157);


+----------------+
| FROM_DAYS(157) |
+----------------+
| 0000-00-00 |
+----------------+
1 row in set (0.00 sec)

mysql> SELECT FROM_DAYS(160);


+----------------+
| FROM_DAYS(160) |
+----------------+
| 0000-00-00 |
+----------------+
1 row in set (0.00 sec)

mysql> SELECT FROM_DAYS(56789);


+------------------+
| FROM_DAYS(56789) |
+------------------+
| 0155-06-26 |
+------------------+
1 row in set (0.00 sec)

mysql> SELECT HOUR('10:05:03');


+------------------+
| HOUR('10:05:03') |
+------------------+
| 10 |
+------------------+
1 row in set (0.00 sec)

mysql> SELECT LAST_DAY('2003-02-05');


+------------------------+
| LAST_DAY('2003-02-05') |
+------------------------+
| 2003-02-28 |
+------------------------+
1 row in set (0.00 sec)

mysql> SELECT MONTH('2008-02-03');


+---------------------+
| MONTH('2008-02-03') |
+---------------------+
| 2|
+---------------------+
1 row in set (0.00 sec)

mysql> SELECT NOW();


+---------------------+
| NOW() |
+---------------------+
| 2023-06-06 19:20:13 |
+---------------------+
1 row in set (0.00 sec)

mysql> SELECT PERIOD_DIFF(200802,200703);


+----------------------------+
| PERIOD_DIFF(200802,200703) |
+----------------------------+
| 11 |
+----------------------------+
1 row in set (0.00 sec)

mysql> SELECT PERIOD_ADD(200801,2);


+----------------------+
| PERIOD_ADD(200801,2) |
+----------------------+
| 200803 |
+----------------------+
1 row in set (0.00 sec)

mysql> SELECT PERIOD_DIFF(200802,200903);


+----------------------------+
| PERIOD_DIFF(200802,200903) |
+----------------------------+
| -13 |
+----------------------------+
1 row in set (0.00 sec)

mysql> SELECT QUARTER('2008-04-01');


+-----------------------+
| QUARTER('2008-04-01') |
+-----------------------+
| 2|
+-----------------------+
1 row in set (0.00 sec)

mysql> SELECT PERIOD_ADD('2008-01-09',2);


+----------------------------+
| PERIOD_ADD('2008-01-09',2) |
+----------------------------+
| 202010 |
+----------------------------+
1 row in set, 1 warning (0.00 sec)

mysql> SELECT PERIOD_ADD(200801,2);


+----------------------+
| PERIOD_ADD(200801,2) |
+----------------------+
| 200803 |
+----------------------+
1 row in set (0.00 sec)

mysql> SELECT PERIOD_ADD(20080108,2);


+------------------------+
| PERIOD_ADD(20080108,2) |
+------------------------+
| 20080110 |
+------------------------+
1 row in set (0.00 sec)

mysql> SELECT PERIOD_ADD(20080108,-2);


+-------------------------+
| PERIOD_ADD(20080108,-2) |
+-------------------------+
| 20080106 |
+-------------------------+
1 row in set (0.00 sec)
mysql> SELECT DATE_SUB('2008-01-02', INTERVAL 31 DAY);
+-----------------------------------------+
| DATE_SUB('2008-01-02', INTERVAL 31 DAY) |
+-----------------------------------------+
| 2007-12-02 |
+-----------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT SUBDATE('2008-01-02', INTERVAL 31 DAY);


+----------------------------------------+
| SUBDATE('2008-01-02', INTERVAL 31 DAY) |
+----------------------------------------+
| 2007-12-02 |
+----------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT TIME('2003-12-31 01:02:03');


+-----------------------------+
| TIME('2003-12-31 01:02:03') |
+-----------------------------+
| 01:02:03 |
+-----------------------------+
1 row in set (0.00 sec)

mysql> SELECT TIMEDIFF('2000-01-01 00:00:00','2000-01-01 00:00:00.000001');


+--------------------------------------------------------------+
| TIMEDIFF('2000-01-01 00:00:00','2000-01-01 00:00:00.000001') |
+--------------------------------------------------------------+
| -00:00:00.000001 |
+--------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT TIMEDIFF('2000-01-01 00:00:000010','2000-01-01 00:00:00.000001');


+------------------------------------------------------------------+
| TIMEDIFF('2000-01-01 00:00:000010','2000-01-01 00:00:00.000001') |
+------------------------------------------------------------------+
| 00:00:09.999999 |
+------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT TIMESTAMP('2003-12-31');


+-------------------------+
| TIMESTAMP('2003-12-31') |
+-------------------------+
| 2003-12-31 00:00:00 |
+-------------------------+
1 row in set (0.00 sec)

mysql> SELECT TIMESTAMP('2003-12-31 12:00:00','12:00:00');


+---------------------------------------------+
| TIMESTAMP('2003-12-31 12:00:00','12:00:00') |
+---------------------------------------------+
| 2004-01-01 00:00:00 |
+---------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT TIMESTAMP('2003-12-31 12:00:00','1:00:00');


+--------------------------------------------+
| TIMESTAMP('2003-12-31 12:00:00','1:00:00') |
+--------------------------------------------+
| 2003-12-31 13:00:00 |
+--------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT TIMESTAMP('2003-12-31 12:00:00','4:00:00');


+--------------------------------------------+
| TIMESTAMP('2003-12-31 12:00:00','4:00:00') |
+--------------------------------------------+
| 2003-12-31 16:00:00 |
+--------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT TIMESTAMPADD(MINUTE, 1, '2003-01-02');


+---------------------------------------+
| TIMESTAMPADD(MINUTE, 1, '2003-01-02') |
+---------------------------------------+
| 2003-01-02 00:01:00 |
+---------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT TIMESTAMPADD(WEEK,1,'2003-01-02');


+-----------------------------------+
| TIMESTAMPADD(WEEK,1,'2003-01-02') |
+-----------------------------------+
| 2003-01-09 |
+-----------------------------------+
1 row in set (0.00 sec)

mysql> SELECT TIMESTAMPDIFF(MONTH,'2003-02-01','2003-05-01');


+------------------------------------------------+
| TIMESTAMPDIFF(MONTH,'2003-02-01','2003-05-01') |
+------------------------------------------------+
| 3|
+------------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT TIMESTAMPDIFF(YEAR,'2002-05-01','2001-01-01');


+-----------------------------------------------+
| TIMESTAMPDIFF(YEAR,'2002-05-01','2001-01-01') |
+-----------------------------------------------+
| -1 |
+-----------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT TIMESTAMPDIFF(MINUTE,'2003-02-01','2003-05-01 12:05:55');


+----------------------------------------------------------+
| TIMESTAMPDIFF(MINUTE,'2003-02-01','2003-05-01 12:05:55') |
+----------------------------------------------------------+
| 128885 |
+----------------------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT TIME_TO_SEC('22:23:00');


+-------------------------+
| TIME_TO_SEC('22:23:00') |
+-------------------------+
| 80580 |
+-------------------------+
1 row in set (0.00 sec)

mysql> SELECT TO_SECONDS(950501);


+--------------------+
| TO_SECONDS(950501) |
+--------------------+
| 62966505600 |
+--------------------+
1 row in set (0.00 sec)

mysql> SELECT TO_SECONDS(TIMESTAMPDIFF(MONTH,'2003-02-01','2003-05-01'));


+------------------------------------------------------------+
| TO_SECONDS(TIMESTAMPDIFF(MONTH,'2003-02-01','2003-05-01')) |
+------------------------------------------------------------+
| NULL |
+------------------------------------------------------------+
1 row in set, 1 warning (0.00 sec)

mysql> SELECT TO_SECONDS(TIMESTAMPDIFF(MINUTE,'2003-02-01','2003-05-01


12:05:55'
));
+----------------------------------------------------------------------+
| TO_SECONDS(TIMESTAMPDIFF(MINUTE,'2003-02-01','2003-05-01 12:05:55')) |
+----------------------------------------------------------------------+
| NULL |
+----------------------------------------------------------------------+
1 row in set, 1 warning (0.00 sec)

mysql> SELECT TO_SECONDS(TIMESTAMPDIFF(MINUTE,'2003-02-01 11:00:00','2003-


05-01
12:05:55'));
+-------------------------------------------------------------------------------
+
| TO_SECONDS(TIMESTAMPDIFF(MINUTE,'2003-02-01 11:00:00','2003-05-01 12:05:55'))
|
+-------------------------------------------------------------------------------
+
| NULL
|
+-------------------------------------------------------------------------------
+
1 row in set, 1 warning (0.00 sec)

mysql> SELECT UTC_DATE(), UTC_DATE();


+------------+------------+
| UTC_DATE() | UTC_DATE() |
+------------+------------+
| 2023-06-06 | 2023-06-06 |
+------------+------------+
1 row in set (0.00 sec)

mysql> SELECT UTC_DATE();


+------------+
| UTC_DATE() |
+------------+
| 2023-06-06 |
+------------+
1 row in set (0.00 sec)

mysql> SELECT STR_TO_DATE('10.31.2003',GET_FORMAT(DATE,'USA'));


+--------------------------------------------------+
| STR_TO_DATE('10.31.2003',GET_FORMAT(DATE,'USA')) |
+--------------------------------------------------+
| 2003-10-31 |
+--------------------------------------------------+
1 row in set (0.00 sec)
mysql> SELECT WEEK('2008-02-20');
+--------------------+
| WEEK('2008-02-20') |
+--------------------+
| 7|
+--------------------+
1 row in set (0.00 sec)

mysql> SELECT WEEKDAY('2007-11-06');


+-----------------------+
| WEEKDAY('2007-11-06') |
+-----------------------+
| 1|
+-----------------------+
1 row in set (0.01 sec)

mysql> SELECT WEEKOFYEAR('2008-02-20');


+--------------------------+
| WEEKOFYEAR('2008-02-20') |
+--------------------------+
| 8|
+--------------------------+
1 row in set (0.00 sec)

mysql> SELECT WEEK('2008-02-20') - WEEK('2008-04-05');


+-----------------------------------------+
| WEEK('2008-02-20') - WEEK('2008-04-05') |
+-----------------------------------------+
| -6 |
+-----------------------------------------+
1 row in set (0.00 sec)

14th June 2023


Set Operators
s1 : 19,89,78,90
s2 : 19,78,100,123
s1 union s2 : 19,89,78,90,100,123
s1 union all s2 : 19,89,78,19,78,90,100,123
s1 intersect s2 : 19,78
s1 minus s2 : 89,90
s2 minus s1 : 100,123
NVL : stands for Null value locator
Syntax : NVL(EXPR1,EXPR2)
If EXPR1 is Null, then output is EXPR2 else output is EXPR1

select first_name,nvl(first_name, 'No name')


from gm_employee;

NVL2
Syntax : NVL2(EXPR1,EXPR2, EXPR3)
If EXPR1 is not Null, then output is EXPR2 else output is EXPR3

select first_name,nvl2(first_name, 'Name present','No name')


from gm_employee;

COALESCE: Returns the first value in the list which is not null.

select coalesce(Null,'Jim','Tom')
from gm_employee;

select coalesce(Null,'Jim',Null,'Tom')
from gm_employee;

NULLIF: Takes two parameters. If both parameters have the same value, then output is Null
Else output is the first parameter

select nullif(10,10)
from dual;

select nullif(10,100)
from dual;

select nullif(10,10)
from dual;

select nullif(10,100)
from dual;

select nullif(null,100)
from dual;

select nullif(100,null)
from dual;

select nullif(100,'ppp')
from dual;

select nullif(100,100.2)
from dual;

--Nullif throws error if datatypes dont match.

mysql> use test;


Database changed
mysql> select * from depts;
+---------+-----------+--------+
| dept_id | dept_name | loc_id |
+---------+-----------+--------+
| 2 | IT | 5|
| 10 | HR | 5|
| 30 | Marketing | 10 |
| 30 | Finance | NULL |
+---------+-----------+--------+
4 rows in set (0.00 sec)

mysql> select loc_id,


-> case loc_id
-> when 5 then 1000
-> when 10 then 2000
-> else 4000
-> end "Answer"
-> from depts;
+--------+--------+
| loc_id | Answer |
+--------+--------+
| NULL | 4000 |
| 5 | 1000 |
| 5 | 1000 |
| 10 | 2000 |
+--------+--------+
4 rows in set (0.00 sec)

mysql> select loc_id,


-> case dept_name
-> when 'IT' then 'Information'
-> when 'HR' then 'Human Resource'
-> end "Answer"
-> from depts;
+--------+----------------+
| loc_id | Answer |
+--------+----------------+
| 5 | Information |
| 5 | Human Resource |
| 10 | NULL |
| NULL | NULL |
+--------+----------------+
4 rows in set (0.00 sec)

mysql> select loc_id,dept_name,


-> case dept_name
-> when 'IT' then 'Information'
-> when 'HR' then 'Human Resource'
-> end "Answer"
-> from depts;
+--------+-----------+----------------+
| loc_id | dept_name | Answer |
+--------+-----------+----------------+
| 5 | IT | Information |
| 5 | HR | Human Resource |
| 10 | Marketing | NULL |
| NULL | Finance | NULL |
+--------+-----------+----------------+
4 rows in set (0.00 sec)

mysql> create table depts2 as select * from depts ;


Query OK, 4 rows affected (0.31 sec)
Records: 4 Duplicates: 0 Warnings: 0

mysql> insert into depts2 value(11,'Production',8);


Query OK, 1 row affected (0.04 sec)

mysql> insert into depts2 value(12,'Design',9);


Query OK, 1 row affected (0.05 sec)

mysql> commit;
Query OK, 0 rows affected (0.00 sec)

mysql> select * from depts2;


+---------+------------+--------+
| dept_id | dept_name | loc_id |
+---------+------------+--------+
| 2 | IT | 5|
| 10 | HR | 5|
| 30 | Marketing | 10 |
| 30 | Finance | NULL |
| 11 | Production | 8 |
| 12 | Design | 9 |
+---------+------------+--------+
6 rows in set (0.00 sec)

mysql> select * from depts;


+---------+-----------+--------+
| dept_id | dept_name | loc_id |
+---------+-----------+--------+
| 2 | IT | 5|
| 10 | HR | 5|
| 30 | Marketing | 10 |
| 30 | Finance | NULL |
+---------+-----------+--------+
4 rows in set (0.00 sec)

mysql> select loc_id from depts2


-> union
-> select loc_id from depts;
+--------+
| loc_id |
+--------+
| 5|
| 10 |
| NULL |
| 8|
| 9|
+--------+
5 rows in set (0.00 sec)

mysql> select loc_id from depts2


-> union all
-> select loc_id from depts;
+--------+
| loc_id |
+--------+
| 5|
| 5|
| 10 |
| NULL |
| 8|
| 9|
| NULL |
| 5|
| 5|
| 10 |
+--------+
10 rows in set (0.00 sec)

mysql> select loc_id from depts2


-> intersect
-> select loc_id from depts;

mysql> select loc_id from depts2


-> minus
-> select loc_id from depts;

select employee_id
from gm_employee
where LNNVL(employee_id > 105) ;

select NANVL(Null,90)
from gm_employee;

select NANVL(100,90)
from gm_employee;

select NANVL(100,'67')
from gm_employee;

select first_name , last_name, first_name || ' ' || last_name


from gm_employee;

select concat(first_name , last_name)


from gm_employee;

MySQL UPSERT
Date : 21st June 2023
UPSERT is one of the essential features of DBMS software for managing the database. This
operation allows the DML users to insert a new record or update existing data into a table. An
UPSERT is made up of a combination of two words named UPDATE and INSERT. The first two
letters, i.e., UP stands for UPDATE while the SERT stands for INSERT. The UPSERT is an atomic
operation that means it is an operation that completes in a single-step. For example, if a record is
new, it will trigger an INSERT command. But, if it already exists in the table, then this operation
will perform an UPDATE statement.
By default, MySQL provides the ON DUPLICATE KEY UPDATE option to INSERT, which
accomplishes this task. However, it also contains some other statements to fulfill this objective,
such as INSERT IGNORE or REPLACE. We will learn and see all these solutions in detail.
MySQL UPSERT Example
We can perform MySQL UPSERT operation mainly in three ways, which are as follows:
1. UPSERT using INSERT IGNORE
2. UPSERT using REPLACE
3. UPSERT using INSERT ON DUPLICATE KEY UPDATE
UPSERT using INSERT IGNORE
INSERT IGNORE statement is used to ignore our execution errors when we perform an insert
operation of invalid rows. For example, the primary key column cannot allow us to store duplicate
values. If we try to insert a new record with the same primary key that already exists in the table,
we will get an error. However, if we perform this action with the INSERT IGNORE command, it
will generate a warning instead of an error.
Syntax
The following are syntax to use the INSERT IGNORE statement in MySQL:
1. INSERT IGNORE INTO table_name (column_names)
2. VALUES ( value_list), ( value_list) .....;
MySQL INSERT IGNORE Example
Let us understand the working of the INSERT IGNORE statement in MySQL. First, we need to
create a table named "Student" using the following statement:
1. CREATE TABLE Student (
2. Stud_ID int AUTO_INCREMENT PRIMARY KEY,
3. Name varchar(45) DEFAULT NULL,
4. Email varchar(45) NOT NULL UNIQUE,
5. City varchar(25) DEFAULT NULL
6. );
The UNIQUE constraint ensures that we cannot keep duplicate values into the email column. Next,
it is required to insert the records into the table. The below statement is used to add data into a
table:
1. INSERT INTO Student(Stud_ID, Name, Email, City)
2. VALUES (1,'Stephen', '[email protected]', 'Texas'),
3. (2, 'Joseph', '[email protected]', 'Alaska'),
4. (3, 'Peter', '[email protected]', 'California');
Now, we can verify the insert operation by using the SELECT statement:
1. mysql> SELECT * FROM Student;
We will get the below output where we have three rows into the table:

Now, we are going to execute the below statement to add two records into the table:
1. INSERT INTO Student(Stud_ID, Name, Email, City)
2. VALUES (4,'Donald', '[email protected]', 'New York'),
3. (5, 'Joseph', '[email protected]', 'Chicago');
After the above statement's execution, we will see the error: ERROR 1062 (23000): Duplicate
entry '[email protected]' for key 'student.Email' because of the email violets the UNIQUE
constraint.
But, when we perform the same statement using the INSERT IGNORE command, we have not
received any error. Instead, we receive a warning only.
1. INSERT IGNORE INTO Student(Stud_ID, Name, Email, City)
2. VALUES (4,'Donald', '[email protected]', 'New York'),
3. (5, 'Joseph', '[email protected]', 'Chicago');
MySQL will produce a message: one row added, and the other row was ignored.
1. 1 row affected, 1 warning(s): 1062 Duplicate entry for key email.
2. Records: 2 Duplicates: 1 Warning: 1
We can see the detailed warning using the SHOW WARNINGS command:

Thus, if there are some duplicates and we use the INSERT IGNORE statement, MySQL gives a
warning instead of issuing an error and will add the remaining records to the table.
UPSERT using REPLACE
In some situations, we want to update the existing records into the table to keep them updated. If
we use the standard insert query for this purpose, it will give a Duplicate entry for PRIMARY
KEY error. In this case, we will use the REPLACE statement to perform our task. When we use
the REPLACE command, there are two possible events take place:
o If no matching value is found with the existing data row, then a standard INSERT statement
is performed.
o If the old record matches the new record, the replace command will delete the existing row,
and then a normal INSERT statement is executed that adds the new record in the table.
In the REPLACE statement, the updation performed in two steps. First, it will delete the existing
record, and then the newly updated record is added, similar to a standard INSERT command. Thus,
we can say that the REPLACE statement performs two standard functions, DELETE and INSERT.
The syntax of REPLACE statement in MySQL is as follows:
1. REPLACE [INTO] table_name(column_list)
2. VALUES(value_list);
Example
Let us understand it with the help of a real example. Here, we will take a Student table that we
have created earlier that contains the following data:

Now, we will use the REPLACE statement to update the city of the student whose id = 2 with the
new city Los Angeles. To do this, execute the following statement:
1. REPLACE INTO Student(Stud_ID, Name, Email, City)
2. VALUES(2, 'Joseph', '[email protected]', 'Los Angeles');
After the successful execution, we will get the output as below:

In the above image, we can see the message that says "2 row(s) affected" while we have updated
the values of a single row only. It is because the REPLACE command first deleted the record, and
then the added the new record into the table. Hence the message says, "2 row(s) affected."
UPSERT using INSERT ON DUPLICATE KEY UPDATE
We have seen the two UPSERT commands so far, but they had some limitations. The INSERT
IGNORE statement only ignores the duplicate error without making any modification to the table.
And the REPLACE method detected the INSERT error, but it will delete the row before adding
the new record. Hence, we are still searching for a more refined solution until now.
So, we use a more refined solution as the INSERT ON DUPLICATE KEY UPDATE statement.
It is a non-destructive method that means it does not remove the duplicate row. Instead, when we
specify the ON DUPLICATE KEY UPDATE clause in a SQL statement and a row would cause
duplicate error value in a UNIQUE or PRIMARY KEY index column, then updation of the existing
row occurs.
The syntax of Insert on Duplicate Key Update statement in MySQL is given below:
1. INSERT INTO table (column_names)
2. VALUES (data)
3. ON DUPLICATE KEY UPDATE
4. column1 = expression, column2 = expression...;
Example
Let us understand it with the help of a real example. Here, we will take a Student table that we
have created earlier. Now, add one more row into the table using the below query:
1. INSERT INTO Student(Stud_ID, Name, Email, City)
2. VALUES (4,'John', '[email protected]', 'New York');
This query will add one record successfully into the table because it does not have any duplicate
values.

Next, execute the below MySQL UPSERT command that updated the duplicate record in
the Stud_ID column:
1. INSERT INTO Student(Stud_ID, Name, Email, City)
2. VALUES (4, 'John', '[email protected]', 'New York')
3. ON DUPLICATE KEY UPDATE City = 'California';
After successful execution, MySQL gives the following message:
1. Query OK, 2 rows affected.
In the output, we can see that the row id=4 already exists. So the query only updates the City New
York with California.

CREATE TABLE Student (


Stud_ID int AUTO_INCREMENT PRIMARY KEY,
Name varchar(45) DEFAULT NULL,
Email varchar(45) NOT NULL UNIQUE,
City varchar(25) DEFAULT NULL
);

INSERT INTO Student(Stud_ID, Name, Email, City)


VALUES (1,'Stephen', '[email protected]', 'Texas'),
(2, 'Joseph', '[email protected]', 'Alaska'),
(3, 'Peter', '[email protected]', 'California');

INSERT INTO Student(Stud_ID, Name, Email, City)


VALUES (4,'Donald', '[email protected]', 'New York'),
(5, 'Joseph', '[email protected]', 'Chicago');

REPLACE INTO Student(Stud_ID, Name, Email, City)


VALUES(2, 'Joseph', '[email protected]', 'Los Angeles');

INSERT INTO Student(Stud_ID, Name, Email, City)


VALUES (4,'John', '[email protected]', 'New York');

INSERT INTO Student(Stud_ID, Name, Email, City)


VALUES (4, 'John', '[email protected]', 'New York')
ON DUPLICATE KEY UPDATE City = 'California';

CTE
WITH student_in_newyork AS (
SELECT * FROM Student WHERE city = 'California'
)
SELECT stud_id , name, email, city FROM student_in_newyork
WHERE stud_id <= 4 ORDER BY name;

Example of Recursion
Factorial of a number
5! = 5 * 4!
4! = 4 * 3!
3! = 3* 2!
2! = 2 * 1!
1! = 1 * 0!
0! =1

WITH RECURSIVE
odd_num_cte (id, n) AS
(
SELECT 1, 1
union all
SELECT id+1, n+2 from odd_num_cte where id < 5
)
SELECT * FROM odd_num_cte;

MySQL ON DELETE CASCADE

Use the ON DELETE CASCADE option if you want rows deleted in the child table when
corresponding rows are deleted in the parent table. If you do not specify cascading deletes, the
default behavior of the database server prevents you from deleting data in a table if other tables
reference it.
If you specify this option, when you delete a row in the parent table, the database server also
deletes any rows associated with that row (foreign keys) in a child table. The advantage of
the ON DELETE CASCADE option is that it allows you to reduce the quantity of SQL
statements needed to perform delete actions.
MySQL ON UPDATE CASCADE
Use the ON UPDATE CASCADE option if you want rows update in the child table when
corresponding rows are updated in the parent table. If you do not specify cascading updates, the
default behavior of the database server prevents you from updating data in a table if other tables
reference it.
-- Correlated Subquery

-- In a Subquery, first inner query executes and sends output to the outer query
-- Based on this output, the outer query executes
-- In Correlated subquery, the outer query sends input to the inner query
-- Based on this input , the row gets selected or rejected
-- This process repeats for all rows in the table.
-- Inner query executes n times.

A correlated subquery is a subquery that uses the values from the outer query. Also, a correlated
subquery may be evaluated once for each row selected by the outer query. Because of this, a
query that uses a correlated subquery may be slow.

A correlated subquery is also known as a repeating subquery or a synchronized subquery.

create table gm_emps


(
empno integer,
lastname varchar(20),
workdept integer,
edlevel integer
);

insert into gm_emps values(1,'A',10,12);


insert into gm_emps values(2,'B',10,14);
insert into gm_emps values(3,'C',10,16);
insert into gm_emps values(4,'D',20,13);
insert into gm_emps values(5,'E',20,14);
insert into gm_emps values(6,'K',20,14);
insert into gm_emps values(7,'F',30,14);
insert into gm_emps values(8,'G',30,12);
insert into gm_emps values(9,'H',30,14);
insert into gm_emps values(10,'B',40,14);
commit;

rollback;
-- Find out the names of those employee whose edlevel is greater than the
-- average of the edlevel in the department which they are working
select * from gm_emps;

select workdept , avg(edlevel)


from gm_emps
group by workdept;

-- 30 13.3
-- 20 13.6
--40 14
--10 14

--Correlated Subquery is
SELECT EMPNO, LASTNAME, WORKDEPT, EDLEVEL
FROM gm_emps X
WHERE EDLEVEL >
(SELECT AVG(EDLEVEL)
FROM gm_emps
WHERE WORKDEPT = X.WORKDEPT);

You might also like