Q&A 4 How do you query data from a MySQL database?
4.1 Explanation
After setting up your database and inserting records, querying is how you extract useful information. The most common query is the SELECT statement, which lets you view specific data or filter based on conditions.
This Q&A demonstrates how to:
- View all records
- Filter data using WHERE
- Sort data using ORDER BY
4.2 SQL/MySQL Code
MariaDB [cdi_learning]> USE cdi_learning;
Database changed
MariaDB [cdi_learning]> SELECT * FROM students;
+----+---------------+-------------------+---------------+
| id | name | email | enrolled_date |
+----+---------------+-------------------+---------------+
| 1 | Alice Example | alice@example.com | 2025-08-10 |
| 2 | Bob Tester | bob@test.com | 2025-08-11 |
+----+---------------+-------------------+---------------+
2 rows in set (0.002 sec)
-- Step 3: View students enrolled after a given date (August 5, 2025)
SELECT * FROM students WHERE enrolled_date > '2025-08-05';MariaDB [cdi_learning]> SELECT * FROM students WHERE enrolled_date > '2025-08-05';
+----+---------------+-------------------+---------------+
| id | name | email | enrolled_date |
+----+---------------+-------------------+---------------+
| 1 | Alice Example | alice@example.com | 2025-08-10 |
| 2 | Bob Tester | bob@test.com | 2025-08-11 |
+----+---------------+-------------------+---------------+
2 rows in set (0.004 sec)
-- Step 4: Sort students by enrollment date (most recent first)
SELECT * FROM students ORDER BY enrolled_date DESC;MariaDB [cdi_learning]> SELECT * FROM students ORDER BY enrolled_date DESC;
+----+---------------+-------------------+---------------+
| id | name | email | enrolled_date |
+----+---------------+-------------------+---------------+
| 2 | Bob Tester | bob@test.com | 2025-08-11 |
| 1 | Alice Example | alice@example.com | 2025-08-10 |
+----+---------------+-------------------+---------------+
2 rows in set (0.004 sec)
4.3 Python Code (Querying MySQL via mysql-connector-python)
import mysql.connector
# Connect to MySQL
conn = mysql.connector.connect(
host="localhost",
user="root",
password="", # XAMPP default
database="cdi_learning"
)
cursor = conn.cursor()
# Query 1: Get all students
cursor.execute("SELECT * FROM students")
print("All Students:")
for row in cursor.fetchall():
print(row)All Students:
(1, 'Alice Example', 'alice@example.com', datetime.date(2025, 8, 10))
(2, 'Bob Tester', 'bob@test.com', datetime.date(2025, 8, 11))
# Query 2: Filter by enrollment date
cursor.execute("SELECT * FROM students WHERE enrolled_date > %s", ("2025-08-05",))
print("\nFiltered Students:")
for row in cursor.fetchall():
print(row)
conn.close()Filtered Students:
(1, 'Alice Example', 'alice@example.com', datetime.date(2025, 8, 10))
(2, 'Bob Tester', 'bob@test.com', datetime.date(2025, 8, 11))