1. Mastering Basic SQL: Your First Steps to Data Retrieval
SQL (Structured Query Language) is the indispensable tool for anyone working with data. At its heart, SQL is a language for talking to databases, and the foundation of that conversation lies in the basic structure of the SELECT statement.
To get started, let's use a simple sales database with three tables: Customer, Product, and Sales.
| Table | Purpose |
| Customer | Holds customer details (CustomerID, Name, City) |
| Product | Holds product details (ProductID, Name, Price) |
| Sales | Holds transaction details (SaleID, CustomerID, ProductID, Date, Quantity) |
1. The Core: SELECT and FROM
The SELECT statement is how you tell the database exactly what data you want to see, and FROM tells it which table the data should come from.
To retrieve all columns (use the asterisk
*):
To retrieve specific columns:
2. Filtering Rows: The WHERE Clause
The WHERE clause is your primary tool for filtering data. It restricts the rows returned based on a specified condition.
Retrieve all products priced over $50.00:
Retrieve sales records made after a specific date:
3. Sorting Results: The ORDER BY Clause
The ORDER BY clause is used to sort the result set by one or more columns. Sorting helps you find minimums, maximums, or follow a chronological sequence.
Sort products from highest price to lowest:
Sort customer names alphabetically by City, and then by Name:
4. Limiting Results: The LIMIT Clause
The LIMIT clause (common in MySQL and PostgreSQL) is used to restrict the number of rows returned. This is essential for quickly checking the data or finding top records.
Find the 5 most expensive products:
Comments
Post a Comment