MySQL

MySQL

Tables

In MySQL you will use Tables quite a lot so lets quickly go over what they are, how they work and how to create and “use” one.

What is a MySQL Table?

A table in MySQL is a structured way to store data in rows and columns. It is similar to a spreadsheet where:

  • Columns: Define the type of data stored (e.g., name, age, salary).
  • Rows: Each row is a record or entry in the table.

Each table has:

  • A Primary Key: A unique identifier for each row (e.g., an ID).
  • Optional Foreign Keys: Links a table to another table to create relationships (e.g., connecting employees to departments).

How do Tables work?

Creating a Table:
You define a table by specifying the columns and the type of data each column will store (e.g., text, numbers, or dates).

Adding Data:
Once a table is created, you can insert new records into it. Each row corresponds to a new entry in the table.

Retrieving Data:
You can query the table to get specific data, such as all rows or only rows matching certain conditions (e.g., employees earning a specific salary).

Updating Data:
If data in a table changes, you can update it, such as modifying someone’s salary or updating their name.

Deleting Data:
You can remove individual records or even multiple records at once, based on specific conditions.

Relationships Between Tables:
Tables can be connected using relationships. For example, an employees table can be linked to a departments table so that each employee is associated with a specific department. This allows for efficient data management and retrieval.

How to Create a Table?

There are different ways to create a Table in MySQL:

  • MySQL Command-Line Client
  • MySQL Workbench
  • Programming Languages with MySQL Support
  • phpMyAdmin
  • Online MySQL Editors

But we will go over the first three so: MySQL Command-Line Client, MySQL Workbench and Programming Languages with MySQL Support.

MySQL Workbench

This is how to create a Table in MySQL Workbench, in case you don’t have MySQL Workbench yet you can download it here: MySQL Workbench Download

Connecting to the Server:

Open MySQL Workbench and if you already have the connection saved Good otherwise here is how to connect to a Server

Click on the small “+” and then the window shown will open. Select the Connection Method as shown in the Image, and then just enter the information in the red marked fields so that its true for which server you want to connect to.

Creating a Database:

If you don’t already have a Database or not one you want this table on then here’s how to create a Database:

Click the cylinder shape with the little “+” and then enter a name for your new Database, after klick Apply to create it.

Creating a Table:

Click the Document with the “+” and then you will get a bunch of options but firstly enter a Name of how you want to name this Table (usually what it will display: users, posts, etc.) then there’s the Column Name, the Datatypes some additional settings and the default.
The Column Name will for example for a “users Table” you would want an “id”, an “username”, and maybe an “admin status” to see if they are or have admin privileges with a “0 or 1” for example. It could look like this:

These “additional settings” are explained here: Additional Settings / Indexes

Add a Foreign Key:

MySQL Command-Line Client

Connect to MySQL:

Open the command Prompt on Windows or Terminal if on Linux / macOS, then enter following command:

PHP
mysql -u root -p

Change root to a different username if you have it so or needed. If you are using a remote or local server enter this code instead:

PHP
mysql -u root -p -h 127.0.0.1

Once your connected you can continue.

Create or select a Database:

To create a database enter the following command:

PHP
CREATE DATABASE your_database_name;

and then to select a database you can use this command:

PHP
USE your_database_name;

Create a Table:

To create a table in the database you can execute the following command:
change it if wanted / needed.

PHP
CREATE TABLE users (
    id INT(11) NOT NULL AUTO_INCREMENT,
    username VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
    admin TINYINT(2) NOT NULL DEFAULT 0,
    PRIMARY KEY (id)
);

To check if the table was created you can use this command to let all tables be shown:

PHP
SHOW TABLES;

Add a Foreign Key:

Lets say instead of an admin column we want a user_id column that uses the id from the users table so a Foreign Key. Here’s how to do that:

PHP
CREATE TABLE users (
    id INT(11) NOT NULL AUTO_INCREMENT,
    username VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
    PRIMARY KEY (id)
);

CREATE TABLE user_relations (
    id INT(11) NOT NULL AUTO_INCREMENT,
    user_id INT(11) NOT NULL,
    PRIMARY KEY (id),
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE
);

The same goes if you want to use the built-in terminal in PHPStorm for example.

Additional Settings / Indexes

These are the different types of indexes you can give a column, you can think of these as rules that the column has to follow.

  • PK = Primary Key: A column that uniquely identifies each row and cannot contain NULL values.
  • NN = Not Null: Ensures a column must have a value and cannot be left empty.
  • UQ = Unique: Guarantees all values in a column are distinct and non-repeating.
  • B = Binary: Stores raw binary data or enables case-sensitive string comparisons.
  • UN = Unsigned: Disallows negative values, increasing the positive range for numeric types.
  • ZF = Zero Fill: Pads numeric values with leading zeros to match a specified length.
  • AI = Auto Increment: Automatically generates sequential numbers for new rows in a table.
  • G = Generated: Creates columns with values computed dynamically or stored based on an expression.

A big advantage of these indexes are that you can search only the value inside a given index or multiple selected indexes, that makes the search a lot faster and therefor allows it to load faster since you don’t have to search the whole table or even database.

Tags: