0% found this document useful (0 votes)
75 views19 pages

MySQL SQL Commands and Concepts Guide

Uploaded by

m62269581
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)
75 views19 pages

MySQL SQL Commands and Concepts Guide

Uploaded by

m62269581
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

SQL Notes

Requirement:
Tool – MySQL

Database – is Collection of data in a format which is easily accessed.


(Digital)

DBMS (Database Management System) – Software to create,


manage, and interact with databases.

User →→ DBMS →→ DB

Types Of Databases

Relational DB (SQL) Non-Relational DB (NoSQL)


Data stored in form of tables, Data stored in form of documents,
rows, columns; relations via keys key-value, graph
DB is used to store structured DB is used to unstructured data or
data semi-structured data
Predefined, strict schema Flexible and dynamic schema
Example – MySQL, SQLite, SQL Example – MongoDB, Redis,
Server, Oracle, PostgreSQL. Neo4j
What is SQL?

• Structured Query Language.


• SQL is programming language that is used to store, retrieve,
manipulate, and manage data in relational databases.

• It is used to perform CRUD operations:

Create

Read

Update

Delete

Why Learn SQL?


• It’s the most popular language for working with databases.
• Used in many industries (banking, social media, finance,
education).
• Helps in data analysis, application development, reporting.

Creating Databases and Tables in MySQL:

Database - A database is a container that holds related data.


Important SQL Commands -
1. To create a Database
Syntax -
CREATE DATABASE database_name;
2. To view all the databases
Syntax -
SHOW DATABASES;

3. To delete a database
Syntax -
DROP DATABASE database_name;

4. To use a database
Syntax -
USE database_name;

Table – a collection of rows and columns.


Each column represents a field (data attribute), and each row is a
record (entry).
Roll_No Name Age
1 Rohit 23
2 Raman 24
3 Sid 24

1. To create a Table
Syntax -
CREATE TABLE table_name (
column1 datatype constraints,
column2 datatype constraints
);
2. To Insert into Table
Syntax -
INSERT INTO table_name (column1, column2,...)
VALUES (value1, value2,...);

3. To view data from Table


Syntax -
SELECT * FROM table_name;
SQL Command/Statement:
Specific commands to perform operations on database.

Types of SQL Commands:


1. Data Definition Language (DDL) - define or modify the structure of
database objects
• CREATE
• DROP
2. Data Query Language (DQL) - Focused on querying data
• SELECT
3. Data Manipulation Language (DML) - manipulate the actual data
stored in database tables.
• INSERT
• UPDATE
• DELETE
4. Data Control Language(DCL) - Manage access and permissions on
the database objects.
• GRANT
• PROVOKE
5. Transport Control Language(TCL) - Control transactions to ensure
data integrity.
• COMMIT
• ROLLBACK
• SAVEPOINT
Datatype – in SQL defines the kind of data a column can in database
table.

DATATYPE DESCRIPTION USAGE


CHAR String(0-255), can store characters of fixed CHAR(50)
length
VARCHAR String(0-255) can store characters up to given VARCHAR(50)
length
INT Integer(-2,147,483,648 to 2,147,483,647) INT
TINYINT Integer(-128 to 127) TINYINT
BIGINT Integer(-9,223,372,036,854,775,808 to BIGINT
9,223,372,036,854,775,807)
BIT Can store x-bit values, x can range from 1 to 64 BIT(2)
FLOAT Decimal number – with precision to 23 digits FLOAT
DOUBLE Decimal number – with 24 to 53 digits DOUBLE
BOOLEAN Boolean values 0 or 1 BOOLEAN
DATE Date in format of YYYY-MM-DD ranging from DATE
1000-01-01 to 9999-12-31
TIME HH: MM: SS TIME
YEAR Year in 4 digits format ranging from 1901 to YEAR
2155

Signed & Unsigned Datatype -

TINYINT(-128 to 127)

TINYINT UNSIGNED (0 to 255)


Keys:

1. Primary Key – Uniquely identifies each row in a table.


Syntax -
CREATE TABLE Students (
rollno INT PRIMARY KEY,
Name VARCHAR(50)
);

2. Foreign Key – References a primary key in another table to link


data.
Syntax-

CREATE TABLE table_name (


OrderID INT PRIMARY KEY,
StudentID INT,
FOREIGN KEY (StudentID) REFERENCES Students(StudentID)
);

Table1 – Student
Rollno(P. K.) Name Age Cityid City
1 Abhay 21 1 Delhi
2 Bhanu 23 2 Goa
3 Raman 24 1 Delhi
4 Sid 22 3 Pune

Table 2 – City
Id (P. K.) City
1 Delhi
2 Goa
3 Pune
Constraints - are used to specify rules for data in a table.

NOT NULL – columns cannot have a null value.


Syntax -
column Datatype NOT NULL;

UNIQUE – all values in column are different.


Syntax -
column Datatype NOT NULL;

DEFAULT – sets the default value of a column.


Syntax -
column Datatype DEFAULT Values;

CHECK – it can limit the values allowed in a column.


Syntax -
1. CONSTRAINT constraint_name CHECK(Conditions);

Create database name – college


Table – Student

rollno name marks grade city


101 Anil 78 C Pune
102 Aman 93 A Goa
103 Bhumi 85 B Goa
104 Chetan 96 A Delhi
105 Rohit 12 F Delhi
106 Raman 82 B Delhi
107 Sid 72 B Pune
SELECT Command:
Used to select any data from database.

Syntax -
SELECT col1, col2 FROM table_name;

DISTINCT – used to remove duplicate values.

WHERE Clause:
Used to define conditions:

Syntax -
SELECT col1, col2
FROM table_name
WHERE conditions;

Operators In SQL:
• Arithmetic Operators: +(addition), -(subtraction),
*(multiplication), /(division), %(modulus)
• Comparison Operators: = (equal to), != (not equal to), >, >=, <,
<=
• Logical Operators: AND, OR, NOT, IN, BETWEEN, ALL, LIKE,
ANY
• Bitwise Operators: & (Bitwise AND), | (Bitwise OR)

LIMIT Clause:
Sets an upper limit on number of (tuples)rows to be returned.

Syntax -
SELECT col1, col2
FROM table_name
LIMIT value;
Order By Clause:
To sort in ascending (ASC) or descending order (DESC)

Syntax
SELECT col1, col2
FROM table_name
ORDER BY col_name(s) ASC;

Aggregate Functions:
The functions which perform calculation on a set of values, and return
a single value.

• COUNT( )
• MAX( )
• MIN( )
• SUM( )
• AVG( )

Group By Clause:
Groups rows that have the same values into summary rows.
It collects data from multiple records and groups the result by one or
more column.

*Generally we use group by with some aggregation function. Count


number of students in each city

Syntax -
SELECT col1, Function()
FROM table_name
GROUP BY col1;
Having Clause:
Used when we want to apply any condition after grouping.

Syntax -
SELECT col1, Function()
FROM table_name
GROUP BY col1
HAVING conditions;

General Order:

SELECT column(s)

FROM table_name

WHERE condition

GROUP BY column(s)

HAVING condition

ORDER BY column(s) ASC;


Table Related Queries:

UPDATE:
Update (to update existing rows)

Syntax -
UPDATE table_name
SET col1 = val1, col2 = val2
WHERE condition;

Error – 1175
Solution – SET SQL_SAFE_UPDATES = 0;

DELETE:
(to delete existing rows)

Syntax -
DELETE FROM table_name
WHERE conditions;

Cascading for Foreign Key:

ON DELETE CASCADE
When we create a foreign key using this option, it deletes the
referencing rows in the child table when the referenced row is deleted
in the parent table which has a primary key.

ON UPDATE CASCADE
When we create a foreign key using UPDATE CASCADE the
referencing rows are updated in the child table when the referenced
row is updated in the parent table which has a primary key.
Joins in SQL:
Join is used to combine rows from two or more tables, based on a
related column between them.

Types of Joins:

1. INNER JOIN

2. RIGHT JOIN

3. LEFT JOIN

4. FULL JOIN

1. INNER JOIN:
Returns records that have matching values in both tables

Syntax -
SELECT A.column1, B.column2
FROM TableA A
INNER JOIN TableB B
ON A.common_column = B.common_column;

2. RIGHT JOIN
Returns all records from the right table, and the matched records from
the left table

Syntax -
SELECT A.column1, B.column2
FROM TableA A
RIGHT JOIN TableB B
ON A.common_column = B.common_column;
3. LEFT JOIN:
Returns all records from the left table, and the matched records from
the right table.

Syntax -
SELECT A.column1, B.column2
FROM TableA A
LEFT JOIN TableB B
ON A.common_column = B.common_column;

4. FULL JOIN:
Returns all rows when there is a match in either left or right table.
Unmatched rows get NULL.

Syntax -
SELECT A.column1, B.column2
FROM TableA A
LEFT JOIN TableB B
ON A.common_column = B.common_column

UNION

SELECT A.column1, B.column2


FROM TableA A
LEFT JOIN TableB B
ON A.common_column = B.common_column;
Practice Questions:

1. Write an SQL command to create a new database of your institute


name.
2. How do you display all the databases available in your MySQL
server?
3. Create a table called students with the following columns:
student_id (INT, primary key)
name (VARCHAR(50))
age (INT)
Course(VARCHAR(10))
4. Write the SQL command to display all the tables present in the
current database.
5. Insert a record into the students table with the following values:
student_id = 111
name = 'Rahul Sharma'
age = 16
grade = '[Link]'
6. Insert multiple records into the students table for three more
students in a single command.
[Link] the query to display all records from the students table.
8. How do you show the structure (column names and data types) of
the students table in MySQL?
CONSTRAINT Questions -
1. Create a table named Employees with columns:
• EmployeeID as INT and primary key,
• Name as VARCHAR(50) and NOT NULL,
• Email as VARCHAR(100) and UNIQUE,
• Age as INT with a CHECK constraint ensuring age is
greater than or equal to 18,
• Salary as FLOAT with a DEFAULT value of 30000.

2. Create a table named Products with columns:


• ProductID as INT and primary key,
• ProductName as VARCHAR(100) and NOT NULL,
• Price as FLOAT with a CHECK constraint ensuring price is
greater than 0,
• Stock as INT with a DEFAULT value of 50.

3. Write a query to create a table Orders with:


• OrderID as an INT primary key,
• OrderDate as DATE with a DEFAULT value of the current
date,
• Quantity as INT with a CHECK constraint that quantity is
greater than 0.
Clause Questions:
1. Write a query to find the average marks in each city and display
results in ascending order of average marks.
2. Get the total number of students in each city who scored above 80
marks.
3. List the names and grades of top 3 students (highest marks) from
‘Delhi’.
4. Show all students with grades ‘A’ or ‘B’, sorted by marks in
descending order, and limit the result to 4 rows.
5. Find all cities where the average marks of students is greater than
75, and display these cities along with their average marks.
6. List the grades with the count of students in each, but only include
groups where the count is at least 2.
7. Display the city and total marks of students, sorted by total marks in
descending order.
8. Show student names and marks who scored more than the average
marks of all students, sorted by marks ascending.
9. Get the grades where the maximum marks earned by students is
above 90.
10. Select students with marks between 70 and 90 from ‘Goa’ or
‘Pune’, sorted by roll number, limit the result to 3.
Practice Questions – Foreign Key, Cascading, Delete, Update:
1. Create a new database named Zepto
Table – Department
dept_id dept_name

1 HR

2 Finance

3 IT

Table – Employees
emp_id emp_name dept_id

101 Anil 1

102 Aman 2

103 Bhumi 1

104 Chetan 3

105 Rohit 2

3. Delete the 'HR' department and observe cascading delete:


4. Update DeptID of the 'Finance' department from 2 to 4 and observe
cascading update:
Practice Question – JOIN:
Table – Customer
CustomerID CustomerName Country

1 John USA

2 Emma Canada

3 Ravi India

4 Lisa Singapore

5 Ahmed UAE

Table – Orders
OrderID OrderDate CustomerID Amount

101 2025-09-01 3 500

102 2025-09-03 2 300

103 2025-09-09 4 700

104 2025-09-10 2 200

105 2025-09-12 6 100

You might also like