PART 1 of 5  •  about 16 class hours

SQL Foundations

Meet databases, install MySQL 9.7, create tables with the right data types, add and change data, and ask questions with SELECT.

1

Meet Databases & MySQL

10 examples  •  4 h
2

Creating Tables & Data Types

10 examples  •  4 h
3

Inserting, Updating & Deleting Data

10 examples  •  4 h
4

Retrieving Data with SELECT

10 examples  •  4 h
🐬
mysql>
SQL:2023  •  MySQL 9.7 LTS
BrainBit Infotech, Ranchi  |  Complete MySQL Course  |  Keys: ← → navigate   M menu   L SQL Lab   F fullscreen
M1

Meet Databases & MySQL

Every app you use - UPI, IRCTC, your school result site - keeps its data in a database. In this module you meet databases, install MySQL and type your first SQL commands.

  • What data, a database and a DBMS are
  • Tables, rows and columns
  • How an app talks to the MySQL server
  • SQL: the language (SQL:2023 standard)
  • Install MySQL 9.7 LTS + Workbench
  • First commands: CREATE DATABASE, USE, SHOW
  • Rules: semicolons, quotes, comments
  • Read and fix your first errors
YOU WILL BUILD:
A school databaseA shop items tableA notice board database
🐬
about 4 hours
10 practice examples: 5 Easy • 3 Medium • 2 Hard
Complete MySQL Course  |  BrainBit Infotech, Ranchi
M1Where is this used in real work?

Databases are behind every app you use

results.jac.jharkhand.gov.in/result?roll=1021
🏫 JAC Class 10 Result 2026SQL
SubjectMarks
Maths92
Science88
English85
Total265 / 300
mysql> SELECT subject, marks FROM results WHERE roll_no = 1021;
Behind the pageThe website sends one SQL question to the database. The database finds roll 1021 among lakhs of students in a few milliseconds.
📱

UPI, banks, IRCTC

Every payment, ticket and balance is a row in a database table. Banks run millions of SQL statements every minute.
🏫

Local work in Jharkhand

School ERPs, hospital OPD software, shop billing, Jharsewa and state portals all store their data in databases like MySQL.
💼

A skill for every job

Developers, data analysts, DBAs and even accountants use SQL. It is one of the most asked skills in IT job posts.
Complete MySQL Course  |  Part 1  |  Meet Databases & MySQL
M1Animated explainer

From a register to a database

📒
Paper registereasy to start
✘ hard to search 5,000 pages
✘ can be lost or torn
✘ one person at a time
📊
Excel sheetbetter
⚠ slow with lakhs of rows
⚠ anyone can type anything
⚠ two people editing = conflict
🗃️
Database (MySQL)professional
✔ finds 1 row in crores fast
✔ rules stop wrong data
✔ thousands of users at once
✔ backups and security
DefinitionData = raw facts (Priya, 91). Information = data with meaning (Priya scored 91 in Maths). A database is an organised collection of data. A DBMS (Database Management System) like MySQL is the software that stores it, protects it and answers questions about it.
Complete MySQL Course  |  Part 1  |  Meet Databases & MySQL
M1Concept

Tables, rows and columns

students (a TABLE)
student_idnamecitymarks
1Priya KumariRanchi91
2Aman RajPatna78
3Sneha OraonRanchi85
4Rohit MahtoDhanbad64
database: school➤table: students➤row: one student
📋

Table

Data about one kind of thing (students, products, orders). Like one sheet in Excel.
➡️

Row (record)

One item: one student, one order. A table can have crores of rows.
⬇️

Column (field)

One property with a fixed type: name is text, marks is a number.
🔑

Primary key

A column that is unique for every row, like student_id or Aadhaar number. It identifies the row.
Complete MySQL Course  |  Part 1  |  Meet Databases & MySQL
M1Animated explainer

How your app talks to MySQL: client and server

💻
ClientWorkbench, mysql> or your app
➤
SQL over the network
port 3306
🐬
MySQL Servermysqld (always running)
⇆
reads and writes
💾
Data files on diskInnoDB tables (.ibd files)
result: rows + "2 rows in set (0.00 sec)"⬅the client shows the result as a table
Complete MySQL Course  |  Part 1  |  Meet Databases & MySQL
M1Concept

SQL: one language, many databases

SQL (Structured Query Language, say "S-Q-L" or "sequel") is the language for talking to relational databases. It is an international standard: ISO/IEC 9075. The current edition is SQL:2023.

1974
IBM researchers create SEQUEL, later called SQL
1986-87
First ANSI and ISO SQL standard (SQL-86)
1992
SQL-92: JOIN syntax we still use
1999-2003
Recursive queries, window functions
2016
SQL:2016 adds JSON support
2023
SQL:2023 - current standard (JSON type, property graphs)

Databases that speak SQL

MySQLSQL
PostgreSQLSQL
SQL ServerSQL
OracleSQL
SQLiteSQL
Good newsAbout 80-90% of what you learn here works in every SQL database. Where MySQL differs from the standard, look for the SQL standard vs MySQL box.
📜 SQL standard vs MySQL
SQL:2023 standardFETCH FIRST 5 ROWS ONLY
MySQL 9.7LIMIT 5 (MySQL keeps its own short form)
Complete MySQL Course  |  Part 1  |  Meet Databases & MySQL
M1Concept

MySQL versions: which one should you install?

ReleaseTypeReleasedUse it for
MySQL 9.7LTSApril 2026This course - new projects, long support (to 2034)
MySQL 8.4LTSApril 2024Many existing servers and hosting
MySQL 26.10InnovationOctober 2026Newest features, upgrade every quarter
MySQL 8.0old2018End of life (April 2026) - upgrade it
MariaDB (XAMPP)other DBMS-A MySQL "cousin": most SQL in this course works
LTS = Long-Term SupportSame features for years, only bug and security fixes. Best for students, schools and companies. Innovation releases now use calendar numbers (26.10 = October 2026).
💻

MySQL Community Server

Free and open source (GPL). The database server itself. Download from dev.mysql.com.
🎨

MySQL Workbench

Free visual tool: write SQL, see results in a grid, draw ER diagrams.
⌨

mysql command-line client

Comes with the server. Professionals use it on servers with no screen.
🔬

Our lab note

The REAL RUN panels were recorded on MySQL 8.0.46. Every command used works the same on 8.4 and 9.7. Your version number will differ.
Complete MySQL Course  |  Part 1  |  Meet Databases & MySQL
M1Concept

Install your MySQL workshop (Windows)

  1. 1
    Go to dev.mysql.com/downloads/installer and download MySQL Installer for Windows (choose the 9.7 LTS version).
  2. 2
    Choose setup type Custom: add MySQL Server 9.7 and MySQL Workbench. Click Execute.
  3. 3
    Keep the default port 3306. Choose "Use Strong Password Encryption".
  4. 4
    Set a root password you will remember (write it in your notebook). Root is the admin user.
  5. 5
    Keep "Start the MySQL Server at System Startup" ticked. Finish the installer.
  6. 6
    Open MySQL Workbench, click the Local instance 3306 tile and type your password.
  7. 7
    Make the practice folder D:\mysql-practice with one sub-folder per module: m01, m02 ...
MySQL Workbench - Local instance 3306
SCHEMAS
▸ school
▸ bazaar
▸ sys
SELECT * FROM students;
student_idnamecity
1Priya KumariRanchi
2Aman RajPatna
⚡ = Execute (Ctrl+Shift+Enter)
Using XAMPP already?XAMPP includes MariaDB, not MySQL. You can still follow most of this course, but install real MySQL for the advanced modules. Do not run both on port 3306 at the same time.
Command lineOpen "MySQL 9.7 Command Line Client" from the Start menu, or in a terminal type mysql -u root -p
Complete MySQL Course  |  Part 1  |  Meet Databases & MySQL
M1Concept

SQL commands come in 5 families

🏗️

DDL - Data Definition

Build the structure: CREATE, ALTER, DROP, TRUNCATE, RENAME.
✏️

DML - Data Manipulation

Change the data: INSERT, UPDATE, DELETE.
🔍

DQL - Data Query

Ask questions: SELECT. You will use it more than anything else.
🔐

DCL - Data Control

Who can do what: GRANT, REVOKE, CREATE USER.
🔄

TCL - Transaction Control

All-or-nothing changes: START TRANSACTION, COMMIT, ROLLBACK.
🛈

Utility

Look around: SHOW, DESCRIBE, USE, EXPLAIN.
Memory trickBuild it (DDL), fill it (DML), ask it (DQL), guard it (DCL), make it safe (TCL).
Complete MySQL Course  |  Part 1  |  Meet Databases & MySQL
M1Concept

Your first SQL commands

Type these one by one in Workbench or at the mysql> prompt.

  • SHOW DATABASES; lists all databases. MySQL keeps its own system databases (mysql, sys ...). Never delete them.
  • CREATE DATABASE coaching; makes a new, empty database.
  • USE coaching; selects it, so the next commands work inside it.
  • SELECT DATABASE(); shows which database you are in.
Every statement ends with ;The semicolon tells MySQL "my statement is complete, run it now". Forget it and the prompt changes to -> and waits.
first.sql
REAL RUN
Complete MySQL Course  |  Part 1  |  Meet Databases & MySQL
M1Concept

SQL writing rules

  • Keywords are not case-sensitive: SELECT = select. We write keywords in CAPITALS so they stand out.
  • Text goes in single quotes: 'Ranchi'. Numbers do not: 91.
  • Spaces and new lines do not matter. Split long statements over lines.
  • Comments: -- note (dash dash space), # note or /* ... */. MySQL ignores them.
  • Names (tables, columns): use snake_case like admission_date. If a name has a space, wrap it in backticks `like this` - better to avoid spaces.
📜 SQL standard vs MySQL
SQL:2023 standardText in 'single quotes', names in "double quotes"
MySQL 9.7Text in single quotes; names in `backticks`. Double quotes also mean text unless ANSI_QUOTES mode is on.
rules.sql
REAL RUN
Complete MySQL Course  |  Part 1  |  Meet Databases & MySQL
M1Practice 1 of 10  •  Easy

Example 1: SELECT as a calculator

● Easy💼 Real project: Quick checks in billing and fee counters
SELECT can work without any table. Use it to calculate, test functions or print text. AS gives the result column a friendly name.
ex01.sql
REAL RUN
✍ Try it yourself Calculate the total cost of 3 notebooks at Rs 45 each plus a pen at Rs 10. Name the column total.
SELECT 3 * 45 + 10 AS total;
Complete MySQL Course  |  Part 1  |  Meet Databases & MySQL
M1Practice 2 of 10  •  Easy

Example 2: Create the coaching database

● Easy💼 Real project: First step of every new project: a database
One MySQL server can hold many databases - one per project. IF NOT EXISTS avoids an error if it is already there.
ex02.sql
REAL RUN
✍ Try it yourself Create a database called my_shop, switch to it and check with SELECT DATABASE();
Three statements: CREATE DATABASE my_shop; USE my_shop; SELECT DATABASE();
Complete MySQL Course  |  Part 1  |  Meet Databases & MySQL
M1Practice 3 of 10  •  Easy

Example 3: Look inside the school database

● Easy💼 Real project: Exploring a database you did not build
On a new job, you first explore: which databases exist, which tables are inside, and what data a small table holds. The school sample database is used in many modules.
ex03.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Show all rows of the teachers table.
SELECT * FROM teachers; - the * means "all columns".
Complete MySQL Course  |  Part 1  |  Meet Databases & MySQL
M1Practice 4 of 10  •  Easy

Example 4: Server facts: version, time and user

● Easy💼 Real project: Checking a server before you work on it
Built-in functions tell you about the server. @@port and @@character_set_server are system variables (settings).
ex04.sql
REAL RUN
The lab server shows 8.0.46 and the build time. Your PC shows 9.7.x and your own clock.
✍ Try it yourself Also show today's date only, with CURDATE().
Add , CURDATE() AS today to the first SELECT.
Complete MySQL Course  |  Part 1  |  Meet Databases & MySQL
M1Practice 5 of 10  •  Easy

Example 5: Comments and multi-line statements

● Easy💼 Real project: Writing scripts other people can read
Real SQL files have comments that explain why. One statement can span many lines - MySQL runs it when it reaches the ;
ex05.sql
REAL RUN
✍ Try it yourself Add a comment line above the SELECT that says who wrote it, and a fourth column for 12 months.
Comment: -- Written by Priya. Column: 750 * 12 AS twelve_months
Complete MySQL Course  |  Part 1  |  Meet Databases & MySQL
M1Practice 6 of 10  •  Medium

Example 6: Your first table: shop items

● Medium💼 Real project: Kirana shop stock list
A table needs a name and columns with types. INT = whole number, VARCHAR(40) = text up to 40 characters, DECIMAL(8,2) = money. (Data types are explained fully in M2.)
ex06.sql
REAL RUN
✍ Try it yourself Add a fourth item: Maggi Noodles at Rs 14. Then show the table again.
INSERT INTO items VALUES (4, 'Maggi Noodles', 14.00);
Complete MySQL Course  |  Part 1  |  Meet Databases & MySQL
M1Practice 7 of 10  •  Medium

Example 7: Explore with information_schema

● Medium💼 Real project: Documenting a database for a new team member
information_schema is a built-in database that describes all other databases: tables, columns, types. You can query it like any table.
ex07.sqlschool_setup.sql
REAL RUN
✍ Try it yourself List the column names and data types of the students table.
SELECT column_name, data_type FROM information_schema.columns WHERE table_schema='school' AND table_name='students';
Complete MySQL Course  |  Part 1  |  Meet Databases & MySQL
M1Practice 8 of 10  •  Medium

Example 8: Run a whole .sql script file

● Medium💼 Real project: Setting up a project database in one go
Instead of typing, save statements in a .sql file and run it all at once. -t prints tables; -p asks for the password. In Workbench: File > Open SQL Script, then ⚡.
welcome.sql
REAL RUN
✍ Try it yourself Save the sample database file school_setup.sql (from the Lab) and load it with mysql -u root -p < school_setup.sql
You must be in the folder where the file is saved (use cd D:\mysql-practice\m01).
Complete MySQL Course  |  Part 1  |  Meet Databases & MySQL
M1Practice 9 of 10  •  Hard

Example 9: Mini notice board database

● Hard💼 Real project: School / office notice board app
A complete small project: database, table with an auto-numbered id, three notices, and a query that shows the newest first. AUTO_INCREMENT gives ids 1, 2, 3 automatically.
ex09.sql
REAL RUN
✍ Try it yourself Add a notice "Winter vacation from 25 December" by the Principal dated today and run the SELECT again.
You do not give notice_id - AUTO_INCREMENT fills 4 for you.
Complete MySQL Course  |  Part 1  |  Meet Databases & MySQL
M1Practice 10 of 10  •  Hard

Example 10: Read and fix your first errors

● Hard💼 Real project: Debugging: the most important daily skill
Each wrong line below gives a real MySQL error. Read the error number and the message: it tells you exactly what is wrong. 1064 = typing (syntax) mistake, 1146 = table not found, 1054 = column not found. Text without quotes is read as a column name, so Ranchi also gives 1054.
⚠ The error in this example is on purpose.
ex10.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Fix each wrong line yourself in the Lab and run it again.
SELEC → SELECT, studnets → students, naam → name, Ranchi → 'Ranchi'
Complete MySQL Course  |  Part 1  |  Meet Databases & MySQL
M1Check your understanding

Quick Quiz

Click an answer. Wrong answers shake; the right one turns green and explains why.

Q1. Which software stores and manages the database?
✔ A DBMS stores, protects and queries data.
Q2. What does USE school; do?
✔ Following statements now work inside school.
Q3. Which is an error for a missing table?
✔ 1146 = table doesn't exist; 1064 = syntax; 1054 = unknown column.
🎯
Your score: 0 / 3 (first try counts)
Answer all questions. Discuss any wrong answer with your partner before moving on.
Complete MySQL Course  |  Part 1  |  Meet Databases & MySQL
M1Module summary

Recap: Meet Databases & MySQL

What you learned in M1

  • ✔A database is organised data; MySQL is the DBMS that manages it.
  • ✔Data lives in tables: rows are items, columns are properties.
  • ✔Apps are clients; they send SQL to the MySQL server on port 3306.
  • ✔SQL is an ISO standard (SQL:2023); MySQL 9.7 LTS is our version.
  • ✔CREATE DATABASE, USE, SHOW, SELECT - and end with ;
  • ✔Error numbers (1064, 1146, 1054) tell you what to fix.
🏆

Module 1 complete!

You practised 10 real examples on a real MySQL server.

👉 Coming next

M2 Creating Tables & Data Types: choose the right type for names, money, dates and Hindi text, and design real tables.
Complete MySQL Course  |  Part 1  |  Meet Databases & MySQL
M2

Creating Tables & Data Types

A table is only as good as its design. Learn to choose the right data type for names, money, dates and Hindi text, and to change a table safely when the project grows.

  • CREATE TABLE step by step
  • Numbers: INT, BIGINT, DECIMAL
  • Why money must never be FLOAT
  • Text: CHAR, VARCHAR, TEXT and utf8mb4
  • Dates and times
  • BOOLEAN, ENUM and DEFAULT
  • DESCRIBE and SHOW CREATE TABLE
  • ALTER, RENAME, DROP, TRUNCATE
YOU WILL BUILD:
Product price listHospital OPD registerBank account table
🏗️
about 4 hours
10 practice examples: 5 Easy • 3 Medium • 2 Hard
Complete MySQL Course  |  BrainBit Infotech, Ranchi
M2Where is this used in real work?

Every form field becomes a typed column

opd.sadarhospital-ranchi.in/register
🏥 Sadar Hospital Ranchi - OPD Registration
Patient name
Sunita Devi VARCHAR(60)
Age
42 TINYINT
Mobile
9431043110 CHAR(10)
Visit date
25-11-2026 DATE
Fee paid (Rs)
20.00 DECIMAL(7,2)
Gender
Female ENUM('M','F','O')
Address (Hindi)
हरमू, राँची utf8mb4
Admitted?
No BOOLEAN
🎯

Types protect data

If age is a number column, nobody can save "forty" by mistake. MySQL rejects wrong data.
💾

Types save space and time

A TINYINT uses 1 byte, a BIGINT 8 bytes. For 1 crore rows that is 70 MB of difference - and smaller is faster.
💰

Types keep money exact

GST, fees, bank balances must be DECIMAL. A wrong type can lose paise - and auditors notice!
Complete MySQL Course  |  Part 1  |  Creating Tables & Data Types
M2Concept

CREATE TABLE: anatomy of a table

A table definition lists each column name followed by its data type and optional rules.

  • CREATE TABLE name ( ... ); - columns go inside brackets, separated by commas (no comma after the last one).
  • INT, VARCHAR(50), DATE ... are data types.
  • NOT NULL = value is required. PRIMARY KEY = unique id (details in M5).
  • DESCRIBE table; (or DESC) shows the structure.
Naming rulesUse small letters and underscores: admission_date, not Admission Date. Table names are usually plural: students, orders.
create.sql
REAL RUN
Complete MySQL Course  |  Part 1  |  Creating Tables & Data Types
M2Concept

Number types: pick the right size

TypeSizeRange (signed)Use for
TINYINT1 byte-128 to 127age, rating 1-5, yes/no
SMALLINT2 bytes-32,768 to 32,767year, small counts
INT4 bytesabout ±2.1 billion (214 crore)ids, quantity, marks
BIGINT8 bytesabout ±9.2 quintillionUPI transaction ids, views count
DECIMAL(p,s)variesexact: p digits, s after the pointmoney, GST, marks %
FLOAT / DOUBLE4 / 8 bytesapproximatescience, GPS, sensor readings

UNSIGNED means "no negatives" and doubles the positive range: TINYINT UNSIGNED = 0 to 255.

DECIMAL(10,2)10 digits in total, 2 after the point: up to 99,999,999.99 (about 10 crore). Perfect for prices and fees.
INT(11)?Old tutorials write INT(11). The number in brackets is only a display width and is deprecated in MySQL 8+. Just write INT.
📜 SQL standard vs MySQL
SQL:2023 standardINTEGER, SMALLINT, BIGINT, DECIMAL, FLOAT, BOOLEAN
MySQL 9.7All of these, plus TINYINT, MEDIUMINT and UNSIGNED (MySQL extras)
Complete MySQL Course  |  Part 1  |  Creating Tables & Data Types
M2Animated explainer

Why money must be DECIMAL, not FLOAT

🌊
DOUBLE (floating point)
0.1 is stored as
0.1000000000000000055511...
0.1 + 0.2 = 0.30000000000000004
🧮
DECIMAL(10,2) (exact)
0.10 is stored as
0.10 (digits, exactly)
0.10 + 0.20 = 0.30
Complete MySQL Course  |  Part 1  |  Creating Tables & Data Types
M2Concept

Text types and Hindi: utf8mb4

  • CHAR(n) - fixed length. Good for codes that are always the same size: PIN CHAR(6), mobile CHAR(10), state code CHAR(2).
  • VARCHAR(n) - variable length up to n characters. Names, emails, addresses. Most used.
  • TEXT - long text (up to 65,535 bytes): reviews, notices, descriptions.
  • utf8mb4 is MySQL's default character set. It stores every language - Hindi, Santhali (Ol Chiki), Bengali, Urdu - and even emoji.
Characters vs bytesCHAR_LENGTH() counts letters. LENGTH() counts bytes. Hindi letters need 3 bytes each in utf8mb4.
text.sql
REAL RUN
Complete MySQL Course  |  Part 1  |  Creating Tables & Data Types
M2Concept

Dates and times

TypeLooks likeUse for
DATE'2026-11-25'date of birth, due date
TIME'09:30:00'class start time
DATETIME'2026-11-25 09:30:00'appointment, order time
TIMESTAMPsame, stored in UTC"created at", auto times
YEAR2026passing year
Always YYYY-MM-DDMySQL writes dates as year-month-day. Type '2026-11-25', not 25/11/2026. You can show dates in Indian style later with DATE_FORMAT (M6).
dates.sql
REAL RUN
Complete MySQL Course  |  Part 1  |  Creating Tables & Data Types
M2Concept

BOOLEAN, ENUM and DEFAULT

  • BOOLEAN is stored as TINYINT(1): TRUE = 1, FALSE = 0.
  • ENUM('a','b','c') allows only values from a fixed list - perfect for status, gender, payment mode.
  • DEFAULT x fills a value when the INSERT does not give one.
📜 SQL standard vs MySQL
SQL:2023 standardA real BOOLEAN type with TRUE / FALSE / UNKNOWN
MySQL 9.7BOOLEAN is a synonym for TINYINT(1); results show 1 and 0
Strict mode is your friendMySQL 8+ runs in strict mode: a value outside the ENUM list is an error (MySQL's message is Data truncated for column), not a silent blank.
enum.sql
REAL RUN
Complete MySQL Course  |  Part 1  |  Creating Tables & Data Types
M2Concept

Changing a table: ALTER TABLE

Projects grow. ALTER TABLE changes a table without losing its data.

  • ADD COLUMN mobile CHAR(10) - new column (existing rows get NULL or the DEFAULT).
  • MODIFY COLUMN name VARCHAR(80) - change type or size.
  • RENAME COLUMN old TO new - new name, same data.
  • DROP COLUMN x - removes the column and its data.
  • RENAME TABLE a TO b - new table name.
Careful on live serversOn a table with crores of rows, ALTER can take minutes. Take a backup first and do it when few users are online.
alter.sqlschool_setup.sql
REAL RUN
Complete MySQL Course  |  Part 1  |  Creating Tables & Data Types
M2Concept

Removing things: DROP, TRUNCATE and DELETE

🗑️

DROP TABLE t

Deletes the table and its structure. It is gone. Used when a table is no longer needed.
🧹

TRUNCATE TABLE t

Empties all rows very fast and resets AUTO_INCREMENT to 1. The empty table stays.
✂️

DELETE FROM t WHERE ...

Removes chosen rows (M3). Slower, but can be rolled back inside a transaction.
🛡️

IF EXISTS / IF NOT EXISTS

DROP TABLE IF EXISTS t and CREATE TABLE IF NOT EXISTS t avoid errors in scripts you run again and again.
⚠️

No undo button

DROP and TRUNCATE cannot be undone with ROLLBACK. Always keep a backup (M18).
📝

Good habit

Write DROP statements by hand, read them twice, check which database you are in with SELECT DATABASE();
Complete MySQL Course  |  Part 1  |  Creating Tables & Data Types
M2Practice 1 of 10  •  Easy

Example 1: Students table with good types

● Easy💼 Real project: School admission software
Each column has a type that fits its data: a whole-number id, text names, a fixed-size mobile, a date of birth. SHOW CREATE TABLE prints the full definition MySQL stored.
ex01.sql
REAL RUN
✍ Try it yourself Add a column email VARCHAR(60) to the CREATE TABLE and run it again (drop the database first).
Start the file with DROP DATABASE IF EXISTS dav_school;
Complete MySQL Course  |  Part 1  |  Creating Tables & Data Types
M2Practice 2 of 10  •  Easy

Example 2: Product price list with DECIMAL

● Easy💼 Real project: Shop billing software
DECIMAL(8,2) stores prices like 58.50 exactly. MySQL shows two decimals even for whole prices, so bills always look right.
ex02.sql
REAL RUN
✍ Try it yourself Try inserting a stock of -5. What does MySQL say about UNSIGNED?
You get ERROR 1264 "Out of range value" - UNSIGNED blocks negatives.
Complete MySQL Course  |  Part 1  |  Creating Tables & Data Types
M2Practice 3 of 10  •  Easy

Example 3: Hindi and English names together

● Easy💼 Real project: Bilingual government and school records
Because the table uses utf8mb4 (the default), Hindi, Bengali and even emoji are stored correctly next to English.
ex03.sql
REAL RUN
✍ Try it yourself Add your own name in Hindi and English.
Copy one row: (4, 'Your Name', 'आपका नाम', 'Your village')
Complete MySQL Course  |  Part 1  |  Creating Tables & Data Types
M2Practice 4 of 10  •  Easy

Example 4: Dates of birth and admission

● Easy💼 Real project: Admission and age records
Dates are typed as 'YYYY-MM-DD'. A DATETIME with DEFAULT CURRENT_TIMESTAMP records when the row was created, automatically.
ex04.sql
REAL RUN
✍ Try it yourself Insert a date like '2026-02-30'. What happens?
ERROR 1292: Incorrect date value. MySQL checks that dates are real.
Complete MySQL Course  |  Part 1  |  Creating Tables & Data Types
M2Practice 5 of 10  •  Easy

Example 5: Read a table design: DESCRIBE

● Easy💼 Real project: Understanding a database you inherited
DESCRIBE shows each column: type, whether NULL is allowed, the key (PRI = primary, MUL = foreign/indexed) and the default.
ex05.sqlbazaar_setup.sql
REAL RUN
✍ Try it yourself Describe the customers and order_items tables. Which table has two PRI columns?
order_items: its primary key is (order_id, product_id) - a composite key.
Complete MySQL Course  |  Part 1  |  Creating Tables & Data Types
M2Practice 6 of 10  •  Medium

Example 6: ENUM for order status

● Medium💼 Real project: E-commerce order tracking
An ENUM column only accepts the listed values. A typing mistake like "Deliverd" is rejected with ERROR 1265 Data truncated, so reports never show strange statuses.
⚠ The error in this example is on purpose.
ex06.sql
REAL RUN
✍ Try it yourself Add a new status Cancelled with ALTER TABLE ... MODIFY COLUMN status ENUM(...).
Repeat the full list in MODIFY and add 'Cancelled' at the end.
Complete MySQL Course  |  Part 1  |  Creating Tables & Data Types
M2Practice 7 of 10  •  Medium

Example 7: ALTER: add mobile and email

● Medium💼 Real project: Upgrading a live customer table
The shop now wants mobile and email. ADD COLUMN ... AFTER places the new column at a chosen position. Old rows get NULL (no value yet).
ex07.sql
REAL RUN
✍ Try it yourself Add a column joined_on DATE DEFAULT (CURRENT_DATE) and see what old rows get.
With an expression default in brackets, existing rows get today's date.
Complete MySQL Course  |  Part 1  |  Creating Tables & Data Types
M2Practice 8 of 10  •  Medium

Example 8: FLOAT vs DECIMAL: the money bug

● Medium💼 Real project: Accounts and GST software
The same amounts are added 3 times in a DOUBLE column and a DECIMAL column. The DOUBLE total is not exactly 0.6 - and the equality check fails!
ex08.sql
REAL RUN
✍ Try it yourself Try the same with FLOAT instead of DOUBLE. Is it better or worse?
FLOAT is even less precise (about 7 digits). Money is always DECIMAL.
Complete MySQL Course  |  Part 1  |  Creating Tables & Data Types
M2Practice 9 of 10  •  Hard

Example 9: Hospital OPD register design

● Hard💼 Real project: Hospital management system (HMS)
A real table design with the right type for every field: auto ids, required fields, ENUM for gender, DECIMAL fee, DATETIME visit time and a default for the department.
ex09.sql
REAL RUN
✍ Try it yourself Add a column doctor VARCHAR(50) and a column token_no SMALLINT. Fill them for visit 1 later with UPDATE (M3).
Use one ALTER TABLE with two ADD COLUMN parts separated by a comma.
Complete MySQL Course  |  Part 1  |  Creating Tables & Data Types
M2Practice 10 of 10  •  Hard

Example 10: Bank account table for crores

● Hard💼 Real project: Cooperative bank core software
Balances can be over 1 crore, so DECIMAL(15,2) (up to 9,999 crore). Account numbers are long digit strings with leading zeros, so they are text, not numbers. A too-big value is rejected (error on purpose).
⚠ The error in this example is on purpose.
ex10.sql
REAL RUN
✍ Try it yourself Why would account_no INT be wrong? Try inserting 00123400567801 into an INT column.
INT drops the leading zeros (123400567801) and is too small for 14 digits in general.
Complete MySQL Course  |  Part 1  |  Creating Tables & Data Types
M2Check your understanding

Quick Quiz

Click an answer. Wrong answers shake; the right one turns green and explains why.

Q1. Best type for a product price?
✔ DECIMAL keeps paise exact.
Q2. Best type for a 6-digit PIN code like 834001?
✔ It is a code, never used for maths, always 6 characters.
Q3. Which statement empties a table but keeps its structure?
✔ TRUNCATE removes all rows and resets AUTO_INCREMENT.
🎯
Your score: 0 / 3 (first try counts)
Answer all questions. Discuss any wrong answer with your partner before moving on.
Complete MySQL Course  |  Part 1  |  Creating Tables & Data Types
M2Module summary

Recap: Creating Tables & Data Types

What you learned in M2

  • ✔A table = columns with names and data types (+ rules like NOT NULL).
  • ✔Whole numbers: TINYINT / INT / BIGINT. Money: DECIMAL, never FLOAT.
  • ✔Text: CHAR for fixed codes, VARCHAR for names, TEXT for long text. utf8mb4 stores Hindi.
  • ✔Dates are typed as 'YYYY-MM-DD'; DATETIME and TIMESTAMP add time.
  • ✔ENUM limits values; DEFAULT fills missing values; BOOLEAN is 1 / 0.
  • ✔ALTER TABLE changes structure; DROP removes; TRUNCATE empties.
🏆

Module 2 complete!

You practised 10 real examples on a real MySQL server.

👉 Coming next

M3 Inserting, Updating & Deleting Data: add rows, fix mistakes with UPDATE, remove rows with DELETE - safely.
Complete MySQL Course  |  Part 1  |  Creating Tables & Data Types
M3

Inserting, Updating & Deleting Data

Tables are empty boxes until you fill them. Learn to add rows, fix mistakes and remove data - and the safety habits that stop one wrong command from destroying a whole table.

  • INSERT one row and many rows
  • Column lists, DEFAULT and NULL
  • INSERT ... SELECT (copy rows)
  • UPDATE with WHERE
  • DELETE and TRUNCATE
  • Upsert: ON DUPLICATE KEY UPDATE
  • INSERT IGNORE and REPLACE
  • Safe-update habits
YOU WILL BUILD:
Admission entriesFee hike scriptDaily mandi price upsert
✏️
about 4 hours
10 practice examples: 5 Easy • 3 Medium • 2 Hard
Complete MySQL Course  |  BrainBit Infotech, Ranchi
M3Where is this used in real work?

Every click that saves something runs INSERT, UPDATE or DELETE

bazaar.jharkhand.shop/cart
🛒 Your cart
ItemQtyPrice
Thekua Pack 500g2440.00
Tussar Silk Saree14500.00
➕ Add to cart
INSERT
🔄 Change qty
UPDATE
❌ Remove
DELETE
📝

Forms and apps

Admission forms, sign-up pages, billing screens - the Save button sends an INSERT. The Edit button sends an UPDATE.
📈

Daily data loads

Mandi prices, attendance, sales from every branch are inserted or "upserted" (insert-or-update) every day.
⚠️

Danger zone

One UPDATE or DELETE without WHERE changes every row. Real companies have lost data this way. You will learn the safety habits.
Complete MySQL Course  |  Part 1  |  Inserting, Updating & Deleting Data
M3Concept

INSERT: add rows to a table

  • Always list the columns: INSERT INTO t (col1, col2) VALUES (...). Your SQL keeps working even if someone adds a column later.
  • Several rows in one statement: separate the brackets with commas. Faster than many single INSERTs.
  • Columns you leave out get their DEFAULT, or NULL, or the next AUTO_INCREMENT number.
  • MySQL replies Query OK, 3 rows affected.
Text needs quotes, numbers do not('Aman', 78). A name with an apostrophe is written twice: 'D''Souza'.
insert.sql
REAL RUN
Complete MySQL Course  |  Part 1  |  Inserting, Updating & Deleting Data
M3Concept

NULL: "no value yet"

NULL means unknown or missing - not zero, not an empty string.

  • A student who has not taken the test has score NULL, not 0.
  • Test with IS NULL / IS NOT NULL. = NULL never matches anything!
  • NOT NULL on a column makes a value compulsory.
The big NULL trapscore = NULL gives no rows because NULL is "unknown", and unknown = unknown is also unknown. Always use IS NULL.
nulls.sqlschool_setup.sql
REAL RUN
Complete MySQL Course  |  Part 1  |  Inserting, Updating & Deleting Data
M3Animated explainer

UPDATE with and without WHERE

fees
idnamefee
1Priya4500
2Aman3000
3Sneha4000
good.sql
UPDATE fees
SET fee = fee * 1.10
WHERE id = 1;
danger.sql
UPDATE fees
SET fee = fee * 1.10;
-- WHERE forgotten!
3 rows affected - every student's fee changed!
Complete MySQL Course  |  Part 1  |  Inserting, Updating & Deleting Data
M3Concept

UPDATE: change existing rows

UPDATE table SET column = new_value WHERE condition;

  • Change several columns at once: SET a = 1, b = 2.
  • Use the old value: SET stock = stock - 2.
  • MySQL reports Rows matched (found by WHERE) and Changed (actually different).
Preview firstRun SELECT * FROM t WHERE ... with the same WHERE. If it shows the right rows, change SELECT * to UPDATE ... SET.
update.sqlbazaar_setup.sql
REAL RUN
Complete MySQL Course  |  Part 1  |  Inserting, Updating & Deleting Data
M3Concept

DELETE and safe updates mode

DELETE FROM table WHERE condition; removes the matching rows.

  • DELETE without WHERE removes all rows (the table stays).
  • Safe updates mode (SET sql_safe_updates = 1, on by default in Workbench) refuses UPDATE/DELETE that do not use a key column in WHERE.
  • Rows used by another table (foreign key) cannot be deleted - MySQL protects them (M5).
This error is on purposeError 1175 below is MySQL saving you from deleting the whole table.
delete.sqlschool_setup.sql
REAL RUN
Complete MySQL Course  |  Part 1  |  Inserting, Updating & Deleting Data
M3Concept

Insert or update? Upsert, IGNORE and REPLACE

StatementIf the key is newIf the key already exists
INSERTadds the rowERROR 1062 Duplicate entry
INSERT IGNOREadds the rowskips it with a warning
INSERT ... ON DUPLICATE KEY UPDATEadds the rowupdates the existing row (upsert)
REPLACEadds the rowdeletes the old row, inserts the new one
Modern upsert syntax (MySQL 8.0.19+)Give the new row a name with AS new and use new.column. The old VALUES(col) function is deprecated - avoid it in new code.
upsert.sql
INSERT INTO stock (item, qty)
VALUES ('Rice', 50) AS new
ON DUPLICATE KEY UPDATE
  qty = stock.qty + new.qty;
📜 SQL standard vs MySQL
SQL:2023 standardMERGE INTO ... WHEN MATCHED THEN UPDATE WHEN NOT MATCHED THEN INSERT
MySQL 9.7No MERGE. Use INSERT ... ON DUPLICATE KEY UPDATE
REPLACE warningREPLACE deletes then inserts, so columns you did not give are reset to defaults. Prefer the upsert.
Complete MySQL Course  |  Part 1  |  Inserting, Updating & Deleting Data
M3Practice 1 of 10  •  Easy

Example 1: Admit new students

● Easy💼 Real project: Admission desk software
Three new students arrive. One multi-row INSERT with a column list adds them; AUTO_INCREMENT gives the next ids (13, 14, 15).
ex01.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Admit yourself into section 10-A. Leave out email - what value does it get?
Columns you leave out become NULL (no DEFAULT is set for email).
Complete MySQL Course  |  Part 1  |  Inserting, Updating & Deleting Data
M3Practice 2 of 10  •  Easy

Example 2: Insert many products at once

● Easy💼 Real project: Uploading a new stock list
A new delivery of Jharcraft items arrives. Listing columns lets us skip product_id (auto number) and stock (DEFAULT 0 applies to the last one).
ex02.sqlbazaar_setup.sql
REAL RUN
✍ Try it yourself Add two books of your choice to category 4 (Books).
Example: ('Sahitya Sagar', 4, 210.00, 15, 'NCERT')
Complete MySQL Course  |  Part 1  |  Inserting, Updating & Deleting Data
M3Practice 3 of 10  •  Easy

Example 3: Fix a spelling mistake

● Easy💼 Real project: Correcting data entry errors
The clerk typed the city wrong for student 6. Preview with SELECT, then UPDATE only that row using the primary key.
ex03.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Student 2 (Aman Raj) gives his email aman.raj@gmail.com. Save it.
UPDATE students SET email = 'aman.raj@gmail.com' WHERE student_id = 2;
Complete MySQL Course  |  Part 1  |  Inserting, Updating & Deleting Data
M3Practice 4 of 10  •  Easy

Example 4: Remove a cancelled order

● Easy💼 Real project: Order management
Order 1006 was cancelled. Its items must be deleted first (they point to the order), then the order itself.
ex04.sqlbazaar_setup.sql
REAL RUN
✍ Try it yourself What happens if you delete the order first? Try it on a fresh copy.
ERROR 1451: Cannot delete a parent row - the foreign key in order_items protects it.
Complete MySQL Course  |  Part 1  |  Inserting, Updating & Deleting Data
M3Practice 5 of 10  •  Easy

Example 5: Default values in action

● Easy💼 Real project: Library membership register
When a column has a DEFAULT, you can skip it, or write the word DEFAULT on purpose.
ex05.sql
REAL RUN
joined_on shows the day the lab ran this. Yours shows your date.
✍ Try it yourself Change the default plan to Silver with ALTER TABLE members ALTER COLUMN plan SET DEFAULT 'Silver'; and insert a new member.
Only new rows get the new default; old rows keep 'Basic'.
Complete MySQL Course  |  Part 1  |  Inserting, Updating & Deleting Data
M3Practice 6 of 10  •  Medium

Example 6: Fee hike of 10% for one course

● Medium💼 Real project: Annual fee revision
Only the Python course fee rises by 10%. ROUND(..., 0) keeps whole rupees. The WHERE keeps all other courses safe.
ex06.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Give a Rs 500 discount on all 3-month courses with one UPDATE.
UPDATE courses SET fee = fee - 500 WHERE duration_months = 3;
Complete MySQL Course  |  Part 1  |  Inserting, Updating & Deleting Data
M3Practice 7 of 10  •  Medium

Example 7: Copy toppers into a merit table

● Medium💼 Real project: Scholarship and merit list
INSERT ... SELECT copies rows from a query into another table - no typing. Here every student with 85+ marks goes into the merit list.
ex07.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Make a table ranchi_students and copy only students from Ranchi into it.
CREATE TABLE ... then INSERT INTO ranchi_students (...) SELECT ... WHERE city = 'Ranchi';
Complete MySQL Course  |  Part 1  |  Inserting, Updating & Deleting Data
M3Practice 8 of 10  •  Medium

Example 8: Stock update with ON DUPLICATE KEY

● Medium💼 Real project: Warehouse stock sync
A godown sends today's arrivals. New items are inserted; items already in stock get their quantity added. Notice: an updated row counts as 2 "rows affected".
ex08.sql
REAL RUN
✍ Try it yourself Run the second INSERT again. What are the totals now?
Rice 200, Dal 40, Sugar 50 - each run adds again.
Complete MySQL Course  |  Part 1  |  Inserting, Updating & Deleting Data
M3Practice 9 of 10  •  Hard

Example 9: Daily mandi price upsert

● Hard💼 Real project: Agriculture market price portal
Each day a mandi sends prices. The key is (mandi, crop, price_date). Running the same file twice must not create duplicates - it updates the price instead. INSERT IGNORE shows the alternative: skip duplicates silently.
ex09.sql
REAL RUN
✍ Try it yourself Add Dhanbad mandi prices for the same date. Do they clash with Ranchi rows?
No: the key includes the mandi name, so (Dhanbad, Paddy, date) is a new key.
Complete MySQL Course  |  Part 1  |  Inserting, Updating & Deleting Data
M3Practice 10 of 10  •  Hard

Example 10: The "forgot WHERE" disaster and recovery

● Hard💼 Real project: Production safety for clerks and admins
On purpose: a clerk sets every student's city to Ranchi. We recover from a backup table made before the change. Lesson: back up, preview, then change. (Transactions in M16 give an even better undo.)
ex10.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Turn on SET sql_safe_updates = 1; first and run step 2 again. What happens?
Error 1175: safe update mode blocks UPDATE without a key column in WHERE.
Complete MySQL Course  |  Part 1  |  Inserting, Updating & Deleting Data
M3Check your understanding

Quick Quiz

Click an answer. Wrong answers shake; the right one turns green and explains why.

Q1. What does UPDATE students SET city = 'Ranchi'; change?
✔ Without WHERE, every row matches.
Q2. How do you find rows where email is missing?
✔ NULL is never "equal" to anything; use IS NULL.
Q3. Which statement inserts a new row or updates it if the key exists?
✔ That is called an upsert.
🎯
Your score: 0 / 3 (first try counts)
Answer all questions. Discuss any wrong answer with your partner before moving on.
Complete MySQL Course  |  Part 1  |  Inserting, Updating & Deleting Data
M3Module summary

Recap: Inserting, Updating & Deleting Data

What you learned in M3

  • ✔INSERT INTO t (cols) VALUES (...), (...) - always list the columns.
  • ✔Missing columns get DEFAULT, AUTO_INCREMENT or NULL. Test NULL with IS NULL.
  • ✔UPDATE ... SET ... WHERE - preview with SELECT first.
  • ✔DELETE FROM ... WHERE - children before parents.
  • ✔Upsert with ON DUPLICATE KEY UPDATE and the AS new row alias.
  • ✔Safety: backups, safe updates mode, never forget WHERE.
🏆

Module 3 complete!

You practised 10 real examples on a real MySQL server.

👉 Coming next

M4 Retrieving Data with SELECT: filter, sort and page through data like a search screen.
Complete MySQL Course  |  Part 1  |  Inserting, Updating & Deleting Data
M4

Retrieving Data with SELECT

SELECT is the question you ask the database. Learn to pick columns, filter rows, search text, sort results and show them page by page - exactly what every search screen does.

  • SELECT columns, * and aliases
  • Calculated columns and DISTINCT
  • WHERE with comparisons
  • AND, OR, NOT and brackets
  • IN, BETWEEN, LIKE, IS NULL
  • ORDER BY one or many columns
  • LIMIT and OFFSET for pages
  • The order MySQL runs a SELECT
YOU WILL BUILD:
Student search screenProduct filter pageExam result board
🔍
about 4 hours
10 practice examples: 5 Easy • 3 Medium • 2 Hard
Complete MySQL Course  |  BrainBit Infotech, Ranchi
M4Where is this used in real work?

Every filter, search box and "sort by" is a SELECT

bazaar.jharkhand.shop/search?max=500&sort=price
City: RanchiPrice: under Rs 500Sort: Price low to highPage 1 of 3
ProductPrice
LED Bulb 9W99.00
Mustard Oil 1L185.00
NCERT Maths Class 10190.00
SELECT name, price FROM products
WHERE price < 500
ORDER BY price LIMIT 3;
🔎

Search screens

Each filter on a shopping site or school ERP adds a condition to the WHERE part of one SELECT.
📊

Reports and lists

Fee defaulters, low-stock items, toppers list - each is a SELECT with WHERE and ORDER BY.
🤖

Data analysis and AI

Data analysts spend most of their day writing SELECT queries to pull data for Excel, Power BI or Python.
Complete MySQL Course  |  Part 1  |  Retrieving Data with SELECT
M4Concept

SELECT columns, * and aliases

  • SELECT * = all columns. Handy to explore, but in real apps list only the columns you need (faster, safer).
  • SELECT name, city = only these columns, in this order.
  • AS gives a column a new heading. Use backticks for headings with spaces: AS `Student Name`.
  • table.column names the table too - needed when you join tables (M8).
select.sqlschool_setup.sql
REAL RUN
Complete MySQL Course  |  Part 1  |  Retrieving Data with SELECT
M4Concept

Calculated columns and DISTINCT

  • Do maths in the SELECT list: price * qty, marks / 5, fee * 0.18. The table is not changed - only the result.
  • DISTINCT removes duplicate rows from the result: "which cities do our students come from?"
TipGive every calculated column a name with AS, otherwise the heading is the whole formula.
calc.sqlbazaar_setup.sql
REAL RUN
Complete MySQL Course  |  Part 1  |  Retrieving Data with SELECT
M4Concept

WHERE: keep only the rows you want

OperatorMeaningExample
=equalcity = 'Ranchi'
<> or !=not equalstatus <> 'Cancelled'
> < >= <=greater / lessmarks >= 60
BETWEEN a AND bin a range (both ends included)price BETWEEN 100 AND 500
IN (...)any value in a listcity IN ('Ranchi','Gaya')
LIKEtext patternname LIKE 'S%'
IS NULLvalue missingemail IS NULL
AND / OR / NOTcombine conditionsa AND (b OR c)
WHERE city = 'Ranchi'
namecitymarks
Priya KumariRanchi91
Aman RajPatna78
Sneha OraonRanchi85
Rohit MahtoDhanbad64
Text comparisonMySQL's default collation is case-insensitive: 'ranchi' = 'RANCHI' is true. Dates compare like dates: dob < '2010-01-01'.
LIKE wildcards% = any number of characters, _ = exactly one character. '_a%' = second letter is a.
Complete MySQL Course  |  Part 1  |  Retrieving Data with SELECT
M4Animated explainer

AND before OR: why brackets matter

❌ Without brackets
namecitymarks
Priya KumariRanchi91
Aman RajPatna78
Sneha OraonRanchi85
Rohit MahtoDhanbad64
Rahul TirkeyRanchi72
Pooja SinghJamshedpur95
✅ With brackets
namecitymarks
Priya KumariRanchi91
Aman RajPatna78
Sneha OraonRanchi85
Rohit MahtoDhanbad64
Rahul TirkeyRanchi72
Pooja SinghJamshedpur95
Complete MySQL Course  |  Part 1  |  Retrieving Data with SELECT
M4Concept

IN, BETWEEN, LIKE and IS NULL

  • IN is a short way to write many ORs.
  • BETWEEN includes both ends. Works for numbers, dates and text.
  • LIKE 'S%' starts with S, '%Kumari' ends with Kumari, '%an%' contains "an".
  • NOT flips any of them: NOT IN, NOT LIKE, IS NOT NULL.
filters.sqlschool_setup.sql
REAL RUN
Complete MySQL Course  |  Part 1  |  Retrieving Data with SELECT
M4Concept

ORDER BY, LIMIT and OFFSET

  • ORDER BY marks DESC = highest first. ASC (lowest first) is the default.
  • Several columns: ORDER BY section, marks DESC - sort by section, then by marks inside each section.
  • LIMIT 3 = first 3 rows. LIMIT 3 OFFSET 3 = rows 4 to 6 (page 2).
  • Without ORDER BY, row order is not guaranteed. Always sort when order matters.
📜 SQL standard vs MySQL
SQL:2023 standardORDER BY marks DESC
OFFSET 3 ROWS FETCH FIRST 3 ROWS ONLY
MySQL 9.7ORDER BY marks DESC
LIMIT 3 OFFSET 3
(also LIMIT 3, 3)
sort.sqlschool_setup.sql
REAL RUN
Complete MySQL Course  |  Part 1  |  Retrieving Data with SELECT
M4Animated explainer

The order MySQL really runs a SELECT

FROM
pick the table
➤
WHERE
filter rows
➤
SELECT
pick / calculate columns
➤
ORDER BY
sort
➤
LIMIT
cut to N rows
after FROM: 12 rows
namemarks
Priya91
Aman78
Sneha85
Rohit64
......
after WHERE: 6 rows
namemarks
Priya91
Sneha85
Anjali88
Pooja95
Neha81
Sahil90
after ORDER BY + LIMIT 3
namemarks
Pooja95
Priya91
Sahil90
Complete MySQL Course  |  Part 1  |  Retrieving Data with SELECT
M4Practice 1 of 10  •  Easy

Example 1: All students from Ranchi

● Easy💼 Real project: City-wise student list for a bus route
The simplest filter: one column equals one value. Text values go in single quotes.
ex01.sqlschool_setup.sql
REAL RUN
✍ Try it yourself List all students from Patna or Gaya (Bihar).
WHERE city IN ('Patna', 'Gaya')
Complete MySQL Course  |  Part 1  |  Retrieving Data with SELECT
M4Practice 2 of 10  •  Easy

Example 2: Products under Rs 500

● Easy💼 Real project: Budget filter on a shopping site
Numbers compare without quotes. ORDER BY price shows the cheapest first, like the "Price: low to high" button.
ex02.sqlbazaar_setup.sql
REAL RUN
✍ Try it yourself Show products between Rs 1,000 and Rs 5,000, costliest first.
WHERE price BETWEEN 1000 AND 5000 ORDER BY price DESC
Complete MySQL Course  |  Part 1  |  Retrieving Data with SELECT
M4Practice 3 of 10  •  Easy

Example 3: Names starting with "S"

● Easy💼 Real project: Search-as-you-type box
When a user types "S" in a search box, the app runs LIKE 'S%'. Each new letter makes the pattern longer.
ex03.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Find students whose name ends with "a" in the first name, e.g. "Priya", "Sneha". Hint: think about the space.
WHERE name LIKE '%a %' - an "a" followed by a space.
Complete MySQL Course  |  Part 1  |  Retrieving Data with SELECT
M4Practice 4 of 10  •  Easy

Example 4: Toppers sorted by marks

● Easy💼 Real project: Merit list on the notice board
Sort descending to put the highest marks first, and break ties by name.
ex04.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Show the 3 students with the lowest marks (they need extra classes).
ORDER BY marks ASC LIMIT 3
Complete MySQL Course  |  Part 1  |  Retrieving Data with SELECT
M4Practice 5 of 10  •  Easy

Example 5: Unique cities of customers

● Easy💼 Real project: Planning delivery areas
DISTINCT lists each city once. A delivery company uses this to decide where to open pickup points.
ex05.sqlbazaar_setup.sql
REAL RUN
✍ Try it yourself List the distinct brands in the products table.
SELECT DISTINCT brand FROM products;
Complete MySQL Course  |  Part 1  |  Retrieving Data with SELECT
M4Practice 6 of 10  •  Medium

Example 6: Bill lines with GST as calculated columns

● Medium💼 Real project: Invoice printing
Each order line shows quantity × price, 5% GST and the line total. ROUND(x, 2) keeps paise. The table itself is not changed.
ex06.sqlbazaar_setup.sql
REAL RUN
✍ Try it yourself Change the GST to 12% and show only lines where amount is over Rs 1,000.
Use 0.12 / 1.12, and add AND qty * price > 1000.
Complete MySQL Course  |  Part 1  |  Retrieving Data with SELECT
M4Practice 7 of 10  •  Medium

Example 7: Filter with AND / OR and brackets

● Medium💼 Real project: Scholarship eligibility check
Scholarship rule: from Ranchi or Khunti, and marks 80 or more, and a mobile number on record. Brackets make the OR happen first.
ex07.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Remove the brackets and run again. Explain the different result.
Without brackets AND binds first, so every Ranchi student (any marks) appears.
Complete MySQL Course  |  Part 1  |  Retrieving Data with SELECT
M4Practice 8 of 10  •  Medium

Example 8: Page 2 of a product list

● Medium💼 Real project: Pagination on a website
With 4 products per page: page 1 = LIMIT 4 OFFSET 0, page 2 = OFFSET 4, page n = OFFSET (n-1)*4. A stable ORDER BY is essential.
ex08.sqlbazaar_setup.sql
REAL RUN
✍ Try it yourself Show page 3. How many rows does it have?
LIMIT 4 OFFSET 8 - the last 4 products.
Complete MySQL Course  |  Part 1  |  Retrieving Data with SELECT
M4Practice 9 of 10  •  Hard

Example 9: Admission search screen with many filters

● Hard💼 Real project: School ERP student search
A search form with optional filters becomes one query: girls in section 10-A or 10-B, born in 2010, with an email, name containing "a". Real apps build this WHERE from the filled-in boxes.
ex09.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Add a filter for admission in April 2024 only.
AND admission_date BETWEEN '2024-04-01' AND '2024-04-30'
Complete MySQL Course  |  Part 1  |  Retrieving Data with SELECT
M4Practice 10 of 10  •  Hard

Example 10: Exam result board: status and rank order

● Hard💼 Real project: Result display on a school website
A result board needs pass/fail and division. CASE (full details in M6) turns marks into words. Sorted by division, then marks.
ex10.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Add a "Distinction" level for 75 and above (put it first in the CASE).
WHEN marks >= 75 THEN 'Distinction' as the first WHEN.
Complete MySQL Course  |  Part 1  |  Retrieving Data with SELECT
M4Check your understanding

Quick Quiz

Click an answer. Wrong answers shake; the right one turns green and explains why.

Q1. Which finds names that START with "Ra"?
✔ % after the text = anything can follow.
Q2. Rows 11-20 of a sorted list?
✔ Skip 10 rows, then take 10.
Q3. Which part does MySQL run FIRST?
✔ FROM, then WHERE, SELECT, ORDER BY, LIMIT.
🎯
Your score: 0 / 3 (first try counts)
Answer all questions. Discuss any wrong answer with your partner before moving on.
Complete MySQL Course  |  Part 1  |  Retrieving Data with SELECT
M4Module summary

Recap: Retrieving Data with SELECT

What you learned in M4

  • ✔SELECT cols FROM table - list the columns you need, rename with AS.
  • ✔Calculate in SELECT (price * 1.18); DISTINCT removes duplicates.
  • ✔WHERE filters: = <> > < BETWEEN IN LIKE IS NULL.
  • ✔Mixing AND and OR? Always add brackets.
  • ✔ORDER BY ... DESC, then LIMIT / OFFSET for pages.
  • ✔Run order: FROM → WHERE → SELECT → ORDER BY → LIMIT.
🏆

Module 4 complete!

You practised 10 real examples on a real MySQL server.

👉 Coming next

M5 Keys & Constraints: make MySQL itself refuse bad data with PRIMARY KEY, UNIQUE, CHECK and FOREIGN KEY.
Complete MySQL Course  |  Part 1  |  Retrieving Data with SELECT
1 / 1

✎ SQL Lab