Reading SQL is useful. Running SQL is how you actually learn it. Every query in this tutorial comes with its real output, and you will understand far more if you type the queries yourself and compare.
In this chapter we will install MySQL 8.4, connect to it from the command line, run our first commands and load the sample database company_db that every later chapter uses. We will also go through the error messages beginners usually hit during setup and how to fix them.
If you cannot install anything right now (for example on a college lab machine), skip to No Installation? Use an Online Playground at the end of the installation section.
Client and Server: Two Different Programs
Before installing, understand one idea that confuses many beginners: MySQL is really two programs.
Part | Program name | What it does |
|---|---|---|
MySQL Server |
| Stores the databases on disk, runs queries, enforces rules. Runs in the background all the time, usually listening on port 3306. |
MySQL Client |
| Connects to the server, sends your SQL and shows the results. |
┌────────────────────┐ SQL over a connection ┌─────────────────────┐
│ Client │ ──────────────────────────────────→ │ Server (mysqld) │
│ mysql / Workbench │ │ port 3306 │
│ your app │ ←────────────────────────────────── │ data files on disk │
└────────────────────┘ result rows └─────────────────────┘Why does this matter? Because many setup errors are really "the client cannot reach the server" — for example, the server is not running, or you are using the wrong port or password. Keeping the two programs separate in your head makes those errors easy to understand.
Which Version Should You Install?
Install MySQL Community Server 8.4 LTS. It is free, and "LTS" (Long-Term Support) means it gets bug and security fixes for years without breaking changes. Every output in this tutorial was produced with MySQL 8.4.
If your college or company already has MySQL 8.0, that is fine too — everything we do works the same way there. A newer LTS line, MySQL 9.7, was released in April 2026; it also works for nearly everything here, but installing 8.4 keeps your output identical to ours. Avoid the very old 5.x versions: they lack features we use later, such as window functions and common table expressions.
Installing MySQL
Pick the section for your operating system. You only need one.
Option 1: Windows
Go to the official download page
dev.mysql.com/downloads/mysql/, choose version 8.4 LTS and operating system Microsoft Windows, and download the Windows MSI Installer (64-bit). You can skip the Oracle account sign-up with the "No thanks, just start my download" link.Run the MSI and choose the Typical setup. It installs the server into
C:\Program Files\MySQL\MySQL Server 8.4\.At the end, the installer launches MySQL Configurator. (The older all-in-one "MySQL Installer" only supports MySQL 8.0, so for 8.4 the configuration step lives in this separate tool.) In the Configurator:
Config type: Development Computer, port 3306.
Set a root password and write it down. You will need it every time you connect.
Keep "Configure MySQL Server as a Windows Service" ticked, so the server starts automatically when Windows starts.
Add the MySQL
binfolder to yourPATH, so themysqlcommand works in any terminal: search "Edit the system environment variables" → Environment Variables →Path→ New →C:\Program Files\MySQL\MySQL Server 8.4\bin. Open a new terminal afterwards.
If the server refuses to start with a missing DLL error, install the latest Microsoft Visual C++ Redistributable (x64) — MySQL 8.4 on Windows needs it.
Option 2: Ubuntu Linux (and WSL)
sudo apt update
sudo apt install mysql-server
mysql --version
sudo systemctl status mysql # should say "active (running)"Ubuntu installs whichever MySQL version its release ships with (8.0 on Ubuntu 24.04, newer releases ship 8.4), so check the version that mysql --version prints. Both are fine for this tutorial. (On Debian, the default repositories ship MariaDB instead of MySQL, so add Oracle's official MySQL APT Repository from the MySQL download page first, or use the Docker option below.)
On Ubuntu, the MySQL root account is set up to log in using your Linux sudo rights instead of a password. So the first login is:
sudo mysqlWorking as root all the time is a bad habit, so create your own practice user straight away (choose your own password):
CREATE USER 'learner'@'localhost' IDENTIFIED BY 'Choose-A-Strong-Pass1';
GRANT ALL PRIVILEGES ON *.* TO 'learner'@'localhost';
EXIT;From now on you can connect with mysql -u learner -p. Giving a user all privileges is fine on your own laptop for learning; on a real server you would grant only what is needed (that is what GRANT/REVOKE, the DCL commands, are for).
Option 3: macOS
Either download the DMG installer for 8.4 LTS from the same official download page (it adds a MySQL pane to System Settings where you can start and stop the server), or use Homebrew:
brew install mysql@8.4
brew services start mysql@8.4
# mysql@8.4 is "keg-only", so add its bin folder to your PATH:
echo 'export PATH="$(brew --prefix mysql@8.4)/bin:$PATH"' >> ~/.zshrc
source ~/.zshrc
mysql -u root # a fresh Homebrew install has no root passwordNote that plain brew install mysql installs the newest MySQL 9.x release, not 8.4. It will work for nearly everything here, but using mysql@8.4 keeps your output identical to ours.
Option 4: Docker (Any Operating System)
If you already use Docker, this is the quickest and cleanest option — nothing is installed on your machine except a container:
docker run --name mysql84 -e MYSQL_ROOT_PASSWORD=Choose-A-Strong-Pass1 \
-p 3306:3306 -d mysql:8.4
# open the mysql client inside the container
docker exec -it mysql84 mysql -u root -pUse docker stop mysql84 and docker start mysql84 to stop and start it later. Your data stays inside the container until you remove it.
No Installation? Use an Online Playground
Several free websites let you create tables and run MySQL 8 queries in the browser (search for "MySQL online fiddle"). Paste the company_db script from later in this chapter into the schema box and you can follow along. The limitation is that you cannot practise command-line tools, users or server settings there, so install MySQL locally as soon as you can.
Connecting With the mysql Command-Line Client
Open a terminal (Command Prompt / PowerShell on Windows, Terminal on Linux/macOS) and run:
mysql -u root -p-u root→ log in as userroot(use-u learnerif you created that user)-p→ ask for the password. Type it and press Enter; nothing is shown while you type, which is normal.
When the login works, you see a welcome banner with the server version and the prompt:
mysql>That prompt means "the client is connected and waiting for SQL". Two optional flags you will use later:
mysql -u root -p company_db # connect and select a database straight away
mysql -h 127.0.0.1 -P 3306 -u root -p # host and port (note: -P capital = port, -p small = password)Tip: Avoid typing the password directly after
-p(like-pSecret). It works, but the password ends up in your shell history and MySQL prints a warning about it. Let the client ask for it.
Your First Commands
Which Version Am I Running?
SELECT VERSION();+-------------------------+
| VERSION() |
+-------------------------+
| 8.4.11-0ubuntu0.26.04.1 |
+-------------------------+Your exact number will differ (for example 8.4.6). What matters is that it starts with 8.4 or 8.0.
Notice that SELECT does not always need a table. You can use it as a calculator too:
SELECT 2 + 3 AS answer, UPPER('mysql') AS shout;+--------+-------+
| answer | shout |
+--------+-------+
| 5 | MYSQL |
+--------+-------+Which Databases Exist?
SHOW DATABASES;On a fresh installation you will see four built-in databases. Never modify these — MySQL uses them to run itself:
Database | Purpose |
|---|---|
| Users, privileges and other server settings |
| Read-only "data about data": which tables and columns exist |
| Low-level performance statistics |
| Friendly views on top of |
The Statement Is Not Finished Until the Semicolon
If you press Enter without a semicolon, the client does not run anything. It shows a continuation prompt and waits for more:
mysql> SELECT COUNT(*)
-> FROM departments
-> ;The -> prompt simply means "continue typing". Type ; and press Enter to run. If you opened a quote and forgot to close it, the prompt changes to '>. Here \c alone does not help, because inside a quote it is treated as part of the text. Type the closing quote first, and then \c to cancel the whole statement.
Prompt | Meaning |
|---|---|
| Ready for a new statement |
| Waiting for the rest of a statement (usually a missing |
| Inside an unclosed single or double quote |
| Inside an unclosed backtick |
| Inside an unclosed |
Other handy client commands (these are client commands, so they do not need a semicolon):
\c– cancel the statement you are typing (close any open quote first)status– show connection details: user, server version, current databaseexitorquit– leave the client
Loading the Sample Database (company_db)
Every chapter from here on uses company_db. You only need to load it once.
Step 1: Save the Script
Copy the script below into a plain text file named company_db.sql — for example in C:/sql on Windows or ~/sql on Linux/macOS. (Use a code editor like VS Code or Notepad, not Word.)
company_db.sql — click to expand the full script
-- Sample database for the CS Learning Portal SQL tutorial (MySQL 8)
DROP DATABASE IF EXISTS company_db;
CREATE DATABASE company_db;
USE company_db;
CREATE TABLE departments (
dept_id INT PRIMARY KEY,
dept_name VARCHAR(50) NOT NULL UNIQUE,
location VARCHAR(50) NOT NULL
);
CREATE TABLE employees (
emp_id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
email VARCHAR(100) UNIQUE,
dept_id INT,
manager_id INT,
salary DECIMAL(10,2) NOT NULL,
hire_date DATE NOT NULL,
city VARCHAR(50),
FOREIGN KEY (dept_id) REFERENCES departments(dept_id),
FOREIGN KEY (manager_id) REFERENCES employees(emp_id)
);
CREATE TABLE customers (
customer_id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
city VARCHAR(50),
signup_date DATE NOT NULL
);
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT,
order_date DATE NOT NULL,
amount DECIMAL(10,2) NOT NULL,
status VARCHAR(20) NOT NULL,
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);
INSERT INTO departments VALUES
(10, 'Engineering', 'Bengaluru'),
(20, 'Sales', 'Mumbai'),
(30, 'HR', 'Delhi'),
(40, 'Marketing', 'Pune'),
(50, 'Research', 'Hyderabad'); -- no employees yet
INSERT INTO employees VALUES
(1, 'Aarav Sharma', 'aarav@company.com', 10, NULL, 150000.00, '2018-04-12', 'Bengaluru'),
(2, 'Priya Iyer', 'priya@company.com', 10, 1, 95000.00, '2019-07-01', 'Chennai'),
(3, 'Rohan Mehta', 'rohan@company.com', 10, 1, 95000.00, '2020-01-15', 'Bengaluru'),
(4, 'Sneha Kapoor', 'sneha@company.com', 20, 1, 110000.00, '2017-11-20', 'Mumbai'),
(5, 'Vikram Singh', 'vikram@company.com', 20, 4, 62000.00, '2021-03-08', 'Mumbai'),
(6, 'Ananya Das', 'ananya@company.com', 20, 4, 58000.00, '2022-06-30', 'Kolkata'),
(7, 'Karan Patel', 'karan@company.com', 30, 1, 70000.00, '2019-09-23', 'Delhi'),
(8, 'Meera Nair', NULL, 30, 7, 48000.00, '2023-02-14', 'Kochi'),
(9, 'Arjun Reddy', 'arjun@company.com', 40, 1, 82000.00, '2020-10-05', 'Hyderabad'),
(10, 'Ishita Gupta', 'ishita@company.com', NULL, 1, 55000.00, '2024-01-10', NULL);
INSERT INTO customers VALUES
(101, 'Rahul Verma', 'Delhi', '2023-01-05'),
(102, 'Kavya Menon', 'Bengaluru', '2023-02-17'),
(103, 'Aditya Joshi', 'Pune', '2023-03-22'),
(104, 'Neha Agarwal', 'Mumbai', '2023-05-09'),
(105, 'Siddharth Rao', NULL, '2023-08-30'); -- has no orders
INSERT INTO orders VALUES
(1001, 101, '2024-01-15', 2500.00, 'Delivered'),
(1002, 102, '2024-01-20', 4800.00, 'Delivered'),
(1003, 101, '2024-02-02', 1200.00, 'Cancelled'),
(1004, 103, '2024-02-14', 7300.00, 'Delivered'),
(1005, 104, '2024-03-01', 950.00, 'Shipped'),
(1006, 102, '2024-03-11', 3100.00, 'Delivered'),
(1007, 101, '2024-03-28', 5600.00, 'Pending'),
(1008, NULL,'2024-04-02', 800.00, 'Pending'); -- guest order, no customerYou do not need to understand every line yet. The CREATE part is explained in CREATE DATABASE & CREATE TABLE and the INSERT part in INSERT INTO.
Warning: The first line,
DROP DATABASE IF EXISTS company_db;, deletes any existingcompany_db. That is deliberate: if you ever mess up the sample data while experimenting, just run the script again to get a fresh copy. Just don't keep your own work insidecompany_db.
Step 2: Run the Script
There are two common ways. Use either one.
Way A – from inside the mysql client, using the SOURCE command:
mysql> SOURCE C:/sql/company_db.sqlOn Linux/macOS use your own path, for example SOURCE /home/you/sql/company_db.sql. On Windows, write the path with forward slashes. Do not put a comment after a SOURCE command on the same line — SOURCE is a client command and treats the rest of the line as the file name.
You will see a series of Query OK lines scroll by, one per statement.
Way B – from your normal terminal, by redirecting the file into the client:
mysql -u root -p < company_db.sqlRun this from the folder that contains the file. If everything works, it prints nothing except the password prompt — in batch mode, silence means success. (In PowerShell the < redirection does not work; use Command Prompt or Way A instead.)
Step 3: Check That It Worked
USE company_db;
SELECT DATABASE();+------------+
| DATABASE() |
+------------+
| company_db |
+------------+USE selects the current database. After it, a bare table name like employees means company_db.employees. SELECT DATABASE() tells you which database is currently selected.
SHOW TABLES;+----------------------+
| Tables_in_company_db |
+----------------------+
| customers |
| departments |
| employees |
| orders |
+----------------------+DESCRIBE departments;+-----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| dept_id | int | NO | PRI | NULL | |
| dept_name | varchar(50) | NO | UNI | NULL | |
| location | varchar(50) | NO | | NULL | |
+-----------+-------------+------+-----+---------+-------+DESCRIBE (or its short form DESC) shows a table's columns, their types, whether they allow NULL, and keys: PRI = primary key, UNI = unique. We will read this output in detail in the next two chapters.
Finally, a quick row count:
SELECT COUNT(*) FROM departments;+----------+
| COUNT(*) |
+----------+
| 5 |
+----------+If you see 5 here (and 10 for employees, 5 for customers, 8 for orders), your setup is complete.
Common Errors and How to Fix Them
"No database selected"
If you query a table before choosing a database:
SELECT * FROM employees;ERROR 1046 (3D000): No database selectedMySQL does not know which database's employees you mean. Fix it with USE company_db;, or write the full name company_db.employees.
Syntax Errors
SELEC * FROM departments;ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELEC * FROM departments' at line 1Error 1064 always means "I could not parse this". The most useful part is the text after near: the problem is at, or just before, that text. Here it points at the very start, where SELECT is misspelled.
Connection and Login Errors
Error message | What it means | Fix |
|---|---|---|
| The terminal cannot find the client program | Add MySQL's |
| Wrong user name or password | Re-check the password you set during installation |
| Ubuntu's root account uses | Use |
| Nothing is listening at that host/port: server stopped, or wrong port | Start the server (Windows: open Services and start the MySQL service, named something like MySQL84; Linux: |
| Same idea on Linux/macOS when connecting locally via a socket file | Start the server |
See how the client/server idea helps? Errors 2002 and 2003 mean the client never reached the server. Errors 1045 and 1698 mean it reached the server, but the server rejected the login.
Graphical Tools (Optional)
The command-line client is all you need for this tutorial, and it is what you will use on servers and in many interviews. Still, a graphical tool is nice for browsing tables:
MySQL Workbench – Oracle's official free GUI. Write a query in the editor and press Ctrl + Enter to run the statement under the cursor (or the lightning-bolt icon to run everything).
DBeaver – a free tool that works with MySQL, PostgreSQL, Oracle, SQLite and more.
VS Code extensions – several extensions let you connect to MySQL and run queries from your editor.
All of them are just clients. They connect to the same server with the same user name, password, host and port you used on the command line.
Interview Questions
What is the default port of MySQL?
3306.
What is the difference between mysql and mysqld?
mysqld is the server process that stores data and executes queries. mysql is a command-line client that connects to the server and sends it SQL.
How do you run a .sql script file in MySQL?
Inside the client with SOURCE path/to/file.sql, or from the shell with mysql -u user -p dbname < file.sql.
What does the USE statement do?
It sets the default (current) database for the session, so unqualified table names refer to tables in that database. SELECT DATABASE() shows the current one.
What are information_schema and the mysql database?
information_schema is a read-only set of views describing all databases, tables, columns and privileges (metadata). The mysql database holds the server's own data such as user accounts and grants.
The Main Idea
MySQL = server (mysqld, port 3306) + clients (mysql, Workbench, apps)
Install → 8.4 LTS: Windows MSI + Configurator, apt, brew mysql@8.4, or Docker
Connect → mysql -u root -p (-P = port, -p = password)
First steps → SELECT VERSION(); SHOW DATABASES; USE company_db;
SHOW TABLES; DESCRIBE departments;
Load script → SOURCE file.sql or mysql -u root -p < file.sql
Prompts → mysql> ready -> needs ; '> open quote \c cancel (after closing quotes)
Errors → 1046 no DB selected, 1064 syntax,
1045/1698 login refused, 2002/2003 server not reachableYou now have a working MySQL server with company_db loaded. Next, in SQL Data Types, we look at what kinds of values a column can hold — and why choosing the right type prevents real bugs.