This tutorial aims to guide you on how to perform CRUD operations with databases. CRUD stands for Create, Read, Update, and Delete, the four basic operations that can be performed on any data stored in a database.
By the end of this tutorial, you will be able to:
Prerequisites:
- Basic knowledge of SQL.
- A database management system installed, like MySQL or PostgreSQL.
The first operation in CRUD is creating or inserting data into the database. This is achieved using the INSERT INTO
statement in SQL.
Syntax:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...);
The 'Read' operation retrieves data from the database. We use the SELECT
statement for this.
Syntax:
SELECT column1, column2,...
FROM table_name;
The 'Update' operation modifies existing data in the database. For this, we use the UPDATE
statement.
Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2,...
WHERE some_column = some_value;
The 'Delete' operation removes data from the database. This is done with the DELETE
statement.
Syntax:
DELETE FROM table_name WHERE some_column = some_value;
Let's insert a new record in the 'students' table.
INSERT INTO students (id, name, age, grade)
VALUES (1, 'John Doe', 15, '10th Grade');
Let's read all records from the 'students' table.
SELECT * FROM students;
Let's update the age of 'John Doe' in the 'students' table from 15 to 16.
UPDATE students
SET age = 16
WHERE name = 'John Doe';
Let's delete the record of 'John Doe' from the 'students' table.
DELETE FROM students WHERE name = 'John Doe';
In this tutorial, we covered how to perform CRUD operations with databases using SQL. We looked at how to create, read, update, and delete records in a database.
Next steps for learning:
- Learn about indexing in databases for faster search.
- Learn about relationships in databases.
- Learn about normalization and denormalization in databases.
Let's practice what we've learned with the following exercises:
Exercise 1: Create a table 'teachers' with the columns 'id', 'name', 'age', 'subject'. Insert 3 records into it.
Exercise 2: Read all records from the 'teachers' table where 'age' is more than 30.
Exercise 3: Update the 'subject' of a teacher from 'Math' to 'Physics'.
Exercise 4: Delete a record from the 'teachers' table where 'name' is 'Mr. Smith'.
Practice these exercises until you are comfortable with CRUD operations. Happy learning!