Thursday, December 19, 2024

SQL SELECT Keyword

 The SQL SELECT keyword is used to retrieve data from a database. It is one of the most fundamental and widely used commands in SQL (Structured Query Language). The SELECT statement allows you to query and extract specific information from a table or multiple tables, based on certain conditions.

Basic Syntax:

SELECT column1, column2, ...
FROM table_name;
  • column1, column2, ...: The columns you want to retrieve from the table. You can list specific columns, or use * to select all columns.
  • table_name: The name of the table from which you want to retrieve data.

Examples:

  1. Select all columns from a table:

    SELECT * FROM employees;
    

    This retrieves all columns and rows from the employees table.

  2. Select specific columns from a table:

    SELECT first_name, last_name FROM employees;
    

    This retrieves the first_name and last_name columns from the employees table.

  3. Select distinct (unique) values:

    SELECT DISTINCT department FROM employees;
    

    This retrieves a list of unique departments from the employees table, removing duplicates.

  4. Select with a condition (using WHERE clause):

    SELECT first_name, last_name FROM employees WHERE department = 'HR';
    

    This retrieves the first_name and last_name of employees who work in the 'HR' department.

  5. Order the results (using ORDER BY clause):

    SELECT first_name, last_name FROM employees ORDER BY last_name;
    

    This retrieves employee names and orders the results alphabetically by last_name.

  6. Limit the number of results (using LIMIT or FETCH clause):

    SELECT first_name, last_name FROM employees LIMIT 5;
    

    This retrieves only the first 5 rows from the employees table.

Combining with Other Clauses:

You can also combine the SELECT statement with other SQL clauses like:

  • WHERE: Filters rows based on a condition.
  • ORDER BY: Sorts the results.
  • GROUP BY: Groups rows based on column values, often used with aggregate functions.
  • JOIN: Combines rows from two or more tables based on a related column.

Example with multiple clauses:

SELECT first_name, last_name, department
FROM employees
WHERE department = 'IT'
ORDER BY last_name ASC;

This retrieves the first_name, last_name, and department of employees in the 'IT' department, ordered by last_name in ascending order.

In short, the SELECT keyword is essential for querying and extracting data from a database in SQL.

No comments:

Post a Comment