2.2 Lab - Hello World MySQL

Introduction

This lab introduces you to working with MySQL from the command line. You will learn how to connect to a MySQL server, create a database, define a table, insert data, and query it. This foundational "Hello World" exercise will prepare you for more complex SQL tasks.

Objectives

By the end of this lab, you will be able to:

  1. Connect to a MySQL server using the command line.
  2. Create a new database.
  3. Define a simple table within the database.
  4. Insert a record into the table.
  5. Query the table to retrieve data.

Lab Steps


Step 1: Open the Command Line and Log In to MySQL

  1. Open your terminal or command prompt.

  2. Log in to the MySQL server using the following command:

    mysql -u root -p
    
    • Replace root with your MySQL username if different.
    • Enter your MySQL password when prompted.
  3. After a successful login, you will see the MySQL prompt:

    mysql>
    

Step 2: Create a Database

  1. At the MySQL prompt, create a new database named hello_world:

    CREATE DATABASE hello_world;
    
  2. Use the newly created database:

    USE hello_world;
    
    • You should see the message Database changed.

Step 3: Create a Table

  1. Define a table named greetings with the following structure:

    • id (integer, primary key, auto-incremented)
    • message (text, stores a greeting message)

    Execute the following SQL statement:

    CREATE TABLE greetings (
        id INT AUTO_INCREMENT PRIMARY KEY,
        message TEXT NOT NULL
    );
    
  2. Verify the table creation by describing its structure:

    DESCRIBE greetings;
    

Step 4: Insert Data into the Table

  1. Insert a "Hello, World!" message into the greetings table:

    INSERT INTO greetings (message) VALUES ('Hello, World!');
    
  2. Confirm that the data has been added:

    SELECT * FROM greetings;
    
    • You should see output similar to this:

      +----+--------------+
      | id | message      |
      +----+--------------+
      |  1 | Hello, World!|
      +----+--------------+
      

Step 5: Query the Data

  1. Retrieve only the message column from the table:

    SELECT message FROM greetings;
    
  2. Experiment by adding another greeting and querying the data again:

    INSERT INTO greetings (message) VALUES ('Welcome to MySQL!');
    SELECT * FROM greetings;
    

Step 6: Exit MySQL

  1. Exit the MySQL command line:

    EXIT;
    
  2. Close your terminal or command prompt.


Summary

In this lab, you learned how to:

This "Hello World" lab serves as your first step into MySQL, providing hands-on experience with the essential commands needed for database interaction. In the next lab, we will build on these concepts by exploring how to filter and sort data using SQL queries.