Courses / SQL
1. SELECT Statement
The SQL command used to select data from a database.
How It Works
Think of a database as a large library, where each table is a shelf filled with books (data). The SELECT statement is like asking a librarian to fetch specific books based on your criteria.
You specify the columns you want to retrieve.
You identify the table from which to select the data.
You can apply conditions to filter results.
You execute the query to get the results.
See It
The code creates an `employees` table and inserts three records. The SELECT statement retrieves the names of employees in the 'Engineering' department, which will return 'Bob'.
CREATE TABLE employees (
id INT,
name VARCHAR(50),
department VARCHAR(50)
);
INSERT INTO employees (id, name, department) VALUES
(1, 'Alice', 'HR'),
(2, 'Bob', 'Engineering'),
(3, 'Charlie', 'Sales');
SELECT name FROM employees WHERE department = 'Engineering';Use It
This concept is used when generating reports from a database.
SELECT COUNT(*) FROM employees WHERE department = 'Sales';Using the SELECT statement allows for efficient data retrieval to summarize information, such as counting employees in a specific department.
Break It
What will this return?
SELECT name, department FROM employees WHERE department = 'Engineering' AND id = 1;The query specifies an id of 1, but that id corresponds to 'Alice' in the HR department, not 'Bob' in Engineering, leading to no matching records.
Change the `id` condition to match an employee in the Engineering department, such as `id = 2`.
SELECT name, department FROM employees WHERE department = 'Engineering' AND id = 2;Level Up
Using JOINs with SELECT: JOINs allow you to combine rows from two or more tables based on a related column, enriching your data retrieval.
SELECT with GROUP BY: GROUP BY enables you to aggregate data, like counting how many employees are in each department.
Prove It
Write a SQL query to retrieve the names of all employees in the 'HR' department.
SQL
SELECT Statement
The SELECT statement is used to retrieve data from a database.
"I need to quickly find specific information without sifting through tons of data."
The SELECT statement allows you to specify which columns of data you want to retrieve from a database table and filter the results based on conditions.
"I need to quickly find specific information without sifting through tons of data."
The SELECT statement allows you to specify which columns of data you want to retrieve from a database table and filter the results based on conditions.