Welcome to our SQL tutorial! Today, we're going to build a Social Media Database from scratch. By the end of this project, you'll have a solid understanding of SQL and how to use it to manage data in a real-world application.
Before we dive in, let's make sure you have everything you need:
First things first, let's create our database.
CREATE DATABASE social_media;Now, select the database we just created:
USE social_media;Now that we have our database, it's time to create some tables. In our Social Media Database, we'll have tables for Users, Posts, Comments, and Likes.
CREATE TABLE Users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE,
password_hash VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);CREATE TABLE Posts (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES Users(id)
);CREATE TABLE Comments (
id INT AUTO_INCREMENT PRIMARY KEY,
post_id INT NOT NULL,
user_id INT NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (post_id) REFERENCES Posts(id),
FOREIGN KEY (user_id) REFERENCES Users(id)
);CREATE TABLE Likes (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
post_id INT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES Users(id),
FOREIGN KEY (post_id) REFERENCES Posts(id)
);What is the primary key for the Users table?
Now that we have our tables set up, let's insert some data into them.
INSERT INTO Users (username, email, password_hash)
VALUES ('john_doe', '[john_doe@example.com](mailto:john_doe@example.com)', 'password123');Now, let's insert a post for John Doe.
INSERT INTO Posts (user_id, content)
VALUES (1, 'Hello, world!');What SQL command do we use to insert data into a table?
Now that we have some data, let's see how to query it.
SELECT * FROM Users WHERE id = 1;SELECT * FROM Posts WHERE user_id = 1;SELECT * FROM Comments WHERE post_id = (SELECT id FROM Posts WHERE user_id = 1);SELECT COUNT(*) FROM Likes WHERE post_id = (SELECT id FROM Posts WHERE user_id = 1);What SQL command do we use to fetch data from a table?
Congratulations! You've built a Social Media Database from scratch. Now that you've got the basics down, you can continue to explore SQL and build more complex applications.
Remember, the key to mastering SQL is practice. Keep experimenting, and don't hesitate to ask questions if you're stuck. Happy coding! 💪