MySQL SELECT Query

The SELECT statement is the most commonly used command in SQL. It allows you to retrieve data from one or more tables in a database. Whether you need to fetch all records, specific columns, or filtered results,SELECT is your primary tool.

Basic Syntax

SELECT column1, column2, ...
FROM table_name;

Select All Columns

Use the asterisk (*) to select all columns from a table:

SELECT * FROM employees;

Select Specific Columns

Specify only the columns you need:

SELECT name, email, salary 
FROM employees;

DISTINCT Keyword

Use DISTINCT to eliminate duplicate rows:

SELECT DISTINCT department 
FROM employees;

SELECT DISTINCT city, country 
FROM customers;

Calculated Columns

Perform calculations in your SELECT statement:

SELECT name, salary, 
       salary * 1.1 AS increased_salary,
       salary / 12 AS monthly_salary
FROM employees;

LIMIT Clause

Restrict the number of rows returned:

-- Get first 10 records
SELECT * FROM employees 
LIMIT 10;

-- Get 5 records starting from the 11th
SELECT * FROM employees 
LIMIT 10, 5;

CONCAT Function

Combine columns or strings:

SELECT CONCAT(first_name, ' ', last_name) AS full_name,
       email
FROM employees;

SELECT CONCAT('Employee: ', name, ' - Salary: $', salary) AS info
FROM employees;

Practical Examples

Example 1: Employee Information
-- Get all employee details with formatted output
SELECT 
    id,
    name,
    email,
    CONCAT('$', FORMAT(salary, 2)) AS formatted_salary,
    DATE_FORMAT(hire_date, '%M %d, %Y') AS hire_date_formatted
FROM employees
ORDER BY hire_date DESC;
Example 2: Product Catalog
-- Get product details with calculations
SELECT 
    product_id,
    product_name,
    category,
    price,
    quantity_in_stock,
    price * 0.85 AS discounted_price, -- 15% discount
    CASE 
        WHEN quantity_in_stock < 10 THEN 'Low Stock'
        WHEN quantity_in_stock < 50 THEN 'Medium Stock'
        ELSE 'High Stock'
    END AS stock_status
FROM products
WHERE active = 1
ORDER BY category, price DESC;

Best Practices

  • Avoid using SELECT * in production code - specify columns explicitly
  • Use table aliases for complex queries
  • Always include a WHERE clause when updating/deleting
  • Use LIMIT when testing queries on large tables