SQL - SELECT Query

This tutorial will explain how to use SELECT clause in a SQL query and how to use them with the examples.

SELECT clause is used to lists the results by given column name(s)

This is the general statement to use SELECT from a table

SELECT
column1, column2, ...
FROM
tablename

Lets create a sample table and add some rows

CREATE TABLE SampleContacts (
FullName VARCHAR(50) NOT NULL,
Gender CHAR(1) NOT NULL,
Age INT NOT NULL
);


INSERT INTO SampleContacts
(FullName, Gender, Age)
VALUES
('Contact1', 'M', 26),
('Contact2', 'M', 29),
('Contact3', 'F', 27),
('Contact4', 'F', 29),
('Contact5', 'F', 27),
('Contact6', 'M', 29)

A) Using SELECT clause with single column
The following statement returns all records with only FullName values from SampleContacts:

SELECT
FullName
FROM
SampleContacts


| FullName |
------------
Contact1
Contact2
Contact3
Contact4
Contact5
Contact6


B) Using SELECT clause with multiple column
The following statement returns all records with FullName, Gender, Age column values from SampleContacts table:

SELECT
FullName, Gender, Age
FROM
SampleContacts


| FullName | Gender | Age |
---------------------------
Contact1 M 26
Contact2 M 29
Contact3 F 27
Contact4 F 29
Contact5 F 27
Contact6 M 29

C) Using SELECT clause with all columns
The following statement returns all records with the all available column values from SampleContacts table:

SELECT
*
FROM
SampleContacts


| FullName | Gender | Age |
---------------------------
Contact1 M 26
Contact2 M 29
Contact3 F 27
Contact4 F 29
Contact5 F 27
Contact6 M 29

D) Using SELECT clause with expression on the columns
The following statement returns all records with FullName, Gender, Age column values from SampleContacts table:

SELECT
FullName, Gender, Age, (1000/Age) DiscountRate
FROM
SampleContacts


| FullName | Gender | Age | DiscountRate |
------------------------------------------
Contact1 M 26 38
Contact2 M 29 34
Contact3 F 27 37
Contact4 F 29 34
Contact5 F 27 37
Contact6 M 29 34