Sqlhandbook
Sqlhandbook
What is a Database?
Example: Think of a library where books are organized by topic, author, and
title – that’s essentially what a database does with data.
What is SQL?
Databases and Excel may seem similar at first, but they work differently under the
hood.
Relational databases store data in structured tables with predefined schemas and
relationships between tables (e.g., MySQL, PostgreSQL). Non-relational databases
(NoSQL) use flexible formats like documents, key-value pairs, or graphs, and don’t
require a fixed schema (e.g., MongoDB, Firebase). Relational is ideal for structured
data and complex queries, while non-relational is better for scalability and
unstructured data.
What is DBMS?
What is MySQL?
Syntax
Example
Tips
SHOW DATABASES;
Switching to a Database
USE student_db;
Dropping a Database
Example
Be very careful! This will permanently delete all data and tables in the
database.
Creating a Table in MySQL
Once you have selected a database, you can create tables to organize and store
data.
Syntax
Example
Explanation
• id INT AUTO_INCREMENT PRIMARY KEY – A unique identifier for each student
that auto-increments.
• name VARCHAR(100) NOT NULL – Name must be provided.
• age INT – Stores numeric values for age.
• email VARCHAR(100) UNIQUE – Each email must be different.
• admission_date DATE – Stores the date of admission.
Commonly Used Data Types
• INT – Whole numbers (e.g., age, quantity)
• VARCHAR(n) – Variable-length string (e.g., names, emails)
• TEXT – Long text strings (e.g., descriptions)
• DATE – Stores date values (YYYY-MM-DD)
• DATETIME – Stores date and time values
• BOOLEAN – Stores TRUE or FALSE
Common Constraints
• PRIMARY KEY – Uniquely identifies each record
• NOT NULL – Ensures the column cannot be left empty
• UNIQUE – Ensures all values in a column are different
• AUTO_INCREMENT – Automatically increases numeric values
• DEFAULT – Sets a default value for the column
• FOREIGN KEY – Enforces relationships between tables
SHOW TABLES;
DESCRIBE students;
Tables are the backbone of any relational database. A well-structured table leads to
efficient data management and fewer issues later on.
Modifying a Table in MySQL
Renaming a Table
Use the RENAME TABLE command to change the name of an existing table.
Dropping a Table
To permanently delete a table and all of its data:
Renaming a Column
To rename a column in an existing table:
Dropping a Column
To remove a column from a table:
Example:
Modifying a Column
To change the data type or constraints of an existing column:
Example:
Always review changes on production databases carefully. Use tools like DESCRIBE
table_name to verify structure before and after modifications.
How to Insert Rows into a Table in
MySQL
Inserting data into a MySQL table can be done in two ways: inserting one row at a
time or inserting multiple rows at once. Below are the steps to create a new
database, create a table, and insert data into it.
USE schooldb;
INSERT INTO student (id, name, age, grade, date_of_birth) VALUES (1, 'Ayesha Khan',
16, '10th', '2007-05-15');
INSERT INTO student (id, name, age, grade, date_of_birth) VALUES (2, 'Ravi Sharma',
17, '11th', '2006-03-22');
INSERT INTO student (id, name, age, grade, date_of_birth) VALUES (3, 'Meena Joshi',
15, '9th', NULL);
INSERT INTO student (id, name, age, grade, date_of_birth) VALUES (4, 'Arjun Verma',
18, '12th', NULL);
INSERT INTO student (id, name, age, grade, date_of_birth) VALUES (5, 'Sara Ali',
16, '10th', NULL);
INSERT INTO student (id, name, age, grade, date_of_birth) VALUES (6, 'Karan Mehta',
17, '11th', NULL);
INSERT INTO student (id, name, age, grade, date_of_birth) VALUES (7, 'Tanya Roy', 1
5, '9th', NULL);
INSERT INTO student (id, name, age, grade, date_of_birth) VALUES (8, 'Vikram
Singh', 18, '12th', NULL);
INSERT INTO student (id, name, age, grade, date_of_birth) VALUES (9, 'Anjali
Desai', 16, '10th', NULL);
INSERT INTO student (id, name, age, grade, date_of_birth) VALUES (10, 'Farhan
Zaidi', 17, '11th', NULL);
What is NULL ?
5. Combining Conditions
SELECT * FROM student WHERE grade = '10th' AND age > 16;
You’re right! The _ wildcard is very handy for matching dates, especially when
you’re looking for values at a specific position (like a specific day or month). Let’s
expand the section accordingly:
Wildcards are used with the LIKE operator to search for patterns. They’re helpful
when you’re not exactly sure about the full value, or you want to match based on
structure or partial content.
This finds any name that starts with ‘A’, like Aakash , Ananya , Aryan .
The _ wildcard is useful for matching specific patterns in date strings, especially
in YYYY-MM-DD format.
Let’s say you want to find records from the 5th day of any month:
SELECT * FROM attendance
WHERE date LIKE '____-__-05';
Explanation:
“Give me all rows where the date ends with -05 — which means the 5th of
any month, any year.”
Pattern to be
Matches
Matched
Pattern Meaning
1. Basic Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
2. Example Table
UPDATE student
SET grade = '12th'
WHERE id = 2;
UPDATE student
UPDATE student
SET age = 18;
UPDATE student
SET grade = '10th'
WHERE grade = '9th';
UPDATE student
SET age = age + 1
WHERE age < 18;
UPDATE student
1. Basic Syntax
Important: If you omit the WHERE clause, all rows in the table will be deleted.
2. Example Table
What is a Transaction?
AUTOCOMMIT
By default, MySQL runs in autocommit mode. This means that every SQL
statement is treated as a separate transaction and is committed automatically right
after it is executed.
SELECT @@autocommit;
Disable Autocommit
SET autocommit = 0;
Enable Autocommit
SET autocommit = 1;
COMMIT
The COMMIT statement is used to permanently save all the changes made in the
current transaction.
Example
START TRANSACTION;
COMMIT;
Once committed, the changes are visible to other sessions and are stored
permanently in the database.
ROLLBACK
The ROLLBACK statement is used to undo changes made in the current transaction.
It is useful if something goes wrong or a condition is not met.
Example
START TRANSACTION;
ROLLBACK;
After a rollback, all changes since the start of the transaction are discarded.
Summary Table
Statement Description
Best Practices
1. CURRENT_DATE
SELECT CURRENT_DATE;
Example Output:
2025-05-02
2. CURRENT_TIME
SELECT CURRENT_TIME;
Example Output:
14:23:45
3. CURRENT_TIMESTAMP (or NOW() )
SELECT CURRENT_TIMESTAMP;
-- or
SELECT NOW();
Example Output:
2025-05-02 14:23:45
These are synonyms for NOW() and return the current date and time.
SELECT LOCALTIME;
SELECT LOCALTIMESTAMP;
These functions return the local date and time of the MySQL server, not the client’s
time zone.
Important Clarification:
The “local” in LOCALTIME refers to the time zone configured on the MySQL server,
not the user’s system.
Best Practices
Use Case:
Make sure critical fields like id , name , or email are always filled.
2. UNIQUE Constraint
Use Case:
Prevent duplicate usernames or email addresses.
Note: A table can have multiple UNIQUE constraints, but only one PRIMARY
KEY.
3. DEFAULT Constraint
Use Case:
Auto-fill common values to reduce data entry effort and prevent missing data.
4. CHECK Constraint
id INT,
balance DECIMAL(10,2) CHECK (balance >= 0)
);
Use Case:
Enforce business rules such as non-negative balances or valid age ranges.
Note: MySQL versions before 8.0 parsed CHECK but did not enforce it. From
MySQL 8.0 onwards, CHECK constraints are enforced.
5. Naming Constraints
You can give explicit names to constraints. This makes them easier to reference,
especially when altering or dropping them later.
);
Yes (MySQL
CHECK Enforce value conditions Yes
8.0+)
Best Practices
1. Create a Database
2. Create Tables
• students
• classes
Each student will belong to a class, creating a one-to-many relationship (one class
has many students).
ON UPDATE CASCADE
ON DELETE SET NULL
);
SELECT
table_name,
column_name,
constraint_name,
referenced_table_name,
referenced_column_name
FROM
information_schema.key_column_usage
WHERE
referenced_table_name IS NOT NULL
AND table_schema = 'school';
When you define a foreign key in MySQL, you can specify what should happen to
the child table when the parent table is updated or deleted. These are called
referential actions.
1. ON UPDATE CASCADE
Definition: If the value in the parent table (i.e., the referenced column) is updated,
the corresponding foreign key value in the child table is automatically updated to
match.
Then all students in the students table whose class_id was 1 will
automatically be updated to 10 .
Definition: If a row in the parent table is deleted, the foreign key in the child table
will be set to NULL for all matching rows.
Then all students in the students table who were in class 2 will have their
class_id set to NULL , indicating that they are no longer assigned to a class.
students
id name
1 Alice
2 Bob
marks
1 Math 95
2 Math 88
2 Science 90
1. INNER JOIN
We are telling MySQL to include only the rows that have matching values in both
tables.
We are telling MySQL to include all students, even if they don’t have any marks. If
there’s no match in the marks table, it will show NULL .
This is useful when we want to list all students, and show marks only if available.
We are telling MySQL to include all rows from the right table ( marks ), even if the
student is missing from the students table.
This is rarely used unless we expect some marks that don’t have a student record.
5. CROSS JOIN
We are telling MySQL to combine every row in the first table with every row in the
second table.
SELECT students.name, marks.subject
FROM students
CROSS JOIN marks;
Use this only when you really want all combinations – it can produce a lot of rows.
Summary
LEFT JOIN All rows from the left table, with matched data if any
RIGHT JOIN All rows from the right table, with matched data if any
It helps when:
This combines names and cities from both tables into a single result.
UNION
SELECT name FROM students;
MySQL will complain that the columns can’t be matched due to type mismatch.
By default, UNION removes duplicate rows. If you want to keep duplicates, use
UNION ALL :
This gives a combined list of all students across both years, without duplicates.
SELECT NOW();
-- Output: 2025-05-03 14:20:45 (example)
3. LENGTH() – Find length of a string (in bytes)
SELECT LENGTH('Harry');
-- Output: 5
CONCAT('A', 'B') →
CONCAT() Combine multiple strings
'AB'
DATEDIFF('2025-06-01',
DATEDIFF() Days between two dates
'2025-05-01')
ROUND(5.678, 2) →
ROUND() Round to decimal places
5.68
Round up to nearest
CEIL() CEIL(5.1) → 6
whole number
Function Description Example Usage
Average of a numeric
AVG() AVG(score)
column
You can use a view just like a regular table: SELECT from it, filter it, join it, etc.
Creating a View
Let’s say you have an employees table with lots of details, but you only want to
show public employee info (name, department, and salary).
Updating a View
Notes
• Views don’t store data. If the underlying table changes, the view reflects that
automatically.
• Not all views are updatable. Simple views usually are (like those selecting
from one table without grouping or joins), but complex ones may not allow
INSERT , UPDATE , or DELETE .
Think of an index like the index in a book: instead of reading every page, MySQL
uses the index to jump straight to the relevant row(s).
“Create a quick lookup structure for the email column in the users table.”
This is useful when your query filters on both name and city in that specific
order.
How to Delete (Drop) an Index
You’re saying:
Indexes are essential for performance, but overusing them or indexing the wrong
columns can actually hurt performance. Use them wisely based on how your data is
queried.
Subqueries in MySQL
A subquery is a query nested inside another SQL query.
It helps you perform complex filtering, calculations, or temporary data shaping by
breaking down the logic into smaller steps.
What is a Subquery?
We are telling MySQL: “First calculate the average salary, then return employees
with salaries greater than that.”
Subquery in the FROM Clause
SELECT name,
This gives each employee along with the number of projects they are assigned to.
Correlated Subqueries
A correlated subquery depends on the outer query. It runs once for each row in
the outer query.
Example: Employee earning more than department’s average
We are telling MySQL: “For each employee, compare their salary with the average
salary of their department.”
Types of Subqueries
Type Description
• When the same result can be achieved with a JOIN, which is often faster
• When the subquery is being executed repeatedly for every row (correlated
subqueries on large tables)
Summary
Subqueries are powerful for solving multi-step problems and isolating logic, but be
mindful of performance when working with large data sets.
GROUP BY in MySQL
The GROUP BY clause is used when you want to group rows that have the same
values in specified columns.
It’s usually combined with aggregate functions like COUNT() , SUM() , AVG() ,
MAX() , or MIN() .
Here, we’re grouping all employees by their department and counting how many
are in each group.
We are telling MySQL: “Group the data by department, then calculate the
average salary for each group.”
Using GROUP BY with Multiple Columns
You can group by more than one column to get more detailed groupings.
FROM employees
GROUP BY department, job_title;
This will count how many employees hold each job title within each department.
Once you’ve grouped data using GROUP BY , you might want to filter the groups
themselves based on the result of an aggregate function. This is where HAVING
comes in.
FROM employees
GROUP BY department
HAVING COUNT(*) > 5;
We are telling MySQL: “First group employees by department, then only show
those departments where the total number is greater than 5.”
Difference Between WHERE and HAVING
FROM employees
WHERE status = 'active'
GROUP BY department
HAVING AVG(salary) > 60000;
The WITH ROLLUP clause in MySQL is used with GROUP BY to add summary rows
(totals and subtotals) to your result set.
Summary
Keyword Role
When you create a stored procedure, you need to temporarily change the SQL
statement delimiter from ; to something else like // or $$ .
DELIMITER //
DELIMITER ;
CALL list_employees();
DELIMITER //
CALL get_employee_by_id(3);
Summary