SQL SELECT Statement πΒΆ
Prerequisites: CREATE TABLE
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!"