SQL Tutorial
The SELECT
statement is one of the most fundamental and commonly used commands in SQL. It is used to retrieve data from a database. The data returned is stored in a result table, called the result-set.
Here's the basic syntax:
SELECT column1, column2, ... FROM table_name;
You can also select all columns in a table using the wildcard *
:
SELECT * FROM table_name;
Examples:
Consider the following Employees
table:
EmployeeID | FirstName | LastName | Department |
---|---|---|---|
1 | John | Doe | Sales |
2 | Jane | Smith | HR |
3 | Alice | Johnson | IT |
4 | Charlie | Brown | Marketing |
If you want to select only the FirstName
and LastName
columns, your SELECT
statement would look like this:
SELECT FirstName, LastName FROM Employees;
This SQL statement will return:
FirstName | LastName |
---|---|
John | Doe |
Jane | Smith |
Alice | Johnson |
Charlie | Brown |
If you want to select all columns from the "Employees" table, use the *
wildcard:
SELECT * FROM Employees;
This SQL statement will return all columns from the "Employees" table.
Additional Points:
SELECT
statement is not case-sensitive. SELECT
is the same as select
.SELECT DISTINCT
statement is used to return only distinct (different) values.SELECT
can also be used in conjunction with other commands and functions to conduct more complex queries (such as JOIN
, WHERE
, GROUP BY
, and so on).Selecting Specific Columns in SQL:
SELECT column1, column2 FROM example_table;
Filtering Data with WHERE Clause in SQL SELECT:
SELECT * FROM example_table WHERE column1 = 'value';
Sorting Results with ORDER BY in SQL SELECT:
SELECT * FROM example_table ORDER BY column1 DESC, column2 ASC;
Limiting Rows with LIMIT in SQL SELECT:
SELECT * FROM example_table LIMIT 10;
Using DISTINCT in SQL SELECT:
SELECT DISTINCT column1 FROM example_table;
Aggregating Data with GROUP BY in SQL SELECT:
SELECT column1, COUNT(*) FROM example_table GROUP BY column1;
Joining Tables in SQL SELECT Statement:
SELECT table1.column1, table2.column2 FROM table1 INNER JOIN table2 ON table1.column_name = table2.column_name;
Subqueries in SQL SELECT Statement:
SELECT column1, (SELECT AVG(column2) FROM another_table) AS average_value FROM example_table;