SQL SELECT Statement 🔍¶
Mentor's Note: If SQL is a conversation,
SELECTis the question. It's how you ask the database, "Can you show me this specific information?" It is the most used command in the world of data. 💡
🌟 The Scenario: The Grocery List 🛒¶
Imagine you are in a massive supermarket.
- SELECT *: "Bring me every single item in the store." (Too much! 🤯)
- SELECT name, price: "Just show me the names and prices of the items." (Much better! ✅)
🎨 Visual Logic: The Extraction Process¶
graph LR
A[(Table: Data)] -- "SELECT Filter" --> B[Result Set: View]
subgraph "Columns"
B1[id]
B2[name]
B3[salary]
end
💻 1. The Basic Syntax¶
A. Select All Columns (*)¶
Use the asterisk (*) to see everything.
B. Select Specific Columns¶
Always prefer this for better performance.
💻 2. Column Aliases (AS) 🏷️¶
You can give a temporary name to a column in your result set to make it more readable.
-- Scenario: Changing technical headers to friendly ones
SELECT first_name AS "Name", salary AS "Monthly_Pay"
FROM employees;
💻 3. Performing Calculations¶
You can perform math directly inside your SELECT statement.
-- Scenario: Calculate an annual bonus (10% of salary)
SELECT
first_name,
salary,
(salary * 0.10) AS bonus
FROM employees;
💡 Pro Tip: The "Rule of SELECT"¶
"Never use
SELECT *in your software code. If someone adds a new column (like a huge image blob) to the table later, your app might crash or slow down because it's fetching data it doesn't need!"