The Ultimate SQL Tutorial - Blog - CodeWithHarry
The Ultimate SQL Tutorial - Blog - CodeWithHarry
</>CodeWithHarry
Eid Mega Sale LIMITED TIME OFFER Get Python Bootcamp FREE with Data Science and Data Analytics
Courses
This bonus won't be available after the sale
Installing MySQL
MySQL Workbench is a visual tool for database architects, developers, and DBAs. It
provides data modeling, SQL development, and comprehensive administration tools for
server configuration, user administration, backup, and much more.
1 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
A Database Management System (DBMS) is software that interacts with end users,
applications, and the database itself to capture and analyze data. It allows for the creation,
retrieval, updating, and management of data in databases. If you know one DBMS, you can
easily transition to another, as they share similar concepts and functionalities.
2 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
sudo mysql_secure_installation
sudo mysql
mysql -u harry -p
Make sure to replace 'password' with a secure password of your choice in production
environments.
3 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
What is a Database?
Think of it like:
• Folder analogy:
• The rows in the table are like the content inside each file.
• Excel analogy:
4 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
USE startersql;
You can delete the entire database (and all its tables) using:
5 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
• ENUM : A string object with a value chosen from a list of permitted values. eg. gender
• TIMESTAMP : Stores date and time, automatically set to the current timestamp when a
row is created.
• BOOLEAN : Stores TRUE or FALSE values, often used for flags like is_active .
• DECIMAL(10, 2) : Stores exact numeric data values, useful for financial data. The first
number is the total number of digits, and the second is the number of digits after the
decimal point.
Constraints Explained
• DEFAULT : Sets a default value for a column if no value is provided. eg. created_at
This fetches every column and every row from the users table.
6 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
This only fetches the name and email columns from all rows.
Renaming a Table
To rename it back:
Altering a Table
Add a Column
Drop a Column
7 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
To move a column after another column (e.g., move gender after name ):
This method requires you to provide values for all columns in order, except columns with
default values or AUTO_INCREMENT .
“Not recommended if your table structure might change (e.g., new columns added later).”
8 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
This method is safer and more readable. You only insert into specific columns.
The remaining columns like id (which is AUTO_INCREMENT ) and created_at (which has
a default) are automatically handled by MySQL.
9 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
Basic Syntax
Not Equal To
10 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
IS NOT NULL
BETWEEN
IN
11 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
AND / OR
ORDER BY
LIMIT
Quick Quiz
12 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
SELECT * FROM users WHERE salary > 60000 ORDER BY created_at DESC LIMIT
5;
Basic Syntax
UPDATE table_name
SET column1 = value1, column2 = value2
WHERE condition;
UPDATE users
SET name = 'Alicia'
WHERE id = 1;
UPDATE users
SET name = 'Robert', email = 'robert@[Link]'
13 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
WHERE id = 2;
UPDATE users
SET gender = 'Other';
“This updates every row in the table. Be very careful when omitting the WHERE clause.”
UPDATE users
SET salary = 70000
WHERE id = 5;
2. Change the name of the user with email aisha@[Link] to Aisha Khan .
UPDATE users
SET name = 'Aisha Khan'
WHERE email = 'aisha@[Link]';
3. Increase salary by ₹10,000 for all users whose salary is less than ₹60,000.
14 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
UPDATE users
SET salary = salary + 10000
WHERE salary < 60000;
UPDATE users
SET gender = 'Other'
WHERE name = 'Ishaan';
UPDATE users
SET salary = 50000;
“Note: This query will overwrite salary for every user. Use with caution!”
Basic Syntax
15 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
Best Practices
• Consider running a SELECT with the same WHERE clause first to confirm what will be
affected:
16 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
MySQL Constraints
Constraints in MySQL are rules applied to table columns to ensure the accuracy, validity,
and integrity of the data.
1. UNIQUE Constraint
17 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
Example:
3. CHECK Constraint
18 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
4. DEFAULT Constraint
Example:
Example:
19 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
6. AUTO_INCREMENT
Example:
Summary Table
Constraint Purpose
SQL functions help you analyze, transform, or summarize data in your tables.
20 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
1. Aggregate Functions
COUNT()
SUM()
AVG()
21 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
2. String Functions
LENGTH()
22 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
CONCAT()
3. Date Functions
NOW()
SELECT NOW();
DATEDIFF()
TIMESTAMPDIFF()
23 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
4. Mathematical Functions
ROUND() , FLOOR() , CEIL()
SELECT salary,
ROUND(salary) AS rounded,
FLOOR(salary) AS floored,
CEIL(salary) AS ceiled
FROM users;
MOD()
5. Conditional Functions
IF()
24 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
Summary Table
Function Purpose
By default, MySQL operates in AutoCommit mode. This means that every SQL statement
is treated as a transaction and is committed automatically. However, for more control over
when changes are saved, you can turn AutoCommit off and manage transactions
manually.
1. Disabling AutoCommit
When AutoCommit is off, you can explicitly control when to commit or rollback changes.
To disable AutoCommit:
SET autocommit = 0;
25 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
This turns off AutoCommit, meaning that changes you make won't be saved to the database
unless you explicitly tell MySQL to commit them.
“Important: Until you execute a COMMIT , your changes are not permanent.”
Once you’ve made changes and you’re confident that everything is correct, you can use
the COMMIT command to save those changes.
To commit a transaction:
COMMIT;
This saves all the changes made since the last COMMIT or ROLLBACK . After this point, the
changes become permanent.
If you make an error or decide you don't want to save your changes, you can rollback the
transaction to its previous state.
To rollback a transaction:
ROLLBACK;
26 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
Example Workflow
SET autocommit = 0;
COMMIT;
ROLLBACK;
If you want to turn AutoCommit back on (so that every statement is automatically
committed), you can do so with:
SET autocommit = 1;
27 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
Best Practices
A PRIMARY KEY is a constraint in SQL that uniquely identifies each row in a table. It is
one of the most important concepts in database design.
• A PRIMARY KEY :
• Must be unique
• Cannot be NULL
Example:
28 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
At first glance, PRIMARY KEY and UNIQUE might seem similar since both prevent duplicate
values. But there are important differences:
How many allowed Only one per table Can have multiple
In this example:
29 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
“This may fail if the primary key is being used elsewhere (like in a foreign key or
auto_increment column).”
Auto Increment
This means that every time you insert a new row, MySQL will automatically assign a unique
value to the id column. You can change the starting value of AUTO_INCREMENT using:
Key Takeaways
• Use UNIQUE for enforcing non-duplicate values in other columns (like email or
phone).
• You can have only one primary key, but you can have many unique constraints.
30 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
A foreign key is a column that creates a link between two tables. It ensures that the value
in one table must match a value in another table.
You have a users table. Now you want to store each user's address. Instead of putting
address columns inside the users table, you create a separate addresses table, and link
it to users using a foreign key.
Explanation:
31 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
To drop a foreign key, you need to know its constraint name. MySQL auto-generates it if
you don’t specify one, or you can name it yourself:
To drop it:
Suppose the foreign key was not defined during table creation. You can add it later
using ALTER TABLE :
32 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
By default, if you delete a user that has related addresses, MySQL will throw an error. You
can control this behavior with ON DELETE .
Or alter it later:
SET NULL Sets the foreign key to NULL in the child table
33 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
Summary
• Use ON DELETE to control what happens when the parent row is deleted.
In SQL, JOINs are used to combine rows from two or more tables based on related
columns — usually a foreign key in one table referencing a primary key in another.
users table
id name
1 Aarav
2 Sneha
3 Raj
addresses table
id user_id city
1 1 Mumbai
2 2 Kolkata
3 4 Delhi
34 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
1. INNER JOIN
Output:
name city
Aarav Mumbai
Sneha Kolkata
Visual Representation:
users addresses
�� ��
| 1 | | 1 |
| 2 | | 2 |
| | | |
� only matching pairs
2. LEFT JOIN
Returns all rows from the left table ( users ), and matching rows from the right table
( addresses ). If no match is found, NULLs are returned.
35 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
Output:
name city
Aarav Mumbai
Sneha Kolkata
Raj NULL
Visual Representation:
users addresses
�� ��
| 1 | | 1 |
| 2 | | 2 |
| 3 | | |
� all users + matched addresses (or NULL)
3. RIGHT JOIN
Returns all rows from the right table ( addresses ), and matching rows from the left table
( users ). If no match is found, NULLs are returned.
Output:
name city
Aarav Mumbai
Sneha Kolkata
NULL Delhi
36 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
Visual Representation:
users addresses
�� ��
| 1 | | 1 |
| 2 | | 2 |
| | | 4 |
� all addresses + matched users (or NULL)
Summary Table
JOIN Type Description
LEFT JOIN All rows from left table + matching from right
RIGHT JOIN All rows from right table + matching from left
The UNION operator in SQL is used to combine the result sets of two or more SELECT
statements. It removes duplicates by default.
If you want to include all rows including duplicates, use UNION ALL .
Example Scenario
You already have a users table for active users. Now, we’ll create an admin_users table
to store users who are administrators or have special roles. We will then combine the
names from both tables using UNION .
37 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
38 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
If you want to keep duplicate names (if any), use UNION ALL .
You can also select multiple columns as long as both SELECT queries return the same
number of columns with compatible types.
39 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
Rules of UNION
1. The number of columns and their data types must match in all SELECT statements.
• When you have two similar tables (like current and archived data).
• When you need to combine filtered results (e.g., high-salary users from two sources).
Summary
Operator Behavior
A Self JOIN is a regular join, but the table is joined with itself.
40 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
This is useful when rows in the same table are related to each other. For example, when
users refer other users, and we store the ID of the person who referred them in the same
users table.
We’ll extend the existing users table to include a column called referred_by_id , which
holds the id of the user who referred them.
This column:
We want to get each user’s name along with the name of the person who referred them.
41 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
SELECT
[Link],
[Link] AS user_name,
[Link] AS referred_by
FROM users a
LEFT JOIN users b ON a.referred_by_id = [Link];
Explanation:
• LEFT JOIN is used so that users with NULL in referred_by_id are also included.
Sample Output:
id user_name referred_by
1 Aarav NULL
2 Sneha Aarav
3 Raj Aarav
4 Fatima Sneha
Summary
• Use Self JOIN when you need to join a table with itself.
• Use aliases like a and b to differentiate the two instances of the same table.
MySQL Views
42 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
A view in MySQL is a virtual table based on the result of a SELECT query. It does not
store data itself — it always reflects the current data in the base tables.
Creating a View
Suppose we want a view that lists all users earning more than ₹70,000.
This will return all users from the users table where salary is above ₹70,000.
43 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
Output:
id name salary
2 Sneha 75000
5 Fatima 80000
UPDATE users
SET salary = 72000
WHERE name = 'Raj';
New Output:
id name salary
2 Sneha 75000
5 Fatima 80000
3 Raj 72000
“Notice how Raj is now included in the view — without updating the view itself. That’s
because views always reflect live data from the original table.”
44 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
Dropping a View
To remove a view:
Summary
MySQL Indexes
Indexes in MySQL are used to speed up data retrieval. They work like the index of a book
— helping the database engine find rows faster, especially for searches, filters, and joins.
This shows all the indexes currently defined on the users table, including the
automatically created primary key index.
45 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
Suppose you're frequently searching users by their email . You can speed this up by
indexing the email column.
Important Notes
• Indexes slow down INSERT , UPDATE , and DELETE operations slightly (because the
index must be updated)
• Use indexes only when needed (i.e., for columns used in WHERE , JOIN , ORDER BY )
If you often query users using both gender and salary , a multi-column index is more
efficient than separate indexes.
Usage Example:
46 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
This query can take advantage of the combined index on gender and salary .
Because the first column in the index ( gender ) is missing in the filter.
Dropping an Index
To delete an index:
Summary
47 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
Feature Description
Subqueries in MySQL
A subquery is a query nested inside another query. Subqueries are useful for breaking
down complex problems into smaller parts.
• SELECT statements
• WHERE clauses
• FROM clauses
Suppose we want to find all users who earn more than the average salary of all users.
This subquery returns a single value — the average salary — and we compare each user's
salary against it.
48 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
Explanation:
• The inner query: SELECT AVG(salary) FROM users returns the average salary.
• The outer query selects all users with a salary greater than that average.
Subquery with IN
Now let's say we want to find users who have been referred by someone who earns more
than ₹75,000.
Explanation:
• The inner query: SELECT id FROM users WHERE salary > 75000 returns a list of
user IDs (referrers) who earn more than ₹75,000.
49 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
Example in SELECT :
This shows each user's salary along with the overall average.
Summary
Subquery Type Use Case
Subqueries are powerful tools when filtering based on computed or dynamic conditions.
The GROUP BY clause is used to group rows that have the same values in specified
columns. It is typically used with aggregate functions like COUNT , SUM , AVG , MIN , or
MAX .
The HAVING clause is used to filter groups after aggregation — similar to how WHERE
filters individual rows.
50 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
Explanation:
51 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
Output:
referred_by_id total_referred
1 2
2 1
Let’s say we only want to show genders where the average salary is greater than
₹75,000.
• HAVING is used after groups are formed — it's the only way to filter aggregated
values.
52 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
Summary
Clause Purpose Can use aggregates?
Use GROUP BY to organize data, and HAVING to filter those groups based on aggregate
conditions.
ROLLUP
Explanation:
• This will give you a count of users by gender, along with a grand total for all users.
A stored procedure is a saved SQL block that can be executed later. It's useful when you
want to encapsulate logic that can be reused multiple times — like queries, updates, or
conditional operations.
53 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
But when defining stored procedures, we use ; inside the procedure as well. This can
confuse MySQL. To avoid this, we temporarily change the delimiter (e.g. to $$ or // )
while creating the procedure.
DELIMITER $$
DELIMITER ;
Let’s say you want to create a stored procedure that inserts a new user into the users
table.
Example:
DELIMITER $$
54 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
IN p_salary INT
)
BEGIN
INSERT INTO users (name, email, gender, date_of_birth, salary)
VALUES (p_name, p_email, p_gender, p_dob, p_salary);
END$$
DELIMITER ;
This creates a procedure named AddUser that accepts five input parameters.
This will insert the new user into the users table.
Notes
55 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
Summary
Command Purpose
Triggers in MySQL
• Logging changes
56 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
Suppose we want to log every time a new user is inserted into the users table. We'll
create a separate table called user_log to store log entries.
57 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
DELIMITER $$
DELIMITER ;
Explanation:
• AFTER INSERT means the trigger fires after the user is inserted.
• NEW refers to the new row being added to the users table.
• We insert the new user's ID and name into the user_log table.
Dropping a Trigger
58 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
Summary
Trigger Component Description
More on MySQL
This section covers some essential MySQL features and operators that help you write more
powerful and flexible queries.
1. Logical Operators
AND All conditions must be true salary > 50000 AND gender = 'Male'
59 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
3. Wildcard Operators
Wildcards are used with the LIKE operator for pattern matching in text.
_ Matches a single character WHERE name LIKE '_a%' (second letter is 'a')
LIMIT is used to limit the number of rows returned. OFFSET skips a number of rows
before starting to return rows.
60 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
Alternative syntax:
5. DISTINCT Keyword
6. TRUNCATE Keyword
TRUNCATE removes all rows from a table, but keeps the table structure.
61 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
Both CHANGE and MODIFY are used to alter existing columns in a table, but they work
slightly differently.
Conclusion
In this tutorial, we've covered the essentials of SQL, including how to create and manage
databases, tables, and records. With this knowledge, you can start building and querying
your own databases effectively.
Tags
Share
mysql mysql tutorial tutorial mysql learn mysql
62 of 63 5/30/26, 06:53
The Ultimate SQL Tutorial | Blog | CodeWithHarry [Link]
Main Learn
Home Courses
Contact Tutorials
Legal Social
Terms LinkedIn
Privacy YouTube
Refund GitHub
Twitter (X)
Facebook
63 of 63 5/30/26, 06:53