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

MySQL Basics - A Comprehensive Guide To DDL and DML With Practical Examples

Uploaded by

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

MySQL Basics - A Comprehensive Guide To DDL and DML With Practical Examples

Uploaded by

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

MySQL Basics

A Comprehensive Guide to DDL and DML


with Practical Examples
Part 1: Data Definition Language (DDL)------------------------------------------------------------------------- 3
1.1 The CREATE Command----------------------------------------------------------------------------------- 3
1.2 The ALTER Command--------------------------------------------------------------------------------------4
1.3 The DROP Command-------------------------------------------------------------------------------------- 5
1.4 The TRUNCATE Command------------------------------------------------------------------------------- 5
1.5 The RENAME Command---------------------------------------------------------------------------------- 5
Part 2: Data Manipulation Language (DML)-------------------------------------------------------------------- 6
2.1 The INSERT Command------------------------------------------------------------------------------------ 6
Implicit Insert-------------------------------------------------------------------------------------------------- 6
Explicit Insert-------------------------------------------------------------------------------------------------- 7
2.2 The UPDATE Command----------------------------------------------------------------------------------- 7
2.3 The DELETE Command----------------------------------------------------------------------------------- 7
2.4 The SELECT Command----------------------------------------------------------------------------------- 8
Part 3: SQL Problems------------------------------------------------------------------------------------------------ 8
3.1 Problem: Find all students older than 20.-------------------------------------------------------------- 8
3.2 Problem: List all students who are either older than 20 or belong to department 1.-------- 8
3.3 Problem: Retrieve students whose names start with 'A'.-------------------------------------------9
3.4 Problem: Retrieve students between the ages of 18 and 25.-------------------------------------9
3.5 Problem: List all students along with their department names using INNER JOIN.---------9
3.6 Problem: Retrieve all students and their department names, including students who may
not have a department (LEFT JOIN).------------------------------------------------------------------------ 9
3.7 Problem: List all students and their department names, including departments even if no
students are assigned (RIGHT JOIN).--------------------------------------------------------------------- 10
3.8 Problem: Count the number of students in each department.---------------------------------- 10
3.9 Problem: Count the number of students per department but only for departments with
more than 1 student.--------------------------------------------------------------------------------------------10
3.10 Problem: Find all students in the 'Computer Science' department using a subquery.---11
3.11 Problem: Count the total number of students.----------------------------------------------------- 11
3.12 Problem: Calculate the total age of students in each department.--------------------------- 11
3.13 Problem: Find the average age of students in each department.---------------------------- 12
3.14 Problem: Find the oldest age among students.--------------------------------------------------- 12
3.15 Problem: Find the youngest age among students.----------------------------------------------- 12
3.16 Problem: List all student names from department 1 and department 2 using UNION.- 12
3.17 Problem: List all student names from department 1 and department 2, including
duplicates, using UNION ALL.------------------------------------------------------------------------------- 13
3.18 Problem: Find students who are in both department 1 and have ages greater than 20
using INTERSECT.----------------------------------------------------------------------------------------------13
3.19 Problem: Retrieve the names of students who are in the same department as student
Bob.----------------------------------------------------------------------------------------------------------------- 13
3.20 Problem: Use an alias to retrieve the student name and their department location in a
single query.------------------------------------------------------------------------------------------------------ 14
Part 4: Subqueries--------------------------------------------------------------------------------------------------- 15
Single-Row Subqueries----------------------------------------------------------------------------------------15
4.1 Problem: Find the student who has the highest age.-----------------------------------------15
4.2 Problem: Retrieve the student who is younger than the oldest student in the 'Physics'
department.-------------------------------------------------------------------------------------------------- 15
4.3 Problem: Find students who are older than the average age of students in the
'Mathematics' department.------------------------------------------------------------------------------- 15
4.4 Problem: Retrieve the student who has an email address with the same domain as
'[email protected]'.------------------------------------------------------------------------------------- 16
4.5 Problem: Find students who have a phone number that is not in the format of
'1234567890' (using not equal operator).------------------------------------------------------------ 16
Multiple-Row Subqueries--------------------------------------------------------------------------------------16
4.6 Problem: Find students who are in any of the departments with IDs 1, 2, or 3.------- 16
4.7 Problem: Retrieve students who are in departments with more than 2 students.-----17
4.8 Problem: Find students who are not in the same departments as those with age over
23.-------------------------------------------------------------------------------------------------------------- 17
4.9 Problem: Retrieve students who are in departments where the department name
contains 'Science'.----------------------------------------------------------------------------------------- 17
4.10 Problem: List students who have an email address that exists in the list of emails
from students in 'Engineering' department.---------------------------------------------------------- 18
Conclusion------------------------------------------------------------------------------------------------------------- 18
Introduction

MySQL is a widely-used open-source relational database management system (RDBMS) that


allows users to store, retrieve, and manage data efficiently. In this blog, we will explore the
foundational aspects of MySQL by diving into the types of MySQL commands, specifically Data
Definition Language (DDL) and Data Manipulation Language (DML). We'll use the
Universitydb database for all examples to provide a hands-on understanding. By the end of
this guide, you'll have a solid grasp of how to use MySQL commands to manage databases.

Part 1: Data Definition Language (DDL)


DDL (Data Definition Language) is a subset of SQL that deals with defining and modifying the
database structure. DDL commands are used to create, alter, and delete database objects such
as tables, views, indexes, etc. The primary DDL commands include:

● CREATE: Used to create a new database or table.


● ALTER: Used to modify an existing database or table.
● DROP: Used to delete an existing database or table.
● TRUNCATE: Used to delete all records in a table without removing the table itself.
● RENAME: Used to rename a database object.

1.1 The CREATE Command

Let's start by creating two tables: Departments and Students in the Universitydb
database. We will also incorporate AUTO_INCREMENT to automatically generate unique values
for department_id and student_id.

-- In sql

-- How to code?

CREATE DATABASE Universitydb;

USE Universitydb;

-- Create Departments table

CREATE TABLE Departments (

department_id INT AUTO_INCREMENT PRIMARY KEY, -- Primary Key with


AUTO_INCREMENT
department_name VARCHAR(100) NOT NULL,

location VARCHAR(100)

);

-- Create Students table

CREATE TABLE Students (

student_id INT AUTO_INCREMENT PRIMARY KEY, -- Primary Key with


AUTO_INCREMENT

name VARCHAR(50) NOT NULL,

age INT,

department_id INT, -- Foreign Key (FK) reference to Departments


table

email VARCHAR(100) UNIQUE,

phone_number VARCHAR(15),

FOREIGN KEY (department_id) REFERENCES Departments(department_id)

);

1.2 The ALTER Command

Add a new column to the Departments table.

-- In sql

-- How to code?

ALTER TABLE Departments

ADD location VARCHAR(100);


1.3 The DROP Command

Remove the Departments table.

-- In sql

-- How to code?

DROP TABLE IF EXISTS Departments;

1.4 The TRUNCATE Command

Remove all records from the Students table.

-- In sql

-- How to code?

TRUNCATE TABLE Students;

1.5 The RENAME Command

Rename the Students table to University_Students.

-- In sql

-- How to code?

RENAME TABLE Students TO University_Students;


Part 2: Data Manipulation Language (DML)
DML (Data Manipulation Language) commands are used to manipulate data within the
database. The main DML commands are:

● INSERT: Used to insert data into a table.


● UPDATE: Used to update existing data within a table.
● DELETE: Used to delete data from a table.
● SELECT: Used to retrieve data from a table.

2.1 The INSERT Command

Implicit Insert

-- In sql

-- How to code?

-- Insert multiple rows into Departments

INSERT INTO Departments (department_name, location)

VALUES ('Computer Science', 'Building A'),

('Mathematics', 'Building B'),

('Physics', 'Building C'),

('Chemistry', 'Building D'),

('Biology', 'Building E');

-- Insert multiple rows into Students

INSERT INTO Students (name, age, department_id, email, phone_number)

VALUES ('Alice', 20, 1, '[email protected]', '1234567890'),

('Bob', 22, 2, '[email protected]', '0987654321'),

('Charlie', 21, 3, '[email protected]', '1122334455'),

('David', 23, 4, '[email protected]', '2233445566'),


('Eva', 24, 5, '[email protected]', '3344556677');

Explicit Insert

-- In sql

-- How to code?

INSERT INTO Departments (department_name, location)

VALUES ('Engineering', 'Building F'),

('Architecture', 'Building G');

INSERT INTO Students (name, age, department_id, email, phone_number)

VALUES ('Frank', 25, 6, '[email protected]', '4455667788'),

('Grace', 26, 7, '[email protected]', '5566778899');

2.2 The UPDATE Command

Update the age of the student named Bob.

-- In sql

-- How to code?

UPDATE Students

SET age = 23

WHERE name = 'Bob';

2.3 The DELETE Command

Delete the record for the student named Alice.


-- In sql

-- How to code?

DELETE FROM Students

WHERE name = 'Alice';

2.4 The SELECT Command

Retrieve all records from the Students table.

-- In sql

-- How to code?

SELECT * FROM Students;

Part 3: SQL Problems


Below are 20 different scenarios demonstrating the use of WHERE clauses, logical operators,
JOINs, GROUP BY, HAVING, subqueries, aggregate functions, UNION, UNION ALL, and
INTERSECT. Each scenario includes a problem description and a corresponding SQL solution.

3.1 Problem: Find all students older than 20.

-- In sql

-- How to code?

SELECT * FROM Students WHERE age > 20;

3.2 Problem: List all students who are either older than 20 or belong to
department 1.

-- In sql

-- How to code?
SELECT * FROM Students WHERE age > 20 OR department_id = 1;

3.3 Problem: Retrieve students whose names start with 'A'.

-- In sql

-- How to code?

SELECT * FROM Students WHERE name LIKE 'A%';

3.4 Problem: Retrieve students between the ages of 18 and 25.

-- In sql

-- How to code?

SELECT * FROM Students WHERE age BETWEEN 18 AND 25;

3.5 Problem: List all students along with their department names using
INNER JOIN.

-- In sql

-- How to code?

SELECT s.name AS student_name, d.department_name AS department

FROM Students s

INNER JOIN Departments d ON s.department_id = d.department_id;

3.6 Problem: Retrieve all students and their department names, including
students who may not have a department (LEFT JOIN).

-- In sql

-- How to code?
SELECT s.name AS student_name, d.department_name AS department

FROM Students s

LEFT JOIN Departments d ON s.department_id = d.department_id;

3.7 Problem: List all students and their department names, including
departments even if no students are assigned (RIGHT JOIN).

-- In sql

-- How to code?

SELECT s.name AS student_name, d.department_name AS department

FROM Students s

RIGHT JOIN Departments d ON s.department_id = d.department_id;

3.8 Problem: Count the number of students in each department.

-- In sql

-- How to code?

SELECT d.department_name AS department, COUNT(*) AS student_count

FROM Students s

INNER JOIN Departments d ON s.department_id = d.department_id

GROUP BY d.department_name;

3.9 Problem: Count the number of students per department but only for
departments with more than 1 student.

-- In sql

-- How to code?
SELECT d.department_name AS department, COUNT(*) AS student_count

FROM Students s

INNER JOIN Departments d ON s.department_id = d.department_id

GROUP BY d.department_name

HAVING COUNT(*) > 1;

3.10 Problem: Find all students in the 'Computer Science' department using
a subquery.

-- In sql

-- How to code?

SELECT name FROM Students

WHERE department_id = (SELECT department_id FROM Departments WHERE


department_name = 'Computer Science');

3.11 Problem: Count the total number of students.

-- In sql

-- How to code?

SELECT COUNT(*) AS total_students FROM Students;

3.12 Problem: Calculate the total age of students in each department.

-- In sql

-- How to code?

SELECT d.department_name AS department, SUM(s.age) AS total_age

FROM Students s
INNER JOIN Departments d ON s.department_id = d.department_id

GROUP BY d.department_name;

3.13 Problem: Find the average age of students in each department.

-- In sql

-- How to code?

SELECT d.department_name AS department, AVG(s.age) AS average_age

FROM Students s

INNER JOIN Departments d ON s.department_id = d.department_id

GROUP BY d.department_name;

3.14 Problem: Find the oldest age among students.

-- In sql

-- How to code?

SELECT MAX(age) AS oldest_age FROM Students;

3.15 Problem: Find the youngest age among students.

-- In sql

-- How to code?

SELECT MIN(age) AS youngest_age FROM Students;

3.16 Problem: List all student names from department 1 and department 2
using UNION.
-- In sql

-- How to code?

SELECT name FROM Students WHERE department_id = 1

UNION

SELECT name FROM Students WHERE department_id = 2;

3.17 Problem: List all student names from department 1 and department 2,
including duplicates, using UNION ALL.

-- In sql

-- How to code?

SELECT name FROM Students WHERE department_id = 1

UNION ALL

SELECT name FROM Students WHERE department_id = 2;

3.18 Problem: Find students who are in both department 1 and have ages
greater than 20 using INTERSECT.

-- In sql

-- How to code?

SELECT name FROM Students WHERE department_id = 1

INTERSECT

SELECT name FROM Students WHERE age > 20;

3.19 Problem: Retrieve the names of students who are in the same
department as student Bob.
-- In sql

-- How to code?

SELECT name FROM Students

WHERE department_id = (SELECT department_id FROM Students WHERE name =


'Bob');

3.20 Problem: Use an alias to retrieve the student name and their
department location in a single query.

-- In sql

-- How to code?

SELECT s.name AS student_name, d.location AS department_location

FROM Students s

INNER JOIN Departments d ON s.department_id = d.department_id;


Part 4: Subqueries
Subqueries are queries nested inside other queries. They can be classified into single-row
subqueries and multiple-row subqueries.

Single-Row Subqueries

Single-row subqueries return a single row and single column of results. These are typically used
with operators like =, <, >, <=, >=, or <>.

4.1 Problem: Find the student who has the highest age.

-- In sql

-- How to code?

SELECT * FROM Students

WHERE age = (SELECT MAX(age) FROM Students);

4.2 Problem: Retrieve the student who is younger than the oldest student in the 'Physics'
department.

-- In sql

-- How to code?

SELECT * FROM Students

WHERE age < (SELECT MAX(age) FROM Students

WHERE department_id = (SELECT department_id FROM


Departments WHERE department_name = 'Physics'));

4.3 Problem: Find students who are older than the average age of students in the
'Mathematics' department.

-- In sql

-- How to code?

SELECT * FROM Students


WHERE age > (SELECT AVG(age) FROM Students

WHERE department_id = (SELECT department_id FROM


Departments WHERE department_name = 'Mathematics'));

4.4 Problem: Retrieve the student who has an email address with the same domain as
'[email protected]'.

-- In sql

-- How to code?

SELECT * FROM Students

WHERE email LIKE CONCAT('%', (SELECT SUBSTRING_INDEX(email, '@', -1)


FROM Students WHERE name = 'Alice'));

4.5 Problem: Find students who have a phone number that is not in the format of
'1234567890' (using not equal operator).

-- In sql

-- How to code?

SELECT * FROM Students

WHERE phone_number <> '1234567890';

Multiple-Row Subqueries

Multiple-row subqueries return more than one row and are often used with operators like IN,
ANY, ALL, or EXISTS.

4.6 Problem: Find students who are in any of the departments with IDs 1, 2, or 3.

-- In sql

-- How to code?

SELECT * FROM Students


WHERE department_id IN (1, 2, 3);

4.7 Problem: Retrieve students who are in departments with more than 2 students.

-- In sql

-- How to code?

SELECT * FROM Students

WHERE department_id IN (SELECT department_id FROM Students

GROUP BY department_id

HAVING COUNT(*) > 2);

4.8 Problem: Find students who are not in the same departments as those with age over
23.

-- In sql

-- How to code?

SELECT * FROM Students

WHERE department_id NOT IN (SELECT department_id FROM Students WHERE


age > 23);

4.9 Problem: Retrieve students who are in departments where the department name
contains 'Science'.

-- In sql

-- How to code?

SELECT * FROM Students

WHERE department_id IN (SELECT department_id FROM Departments WHERE


department_name LIKE '%Science%');
4.10 Problem: List students who have an email address that exists in the list of emails
from students in 'Engineering' department.

-- In sql

-- How to code?

SELECT * FROM Students

WHERE email IN (SELECT email FROM Students WHERE department_id =


(SELECT department_id FROM Departments WHERE department_name =
'Engineering'));

Conclusion
This guide provided a comprehensive overview of MySQL basics, including DDL and DML
commands, advanced concepts such as aliases and auto-increment fields, practical examples
of SQL queries for various scenarios, and detailed subquery examples. By understanding these
concepts and practicing the provided examples, you can effectively manage and manipulate
your data in MySQL.

You might also like