Welcome to our SQL Tutorial, where we'll build a Blog Database from scratch! This tutorial is designed for beginners and intermediates, so no prior SQL knowledge is required. Let's dive in!
SQL (Structured Query Language) is a language used to communicate with databases. It helps us create, manage, and retrieve data from a database.
First, let's set up our Blog Database. We'll use MySQL, a popular open-source Relational Database Management System (RDBMS).
CREATE DATABASE blog;Now, we need to select the database we just created.
USE blog;A table is like a spreadsheet in a database. We'll create three tables: Users, Posts, and Comments.
CREATE TABLE Users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL
);
CREATE TABLE Posts (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
content TEXT NOT NULL,
user_id INT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES Users(id)
);
CREATE TABLE Comments (
id INT AUTO_INCREMENT PRIMARY KEY,
comment TEXT NOT NULL,
post_id INT,
user_id INT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (post_id) REFERENCES Posts(id),
FOREIGN KEY (user_id) REFERENCES Users(id)
);Now that we have our tables, let's insert some data.
INSERT INTO Users (username, email, password)
VALUES ('john_doe', '[john_doe@example.com](mailto:john_doe@example.com)', 'password123');We can retrieve data using SELECT statements.
SELECT * FROM Users;What does SQL stand for?
We've created a basic Blog Database and learned how to create tables and insert data. In the next lessons, we'll learn more advanced SQL concepts like joins, updates, and deletes.
Happy coding! 💻🚀