start learning
Image 1
614

Retrieving Data with SELECT Statements

Retrieving data with SELECT statements is a fundamental aspect of working with databases. The SELECT statement is used to query the database and retrieve information from one or more tables.

Here's an overview of the basic structure of a SELECT statement and some common examples :

Basic SELECT Statement

The basic syntax of a SELECT statement is as follows :


SELECT column1, column2, ...
FROM table_name
WHERE condition;
Examples :

Selecting All Columns from a Table


SELECT * FROM employees;

Selecting Specific Columns


SELECT first_name, last_name, salary
FROM employees;

Filtering Rows with WHERE Clause


SELECT product_name, price
FROM products
WHERE price > 50;

Using Logical Operators in WHERE Clause


SELECT product_name, price
FROM products
WHERE category = 'Electronics' AND price > 100;

Sorting Results with ORDER BY


SELECT product_name, price
FROM products
ORDER BY price DESC;

Limiting the Number of Rows with LIMIT


SELECT product_name, price
FROM products
LIMIT 10;

Joining Tables


SELECT orders.order_id, customers.customer_name, orders.order_date
FROM orders
JOIN customers ON orders.customer_id = customers.customer_id;

Aggregating Data with GROUP BY


SELECT department_id, AVG(salary) AS average_salary
FROM employees
GROUP BY department_id;

Filtering Grouped Results with HAVING


SELECT department_id, AVG(salary) AS average_salary
FROM employees
GROUP BY department_id
HAVING AVG(salary) > 50000;

These examples cover some common scenarios when using SELECT statements. Remember that SQL is a powerful language, and you can combine and customize these clauses to meet your specific requirements. Always refer to the official MySQL documentation for detailed information and advanced usage.

×