SQL Basics
Welcome to the foundational guide for SQL (Structured Query Language). This section covers the essential concepts and commands you need to get started with relational databases.
What is SQL?
SQL is a standard language for managing and manipulating databases. It's used to communicate with a database. SQL is a declarative language, meaning you tell the database what you want to do, and it figures out how to do it.
Key uses of SQL include:
- Querying data
- Inserting data
- Updating data
- Deleting data
- Creating and modifying database structures
Core Concepts
Databases and Tables
A database is an organized collection of data. Within a database, data is typically stored in tables. A table is a collection of related data entries organized in a row-and-column format.
Columns and Rows
Each column in a table represents a specific attribute (e.g., 'CustomerID', 'FirstName'). Each row represents a single record or entry (e.g., a specific customer's details).
Primary Keys
A primary key is a column (or a set of columns) that uniquely identifies each row in a table. It ensures that no two rows have the same key value.
Foreign Keys
A foreign key is a column that establishes a link between two tables. It is a column in one table that refers to the primary key in another table, enforcing referential integrity.
Essential SQL Commands (CRUD Operations)
SQL commands are often categorized by the operations they perform. The most fundamental are CRUD operations:
SELECT: Retrieving Data
The SELECT
statement is used to query the database and retrieve data from one or more tables.
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Example: Get all customer names and emails from the 'Customers' table.
SELECT FirstName, LastName, Email
FROM Customers;
INSERT: Adding Data
The INSERT INTO
statement is used to add new records into a table.
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
Example: Add a new customer.
INSERT INTO Customers (FirstName, LastName, Email)
VALUES ('Jane', 'Doe', 'jane.doe@example.com');
UPDATE: Modifying Data
The UPDATE
statement is used to modify existing records in a table.
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Example: Update the email for a customer named 'Jane Doe'.
UPDATE Customers
SET Email = 'jane.d@newdomain.com'
WHERE FirstName = 'Jane' AND LastName = 'Doe';
DELETE: Removing Data
The DELETE FROM
statement is used to remove existing records from a table.
DELETE FROM table_name
WHERE condition;
Example: Delete a customer named 'Jane Doe'.
DELETE FROM Customers
WHERE FirstName = 'Jane' AND LastName = 'Doe';
Caution: Omitting the WHERE
clause will delete ALL records from the table.
Next Steps
Now that you understand the basics, explore more advanced topics like: