These clauses help us filter, sort and restrict records returned by a query.
SELECT *
FROM Student
WHERE City = 'Mumbai';
SELECT *
FROM Student
ORDER BY Name;
SELECT *
FROM Student
ORDER BY Name DESC;
SELECT *
FROM Student
LIMIT 2;
Relationships allow tables to be connected with each other.
One Category can contain many Blog Posts.
| CategoryId | Name |
|---|---|
| 1 | Technology |
| 2 | Travel |
| PostId | Title | CategoryId |
|---|---|---|
| 1 | Django Basics | 1 |
| 2 | Goa Trip | 2 |
CREATE TABLE Category
(
Id INT PRIMARY KEY AUTO_INCREMENT,
Name VARCHAR(100)
);
CREATE TABLE Post
(
Id INT PRIMARY KEY AUTO_INCREMENT,
Title VARCHAR(200),
CategoryId INT,
FOREIGN KEY(CategoryId)
REFERENCES Category(Id)
);
Joins are used to retrieve data from multiple related tables.
| Id | Name |
|---|---|
| 1 | Technology |
| 2 | Travel |
| Id | Title | CategoryId |
|---|---|---|
| 1 | Django Basics | 1 |
| 2 | Goa Trip | 2 |
SELECT
Post.Title,
Category.Name
FROM Post
INNER JOIN Category
ON Post.CategoryId = Category.Id;
+---------------+------------+
| Title | Name |
+---------------+------------+
| Django Basics | Technology |
| Goa Trip | Travel |
+---------------+------------+
A Transaction is a group of SQL statements executed as a single unit of work.
Transactions help maintain data consistency and prevent partial updates.
COMMIT permanently saves changes made during a transaction.
START TRANSACTION;
UPDATE Student
SET City = 'Pune'
WHERE Id = 1;
COMMIT;
ROLLBACK cancels all changes made during the current transaction.
START TRANSACTION;
UPDATE Student
SET City = 'Mumbai'
WHERE Id = 1;
ROLLBACK;
START TRANSACTION;
UPDATE Accounts
SET Balance = Balance - 1000
WHERE Id = 1;
UPDATE Accounts
SET Balance = Balance + 1000
WHERE Id = 2;
COMMIT;
A Stored Procedure is a group of SQL statements stored inside the database and executed whenever required.
DELIMITER //
CREATE PROCEDURE GetStudents()
BEGIN
SELECT * FROM Student;
END //
DELIMITER ;
CALL GetStudents();
All records from Student table will be displayed.
Before starting our Django Blog Project, let's understand the database design.
| Table | Purpose |
|---|---|
| Category | Store Blog Categories |
| Post | Store Blog Posts |
Category
--------------------------------
Id
Name
Post
--------------------------------
Id
Title
Description
Image
CreatedDate
CategoryId
One Category
|
|
|
Many Posts
CREATE TABLE Category
(
Id INT PRIMARY KEY AUTO_INCREMENT,
Name VARCHAR(100) NOT NULL
);
CREATE TABLE Post
(
Id INT PRIMARY KEY AUTO_INCREMENT,
Title VARCHAR(200) NOT NULL,
Description TEXT,
Image VARCHAR(255),
CreatedDate DATETIME DEFAULT CURRENT_TIMESTAMP,
CategoryId INT,
FOREIGN KEY(CategoryId)
REFERENCES Category(Id)
);