Welcome to the fundamental guide to SQL (Structured Query Language). SQL is the standard language for relational database management. It allows you to create, retrieve, update, and delete data in databases.
A database is an organized collection of structured information, or data, typically stored electronically in a computer system. Relational databases organize data into tables, which consist of rows and columns.
SQL is used to communicate with a database. It's a programming language that is specialized for managing and manipulating data in relational database systems.
Think of a table like a spreadsheet:
Customers table.CustomerID, FirstName, LastName.You'll use a DBMS to interact with your database. Popular examples include:
The SELECT statement is used to fetch data from a database. You can select one or more columns, or all columns, from one or more tables.
Syntax:
SELECT column1, column2, ...
FROM table_name;
Example: Select all columns from the Customers table:
SELECT * FROM Customers;
Example: Select specific columns from the Products table:
SELECT ProductName, Price
FROM Products;
The INSERT INTO statement is used to add new records to a table.
Syntax:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
If you are adding values for all columns, you can omit the column list, but it's good practice to include it.
Example: Insert a new customer:
INSERT INTO Customers (CustomerID, FirstName, LastName, Email)
VALUES (101, 'Jane', 'Doe', 'jane.doe@example.com');
The UPDATE statement is used to modify existing records in a table.
Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
The WHERE clause is crucial. If you omit it, all rows will be updated!
Example: Update the email for customer with CustomerID 101:
UPDATE Customers
SET Email = 'janedoe.updated@example.com'
WHERE CustomerID = 101;
The DELETE statement is used to delete existing records from a table.
Syntax:
DELETE FROM table_name
WHERE condition;
Again, the WHERE clause is essential. Omitting it will delete all records in the table.
Example: Delete the customer with CustomerID 101:
DELETE FROM Customers
WHERE CustomerID = 101;
Let's imagine a Books table:
| BookID | Title | Author | Genre | PublicationYear |
|---|---|---|---|---|
| 1 | The Hitchhiker's Guide to the Galaxy | Douglas Adams | Science Fiction | 1979 |
| 2 | Pride and Prejudice | Jane Austen | Romance | 1813 |
| 3 | 1984 | George Orwell | Dystopian | 1949 |
SQL Query to get all books by George Orwell:
SELECT Title, Author
FROM Books
WHERE Author = 'George Orwell';
Result:
Title: 1984Author: George OrwellThis covers the very basics. Here are some concepts to explore next:
WHERE clause with operators (=, <, >, !=, LIKE, IN, BETWEEN)ORDER BY clause for sortingGROUP BY clause for aggregationJOIN operations to combine data from multiple tablesCOUNT(), SUM(), AVG(), MAX(), MIN()