SQL SELECT Rows(s) From Table



SQL SELECT Statement

The SQL SELECT statement is used to query and retrieve data from a database. This statement allows you to specify the columns to be returned and the conditions for selecting rows.


Syntax

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

The SELECT statement has the following components:

  • column1, column2, ...: The columns to be retrieved.
  • table_name: The name of the table from which to retrieve the data.
  • condition: The condition for selecting rows (optional).

Example SQL SELECT Statement Queries

Let's look at some examples of SQL SELECT statement queries:

1. Basic SELECT Example

SELECT first_name, last_name
FROM employees;

This query retrieves the first_name and last_name columns from the employees table. The result will be a list of first and last names.

2. SELECT with WHERE Clause

SELECT first_name, last_name
FROM employees
WHERE last_name = 'Doe';

This query retrieves the first_name and last_name columns from the employees table where the last_name is 'Doe'. The result will be a list of employees with the last name 'Doe'.

3. SELECT All Columns

SELECT *
FROM employees;

This query retrieves all columns from the employees table. The result will be all the data from the employees table.


Full Example

Let's go through a complete example that includes creating a table, inserting data, and querying the table.

Step 1: Creating a Table

This step involves creating a new table named employees to store employee data.

CREATE TABLE employees (
    id INT PRIMARY KEY AUTO_INCREMENT,
    first_name VARCHAR(50),
    last_name VARCHAR(50),
    email VARCHAR(100)
);

In this example, we create a table named employees with columns for id, first_name, last_name, and email.

Step 2: Inserting Data into the Table

This step involves inserting some sample data into the employees table.

INSERT INTO employees (first_name, last_name, email)
VALUES ('John', 'Doe', 'john.doe@example.com');

INSERT INTO employees (first_name, last_name, email)
VALUES ('Jane', 'Smith', 'jane.smith@example.com');

INSERT INTO employees (first_name, last_name, email)
VALUES ('Jim', 'Brown', 'jim.brown@example.com');

Here, we insert data into the employees table.

Step 3: Querying the Table

This step involves selecting the data from the employees table to view the inserted records.

SELECT *
FROM employees;

This query retrieves all the rows from the employees table. The result will be:

id  first_name  last_name  email
--- ----------- ---------- ------------------------
1   John        Doe        john.doe@example.com
2   Jane        Smith      jane.smith@example.com
3   Jim         Brown      jim.brown@example.com

Conclusion

The SQL SELECT statement is a fundamental tool for querying and retrieving data from a database. Understanding how to use the SELECT statement and its syntax is essential for effective data management and analysis in SQL databases.