Beginner's guide to MySQL syntax - torarnehave1/slowyouio GitHub Wiki

Here's a beginner's guide to MySQL syntax covering the basics, starting from creating a database. This guide will help you understand how to perform fundamental database operations using MySQL.

1. Installing MySQL

Before you begin, you need to install MySQL. You can download it from the official MySQL website and follow their instructions for installation on your operating system.

2. Accessing MySQL

To start using MySQL, open your command-line interface and type:

mysql -u root -p

You'll be prompted to enter the password for the MySQL root user.

3. Creating a Database

To create a new database:

CREATE DATABASE example_db;

4. Selecting a Database

To start working with your new database, you need to select it:

USE example_db;

5. Creating Tables

A table is where your data is stored. Here's how to create a simple table:

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL,
    email VARCHAR(100) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

This command creates a table called users with four columns: id, username, email, and created_at.

6. Inserting Data

To add data to your table:

INSERT INTO users (username, email) VALUES ('johndoe', '[email protected]');

7. Reading Data

To retrieve data from a table:

SELECT * FROM users;

This retrieves all columns and all rows from the users table.

To retrieve only certain columns:

SELECT username, email FROM users;

8. Updating Data

To update existing data:

UPDATE users SET email = '[email protected]' WHERE username = 'johndoe';

This changes the email address for the user johndoe.

9. Deleting Data

To delete data:

DELETE FROM users WHERE username = 'johndoe';

This removes the record for johndoe from the users table.

10. Dropping a Table

If you decide that you no longer need a table:

DROP TABLE users;

11. Dropping a Database

Similarly, if you want to remove an entire database:

DROP DATABASE example_db;

Additional Tips

  • SQL Syntax: SQL commands are not case-sensitive. However, it's common to use uppercase for SQL keywords.
  • Helpful Functions: Use functions like NOW() for the current date and time when inserting data.
  • Security Practices: Ensure your database and tables are designed with security in mind, especially when handling sensitive information.

This guide covers basic SQL commands in MySQL and provides a foundation from which you can expand your skills. As you grow more comfortable, explore more complex queries, including joins, subqueries, and transactions, to fully leverage the power of your database.