Retrieving Data in SQL (SELECT) 📌
.jpg)
Retrieving Data in SQL (SELECT) 📌
The SELECT statement is used to retrieve data from a database table. You can retrieve all columns, specific columns, filter results, and sort them.
1️⃣ Selecting All Columns (SELECT *)
To fetch all the data from a table, use SELECT *.
✅ Syntax:
SELECT * FROM table_name;
✅ Example:
SELECT * FROM students;
🔹 Output:
| id | name | age | email | |
|---|
| 1<.td> | Alice | 20 | alice@example.com |
| 2 | Bob | 22 | bob@example.com |
| 3 | Charlie 23 | charlie@example.com |
2️⃣ Selecting Specific Columns
To fetch only certain columns, specify them in the SELECT statement.
✅ Syntax:
sql
Copy
Edit
SELECT column1, column2 FROM table_name;
✅ Example:
sql
Copy
Edit
SELECT name, age FROM students;
🔹 Output:
name age
Alice 20
Bob 22
Charlie 23
3️⃣ Filtering Data with WHERE
The WHERE clause filters rows based on conditions.
✅ Syntax:
sql
Copy
Edit
SELECT column1, column2 FROM table_name WHERE condition;
✅ Example: Get students older than 21
sql
Copy
Edit
SELECT * FROM students WHERE age > 21;
🔹 Output:
id name age email
2 Bob 22 bob@example.com
3 Charlie 23 charlie@example.com
👉 Filtering with Multiple Conditions
✅ Using AND (Both conditions must be true)
sql
Copy
Edit
SELECT * FROM students WHERE age > 20 AND name = 'Bob';
✅ Using OR (At least one condition must be true)
sql
Copy
Edit
SELECT * FROM students WHERE age < 21 OR name = 'Charlie';
✅ Using LIKE (Pattern matching)
sql
Copy
Edit
SELECT * FROM students WHERE name LIKE 'A%'; -- Names starting with 'A'
✅ Using IN (Multiple possible values)
sql
Copy
Edit
SELECT * FROM students WHERE name IN ('Alice', 'Charlie');
✅ Using BETWEEN (Range filtering)
sql
Copy
Edit
SELECT * FROM students WHERE age BETWEEN 20 AND 22;
4️⃣ Sorting Data with ORDER BY
The ORDER BY clause sorts results in ascending (ASC) or descending (DESC) order.
✅ Syntax:
sql
Copy
Edit
SELECT column1, column2 FROM table_name ORDER BY column_name ASC|DESC;
✅ Example: Sort students by age (ascending)
sql
Copy
Edit
SELECT * FROM students ORDER BY age ASC;
🔹 Output:
id name age email
1 Alice 20 alice@example.com
2 Bob 22 bob@example.com
3 Charlie 23 charlie@example.com
✅ Example: Sort students by age (descending)
sql
Copy
Edit
SELECT * FROM students ORDER BY age DESC;
🔹 Output:
id name age email
3 Charlie 23 charlie@example.com
2 Bob 22 bob@example.com
1 Alice 20 alice@example.com
👉 Sorting with Multiple Columns
To sort by multiple columns, list them in ORDER BY.
sql
Copy
Edit
SELECT * FROM students ORDER BY age DESC, name ASC;
First sorts by age in descending order.
If age is the same, sorts by name in ascending order.
🎯 Summary
✔ SELECT * retrieves all columns.
✔ SELECT column1, column2 retrieves specific columns.
✔ WHERE filters data based on conditions.
✔ ORDER BY sorts data in ascending (ASC) or descending (DESC) order.
Date: 2025-03-28 00:00:00.000000