MySQL Basics: Create table and insert and update data
SQL (Structured Query Language) is like the language you use to talk to your database. Think of it like you’re asking your computer to give you some information it has stored, or you want to tell the computer to add new information to its memory.
Imagine you have a big bookshelf where you store all your books, SQL is like asking your friend to go get a specific book you want to read or asking them to add a new book to the bookshelf.
You use specific phrases, called “commands” in SQL to get things done, like SELECT and INSERT. SELECT is like asking your friend to show you a certain book, and INSERT is like asking your friend to put a new book on the bookshelf. Pretty much every big company uses SQL to interact with the databases of their software, and it’s a standard in the industry.
Create database #
To create a database in SQL, you can use the CREATE DATABASE statement. Here is an example:
CREATE DATABASE mydatabase;
Create table #
Here is an example of a CREATE TABLE statement in SQL:
CREATE TABLE users (
user_id INTEGER PRIMARY KEY,
username TEXT NOT NULL,
password TEXT NOT NULL,
email TEXT NOT NULL
);
This creates a table called users with four columns: user_id, username, password, and email. The user_id column is an integer and is the primary key for the table, meaning that it is unique for each row. The username, password, and email columns are all text values and cannot be NULL.
Insert data #
To insert data into the table, you can use an INSERT statement like this:
INSERT INTO users (username, password, email)
VALUES ('john', 'password123', 'john@example.com');
Update statement #
To update a record in a database table, you can use the UPDATE statement in SQL. Here is the general syntax for an UPDATE statement. For example, to update the email address of a user with a specific user_id in the users table, you can use the following UPDATE statement:
UPDATE users
SET email = 'newemail@example.com'
WHERE username = 'john';
Delete records #
To delete data from a database table in SQL, you can use the DELETE statement. Here is the general syntax for a DELETE statement. For example, to delete a user with a specific user_id from the users table, you can use the following DELETE statement:
DELETE FROM users WHERE user_id = 123;
This will delete the row with user_id 123 from the users table.