. Working with Databases
Working with databases involves several key concepts that are essential for managing and manipulating data effectively. This section will cover three fundamental aspects: creating databases, managing tables, and handling data within those tables.
1. Creating Databases
Creating a database is the first step in organizing your data. A database is a container that holds one or more tables. To create a database, you use the CREATE DATABASE
statement.
Example:
CREATE DATABASE MyFirstDatabase;
This command creates a new database named "MyFirstDatabase." Once created, you can start adding tables and data to this database.
2. Managing Tables
Tables are the core structure within a database where data is stored. Managing tables involves creating, altering, and deleting them. The CREATE TABLE
statement is used to create a new table, while ALTER TABLE
modifies an existing table, and DROP TABLE
removes a table.
Example of creating a table:
CREATE TABLE Employees ( EmployeeID INT PRIMARY KEY, Name VARCHAR(100), Department VARCHAR(50), HireDate DATE );
This command creates a table named "Employees" with columns for EmployeeID, Name, Department, and HireDate.
Example of altering a table:
ALTER TABLE Employees ADD COLUMN Email VARCHAR(100);
This command adds a new column named "Email" to the "Employees" table.
Example of deleting a table:
DROP TABLE Employees;
This command removes the "Employees" table from the database.
3. Handling Data within Tables
Once tables are created, the next step is to handle the data within them. This involves inserting new data, updating existing data, and deleting data when necessary. The INSERT INTO
statement is used to add new records, UPDATE
modifies existing records, and DELETE FROM
removes records.
Example of inserting data:
INSERT INTO Employees (EmployeeID, Name, Department, HireDate) VALUES (1, 'John Doe', 'Sales', '2023-01-15');
This command adds a new employee record to the "Employees" table.
Example of updating data:
UPDATE Employees SET Department = 'Marketing' WHERE EmployeeID = 1;
This command updates the department of the employee with EmployeeID 1 to "Marketing."
Example of deleting data:
DELETE FROM Employees WHERE EmployeeID = 1;
This command removes the employee record with EmployeeID 1 from the "Employees" table.
Understanding these key concepts and commands is crucial for effectively working with databases. By mastering these operations, you can efficiently manage and manipulate data to meet your needs.