![](https://scientifictools.org/courses/images/coverPhotos/14/17-14d028c31b8410c8a384ab4d23c8d33c9a8e9806.png)
In this guide, we will introduce you to the basics of MySQL queries and provide some practical examples.
Understanding Queries
A query is a request to access or manipulate data stored in a database. In MySQL, you primarily use SQL (Structured Query Language) to write these queries.
Basic Query Structure
The basic structure of a query involves the SELECT statement, which retrieves data from the database.
Example: Selecting Data
To retrieve all data from a Users table:
In this example, * means "all columns."
Example: Selecting Specific Columns
To retrieve only the Name and Email columns:
Filtering Data with WHERE
The WHERE clause filters records that meet certain criteria.
Example: Filtering by a Condition
To find users named 'John Doe':
Example: Using Logical Operators
To find users named 'John Doe' or 'Jane Doe':
To find users aged 30 and above:
Sorting Data with ORDER BY
The ORDER BY clause is used to sort the result set.
Example: Sorting in Ascending Order
To sort users by their names in alphabetical order:
Example: Sorting in Descending Order
To sort users by age in descending order:
Aggregating Data
Aggregation functions perform a calculation on a set of values and return a single value.
Example: Counting Records
To count the number of users:
Example: Finding Maximum and Minimum
To find the oldest user's age:
To find the youngest user's age:
Joining Tables
Joins are used to combine rows from two or more tables.
Example: Inner Join
To list users along with their orders from an Orders table:
This query joins Users and Orders based on the UserID.
Using Subqueries
Subqueries are queries nested inside another query.
Example: Subquery
To find users who have placed an order: