SQL Select

Syntax:

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

  • column1, column2, ...: The columns you want to retrieve. You can use * to select all columns.
  • table_name: The name of the table from which you want to retrieve data.
  • WHERE condition: Optional. It allows you to filter the rows based on a specified condition.

Example 1: Select All Columns

                                  
                                    SELECT * FROM employees;
                                  
                                

This retrieves all columns for all records in the employees table.

Example 2: Select Specific Columns

                                  
                                    SELECT employee_id, first_name, last_name FROM employees;
                                  
                                

This retrieves only the specified columns (employee_id, first_name, and last_name) for all records in the employees table.

Example 3: Filter with WHERE Clause

                                  
                                    SELECT * FROM employees
WHERE salary > 50000;
                                  
                                

This retrieves all columns for employees with a salary greater than 50000.

Example 4: Combining Conditions

                                  
                                    SELECT * FROM employees
WHERE salary > 50000 AND hire_date < '2023-01-01';
                                  
                                

This retrieves all columns for employees with a salary greater than 50000 hired before January 1, 2023.

Example 5: Sorting Results

                                  
                                    SELECT * FROM employees
ORDER BY salary DESC;
                                  
                                

This retrieves all columns for all employees and sorts the results by salary in descending order.

Example 6: Limiting Results

                                  
                                    SELECT * FROM employees
LIMIT 10;
                                  
                                

This retrieves the first 10 rows from the employees table.

Example 7: Aggregation Functions

                                  
                                    SELECT AVG(salary) AS average_salary, MAX(salary) AS max_salary
FROM employees
WHERE hire_date > '2022-01-01';
                                  
                                

This calculates the average and maximum salary for employees hired after January 1, 2022.

Tips:
  • Use aliases (e.g., AS average_salary) to rename columns or results of calculations for better readability.
  • Be mindful of data types and ensure that conditions in the WHERE clause are appropriate for the data.