
Select in MySql
SELECT
in MySQL
The SELECT
statement in MySQL is used to retrieve data from one or more tables in a database. It allows filtering, sorting, and aggregating data.
1. Basic Syntax
SELECT column1, column2 FROM table_name;
- To select all columns, use
*
:
SELECT * FROM table_name;
2. Selecting Specific Columns
SELECT name, salary FROM employees;
✅ Example Output:
name | salary |
---|---|
Alice | 6000 |
Bob | 7000 |
3. Using WHERE Clause (Filtering Data)
SELECT * FROM employees WHERE salary > 6000;
✅ Result: (Only employees with salary greater than 6000)
emp_id | name | salary |
---|---|---|
2 | Bob | 7000 |
4. Using ORDER BY (Sorting Data)
SELECT * FROM employees ORDER BY salary DESC;
✅ Sorts employees by salary in descending order.
5. Using DISTINCT (Removing Duplicates)
SELECT DISTINCT department FROM employees;
✅ Returns unique department names.
6. Using LIMIT (Get Top Results)
SELECT * FROM employees ORDER BY salary DESC LIMIT 3;
✅ Returns the top 3 highest salaries.
7. Using IN
(Match Multiple Values)
SELECT * FROM employees WHERE department IN ('IT', 'HR');
✅ Returns employees from IT or HR departments.
8. Using BETWEEN
(Range Query)
SELECT * FROM employees WHERE salary BETWEEN 5000 AND 7000;
✅ Returns employees with salaries between 5000 and 7000.
9. Using LIKE
(Pattern Matching)
SELECT * FROM employees WHERE name LIKE 'A%';
✅ Finds names starting with "A".
10. Using JOINs (Fetching Data from Multiple Tables
SELECT employees.name, departments.dept_nameFROM employeesJOIN departments ON employees.dept_id = departments.dept_id;
✅ Fetches employee names along with department names.
11. Using Aggregation Functions
SELECT COUNT(*) FROM employees;SELECT AVG(salary) FROM employees;SELECT SUM(salary) FROM employees;
✅ Performs count, average, and sum calculations.
12. Using GROUP BY and HAVING
SELECT department, AVG(salary) FROM employees GROUP BY department HAVING AVG(salary) > 6000;
✅ Groups employees by department and filters those with an average salary > 6000.
Key Takeaways
✅ SELECT
retrieves data from a database.
✅ Use WHERE
to filter results.
✅ Use ORDER BY
for sorting.
✅ Use JOIN
to fetch data from multiple tables.
✅ Use GROUP BY
and HAVING
for aggregation.