SQL SELECT Statement
The SELECT
statement is one of the most commonly used commands in SQL. It is used to retrieve data from one or more tables in a database. You can specify the columns you want to retrieve or use a wildcard (*
) to select all columns.
Syntax
The basic syntax of the SELECT statement is:
SELECT column1, column2, ...
FROM table_name;
SELECT * FROM table_name;
Example
Let us retrieve all columns from the Staff table and then retrieve specific columns (ID and Name).
Code Example
-- Retrieve all columns from the Staff table
SELECT * FROM Staff;
-- Retrieve specific columns: ID and Name
SELECT ID, Name FROM Staff;
Output
ID | Name | Age | Department |
---|---|---|---|
1 | Alice | 30 | HR |
2 | Bob | 25 | IT |
3 | Charlie | 35 | Finance |
ID | Name |
---|---|
1 | Alice |
2 | Bob |
3 | Charlie |
Explanation
- The first SELECT * query retrieves all the columns from the Staff table.
- The second SELECT ID, Name query retrieves only the ID and Name columns.
- The output demonstrates the retrieved rows based on the queries.
- Use SELECT * only when you need all columns; otherwise, explicitly specify the columns to improve performance.
- Ensure the table exists and contains the required data before executing the SELECT statement.