Unit 1
Unit 1
managing and organizing data in a structured way. It is widely used for applications ranging from small
personal projects to large enterprise-level systems. Here’s an introduction to MySQL, covering its key
features, architecture, and usage.
1. What is MySQL?
• Definition: MySQL is an open-source RDBMS developed and maintained by Oracle
Corporation. It uses Structured Query Language (SQL) for managing and manipulating
databases.
• Purpose: It helps in storing, retrieving, and managing data efficiently and securely.
2. Key Features
• Open Source: MySQL is freely available under the GNU General Public License (GPL),
allowing users to view, modify, and distribute its source code.
• Cross-Platform: It runs on various operating systems, including Windows, Linux, and macOS.
• Scalability: MySQL can handle large databases with thousands of tables and millions of
records, suitable for both small and large applications.
• Performance: It provides high performance with features such as indexing, query
optimization, and caching.
• Security: MySQL includes robust security features like user authentication, access control, and
data encryption.
• Replication: Supports database replication, which allows data to be copied from one server
(master) to others (slaves) for load balancing and backup purposes.
• ACID Compliance: Ensures reliable transactions through its support for Atomicity,
Consistency, Isolation, and Durability.
3. MySQL Architecture
1. Server Layer:
o MySQL Server: The core component that handles database operations. It manages
data storage, querying, and processing.
2. Storage Engines:
o InnoDB: The default storage engine known for its support for transactions, foreign
keys, and row-level locking.
o MyISAM: An older storage engine known for its fast read operations and simplicity,
but lacking transaction support.
3. Query Processor:
o SQL Parser: Converts SQL queries into a form that can be understood by the MySQL
engine.
o Optimizer: Determines the most efficient way to execute a query based on indexes,
data distribution, and other factors.
o Execution Engine: Executes the query and returns the results to the client.
4. Client Layer:
o Client Applications: Programs or tools that interact with the MySQL server. Examples
include MySQL Workbench, phpMyAdmin, and custom applications using MySQL
connectors.
4. Basic MySQL Concepts
• Database: A collection of related data organized in tables.
• Table: A set of rows (records) and columns (fields) used to store data. Each table has a unique
name within a database.
• Row (Record): An individual entry in a table, representing a single instance of the data.
• Column (Field): A specific attribute or property of the data stored in a table.
• Index: A data structure that improves the speed of data retrieval operations on a table.
• Query: A request for data or operations on data using SQL. Common SQL commands include
SELECT, INSERT, UPDATE, and DELETE.
5. Common SQL Commands
• CREATE DATABASE: Creates a new database.
CREATE DATABASE my_database;
• CREATE TABLE: Defines a new table within a database.
CREATE TABLE employees (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
position VARCHAR(50)
);
• INSERT INTO: Adds new records to a table.
INSERT INTO employees (name, position) VALUES ('John Doe', 'Software Engineer');
• SELECT: Retrieves data from a table.
SELECT * FROM employees;
• UPDATE: Modifies existing records.
UPDATE employees SET position = 'Senior Software Engineer' WHERE id = 1;
• DELETE: Removes records from a table.
DELETE FROM employees WHERE id = 1;
6. MySQL Tools and Interfaces
• MySQL Workbench: A graphical tool for database design, SQL development, and server
administration.
• phpMyAdmin: A web-based interface for managing MySQL databases, commonly used in
web hosting environments.
• Command-Line Client: A text-based interface for interacting with MySQL using SQL
commands.
7. Use Cases
• Web Development: MySQL is frequently used in conjunction with web development
technologies like PHP (LAMP stack) for building dynamic websites and web applications.
• Data Warehousing: Suitable for managing large volumes of data and performing complex
queries.
• Business Applications: Used for CRM systems, ERP solutions, and other enterprise
applications.
8. Getting Started with MySQL
1. Installation: MySQL can be installed on various operating systems. Installation packages are
available from the MySQL website.
2. Configuration: After installation, configure MySQL settings such as user accounts,
permissions, and database parameters.
3. Connecting: Use MySQL client tools or programming language connectors to connect to the
MySQL server and start working with databases.
MySQL is a powerful and versatile RDBMS that provides a robust solution for managing relational
data. Its ease of use, performance, and wide adoption make it a popular choice for many applications.
Installing MySQL involves different procedures depending on the operating system you are using.
Here’s a guide to installing MySQL on Windows and Linux systems using RPM packages.
1. Installing MySQL on Windows
Step 1: Download MySQL Installer
• Go to the MySQL Downloads page.
• Download the MySQL Installer for Windows. You can choose between the web community
installer (smaller size) or the full installer (includes all components).
Step 2: Run the Installer
• Double-click the downloaded .msi file to start the installation.
• You may be prompted to install prerequisites like Microsoft Visual C++ Redistributable; follow
the on-screen instructions.
Step 3: Choose Setup Type
• Select the setup type: Developer Default (recommended), Server Only, Client Only, Full, or
Custom.
• Developer Default installs MySQL Server, MySQL Workbench, MySQL Shell, and other
development tools.
Step 4: Installation
• Click Next to proceed through the steps. The installer will check for any issues and install the
selected components.
• Configure MySQL Server by setting a root password and choosing other configuration options
like port number and server type.
Step 5: Complete Installation
• After installation, you can start MySQL Server and MySQL Workbench from the Start menu or
directly from the MySQL Installer.
• Verify the installation by opening MySQL Workbench and connecting to the local MySQL
server using the root account.
2. Installing MySQL on Linux (RPM-based systems like CentOS, RHEL, Fedora)
Step 1: Download MySQL RPM Packages
• Go to the MySQL Downloads page.
• Download the MySQL Yum Repository package, which is a repository configuration file for
the package manager.
Step 2: Install MySQL Yum Repository
• Open a terminal and navigate to the directory where you downloaded the .rpm file.
• Install the repository package using the following command:
Step 3: Install MySQL Server
• After adding the repository, install the MySQL server package:
• This command will install MySQL Server and related packages.
Step 4: Start MySQL Service
• Start the MySQL service using:
• Enable MySQL to start on boot:
Step 5: Secure MySQL Installation
• MySQL provides a script to secure your installation by setting the root password and removing
insecure default settings:
• Follow the prompts to configure the root password and make other security adjustments.
Step 6: Verify Installation
• Log in to MySQL to check that it is working correctly
• Enter the root password you set during the secure installation process.
Additional Notes
• For Windows:
o The MySQL Installer provides a graphical user interface, making it easier to select and
configure components.
o After installation, you can manage MySQL through MySQL Workbench or command-
line tools.
• For Linux:
o RPM-based systems like CentOS, RHEL, and Fedora use the yum package manager
for installing and updating packages.
o Make sure you have the required privileges (typically root) to perform these
installations.
By following these steps, you should be able to successfully install MySQL on both Windows and Linux
systems.
Managing MySQL involves starting, stopping, and restarting the MySQL server as needed. Here’s how
to perform these actions on both Windows and Linux systems.
1. Starting and Stopping MySQL on Windows
Starting MySQL:
• Using MySQL Installer:
1. Open MySQL Installer from the Start menu.
2. Go to the MySQL Server section and click on Start if it's not already running.
• Using Services:
1. Open Services from the Start menu (search for services.msc).
2. Find MySQL (or MySQL56, MySQL57, etc., depending on your version) in the list.
3. Right-click on MySQL and select Start.
• Using Command Line:
1. Open Command Prompt as an administrator.
2. Run the following command:
Stopping MySQL:
• Using MySQL Installer:
1. Open MySQL Installer.
2. Go to the MySQL Server section and click on Stop.
• Using Services:
1. Open Services (search for services.msc).
2. Find MySQL in the list.
3. Right-click on MySQL and select Stop.
• Using Command Line:
1. Open Command Prompt as an administrator.
2. Run the following command:
2. Starting and Stopping MySQL on Linux (RPM-based systems like CentOS, RHEL, Fedora)
Starting MySQL:
• Using systemd:
1. Open a terminal.
2. Start MySQL with the following command:
Stopping MySQL:
• Using systemd:
1. Open a terminal.
2. Stop MySQL with the following command:
Restarting MySQL:
• Using systemd:
1. Open a terminal.
2. Restart MySQL with the following command:
Checking the Status of MySQL:
• Using systemd:
1. Open a terminal.
2. Check the status of MySQL with the following command:
Additional Commands:
• To reload configuration without restarting:
• To enable MySQL to start on boot:
• To disable MySQL from starting on boot:
3. Troubleshooting Tips
• Check Logs: If MySQL does not start or stops unexpectedly, check the MySQL error log for
details. The log file is typically located in /var/log/mysql/ or /var/log/mysqld.log on Linux and
in the MySQL installation directory on Windows.
• Verify Installation: Ensure MySQL is properly installed and configured. Incorrect settings in
the configuration file (my.cnf on Linux or my.ini on Windows) can prevent the server from
starting.
• Permissions: Make sure you have the necessary administrative or root privileges to start or
stop MySQL.
By following these instructions, you should be able to manage the MySQL server effectively on both
Windows and Linux systems.
MySQL queries are written in Structured Query Language (SQL) and are used to interact with a MySQL
database. Here’s a guide to some of the basic SQL queries that you will frequently use to manage and
retrieve data.
1. Basic SQL Query Structure
SQL queries generally follow this structure:
SELECT column1, column2
FROM table_name
WHERE condition;
2. Common SQL Queries
**1. Selecting Data
• Select All Columns:
SELECT * FROM table_name;
o Retrieves all columns and rows from the specified table.
• Select Specific Columns:
SELECT column1, column2 FROM table_name;
o Retrieves only the specified columns from the table.
**2. Filtering Data
• Using WHERE Clause:
SELECT * FROM table_name WHERE condition;
o Filters records based on the condition. For example:
SELECT * FROM employees WHERE age > 30;
▪ Retrieves employees older than 30.
• Using Multiple Conditions:
SELECT * FROM table_name WHERE condition1 AND condition2;
o Filters records based on multiple conditions. For example:
SELECT * FROM employees WHERE age > 30 AND department = 'Sales';
▪ Retrieves employees older than 30 in the Sales department.
**3. Sorting Data
• Order By:
SELECT * FROM table_name ORDER BY column_name [ASC|DESC];
o Sorts records based on a specified column. For example:
SELECT * FROM employees ORDER BY salary DESC;
▪ Retrieves employees sorted by salary in descending order.
**4. Limiting Results
• Limit Results:
SELECT * FROM table_name LIMIT number;
o Limits the number of rows returned. For example:
SELECT * FROM employees LIMIT 5;
▪ Retrieves the first 5 rows from the employees table.
**5. Inserting Data
• Insert Into Table:
INSERT INTO table_name (column1, column2) VALUES (value1, value2);
o Adds a new record to the table. For example:
INSERT INTO employees (name, position, salary) VALUES ('Jane Doe', 'Developer', 70000);
▪ Adds a new employee with specified details.
**6. Updating Data
• Update Records:
UPDATE table_name SET column1 = value1, column2 = value2 WHERE condition;
o Modifies existing records. For example:
UPDATE employees SET salary = 75000 WHERE name = 'Jane Doe';
▪ Updates the salary of 'Jane Doe' to 75,000.
**7. Deleting Data
• Delete Records:
DELETE FROM table_name WHERE condition;
o Removes records based on a condition. For example:
DELETE FROM employees WHERE name = 'Jane Doe';
▪ Deletes the employee named 'Jane Doe'.
**8. Creating Tables
• Create Table:
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
...
);
o Defines a new table with specified columns. For example:
CREATE TABLE employees (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
position VARCHAR(50),
salary DECIMAL(10, 2)
);
▪ Creates a table for storing employee data.
**9. Altering Tables
• Add Column:
ALTER TABLE table_name ADD column_name datatype;
o Adds a new column to an existing table. For example:
The server creates all the log files in the data directory and sets the file name to the current hostname if
you do not set another pathname. You can enable these log files by starting the server with the
corresponding options (on the command line or in an option file without the preceding ‘–’).
• Error log: Set –log-error=[file_name] to log errors to the given file. The mysqld_safe script
creates the error log and starts the server with its output redirected to the error log.
• General query log: Set –general_log_file=[file_name] to log queries. The global general_log
and general_log_file server variables provide runtime control over the general query log. Set
general_logto 0 (or OFF) to disable the log, or to 1 (or ON) to enable it.
• Slow query log: Set –slow_query_log_file=[file_name] to provide runtime control over the
slow query log. Set slow_query_log to 0 to disable the log, or to 1 to enable it. If a log file is
already open, it is closed and the new file is opened.
• Binary log: Set –log-binto enable binary logging. The server uses the option value as a base
name, adding an increasing sequential numeric suffix to the base name as it creates new log
files. These log files are stored in binary format rather than text format.
• Audit log: The audit log is provided as an Enterprise Edition plugin that, when loaded, you can
use to log events into the file specified by the audit_log_file option. Auditing constantly writes
to the audit log until you remove the plugin, or you turn off the auditing with the
audit_log_policy=NONEoption setting. You can prevent the removal of the plugin by using
audit_log=FORCE_PLUS_PERMANENTas an option when the server is started. For detailed
information about all available audit plugin options, see the MySQL Reference
Manual: http://dev.mysql.com/doc/mysql/en/audit-log-plugin-optionsvariables.html
If the general or slow query logs are enabled, they can output log entries to a file, a table in the mysql
database, or both, by setting the –log-output option. See the MySQL Reference
Binary Logging
The binary log contains “events” that describe database changes such as table creation or changes to
table data. It also contains events for statements that could have potentially made changes (for example,
a DELETE that matched no rows). It also contains information about how long each update statement
took. The binary log has two important purposes: replication and data recovery.
MySQL uses a log-shipping replication solution. With the log-shipping system, you can store all data
changes that occur on the masterin a binary log and then retrieve them with the slave, and execute from
these received log files. You can download log files and execute the contents in real time; that is, as
soon as a log file event is generated, it is sent to the connected slaves for execution. Due to network
propagation delays, it can take from a few seconds to a few minutes (worst case) for the slave to receive
the updates. In ideal situations, the delay is well under one second.
The binary log rotates when one of the following events occurs:
• The MySQL server is restarted.
• The maximum allowed size is reached (max_binlog_size).
• A FLUSH LOGS SQL command is issued.
The binary log is independent of the storage engine. MySQL replication works regardless of the storage
engine that is being used (that is, InnoDB or MyISAM).
Binary Logging Formats
There are two different types of logging to choose from:
Replication limitations Not all statements can be replicated. All statements can be
replicated.
Master/Slave MySQL Slave can be a newer version with a different Slave must be an identical
versions row structure. version and row structure.
MySQL follows the client-server architecture, which divides the system into two main components:
Client and Server.
Client
• The client is the application that interacts with the MySQL database server.
• The client can be a standalone application, a web application, or any program that needs a
database.
• The client sends SQL queries to the MySQL server for processing.
Server
• The server is the MySQL database management system responsible for storing, managing, and
processing data.
• The server receives SQL queries, processes them, and returns the result sets.
• The server manages multiple clients’ data storage, security, and concurrent access.
The client communicates with the server over the network using MySQL protocol. The client-server
architecture allows for the separation of concerns and enables multiple clients to interact with MySQL
concurrently.
In the client-server architecture, the applications use MySQL connectors to connect to the MySQL
database server. The applications can be developed using various programming languages such
as Java, PHP, Python, Perl, and JavaScript (Node.js)
MySQL also comes with some of the MySQL client tool that allows you to interact with the MySQL
database server:
• MySQL Workbench (GUI-based).
• MySQL client (terminal-based).
• MySQL shell.
MySQL database server includes several daemon processes:
• NoSQL manages schema-less data storage, often used for unstructured or semi-structured data.
• SQL Interface defines a standardized interface enabling applications to interact with relational
databases using SQL queries.
• Query Parser is responsible for analyzing SQL queries to understand their structure and syntax,
breaking them down into components for further processing.
• Query Optimizer evaluates various execution plans for a given query and selects the most
efficient one to enhance the performance of database operations.
• Caches & Buffers store frequently accessed data or query results in memory, reducing the need
to repeatedly access the underlying storage and improving overall system performance.
Storage engines
In MySQL, a storage engine is a component that is in charge of storage, retrieval, and management of
data in the database.
MySQL uses a pluggable storage engine architecture that allows you to select different storage engines
such as InnoDB, MyISAM, and others.
The pluggable storage engine architecture provides flexibility to meet specific performance and
scalability requirements while maintaining a consistent SQL interface and overall database
functionality.
File systems
The file system organizes and stores various file types, including data and index files. MySQL uses log
files to maintain transactional consistency and support recovery mechanisms. Typically log files are
binary and redo logs.
Summary
• MySQL follows a client-server architecture where clients send SQL queries to the server for
processing.
• MySQL supports a pluggable storage engine that manages the storage and retrieval of data with
different features and performance characteristics.