Let’s begin our journey of SQL tutorials with the one of the powerful and most commonly used query i.e. SQL SELECT statement. It is used to retrieve rows from a single table or multiple tables or views. SQL SELECT query works in a specific way i.e. it defines what is to fetch (column_list) and from where this data is to be fetch (tables).
Basic SELECT statement syntax –
SELECT column_list FROM table_name
[GROUP BY clause]
[ORDER BY clause]
NOTE: – SELECT and FROM clause are mandatory in sql select queries whereas other clauses written in square  brackets are optional.
- SELECT clause – Specifies column(s) to be displayed.
- FROM clause – Specifies the table which contains all the data in columns and rows format.
- Other clauses within square brackets are optional and will be discussed later in our SQL tutorials section.
We all know that SQL is not a case sensitive language like java, ASP.NET, etc. It means our “SELECT” will display the same result as displayed by “select” in the query. Let’s start fetching the data from the database using the SELECT statement.
- SELECT particular columns example – SELECT column1, column2, column3 FROM table_name;
- SELECT all columns example – SELECT * FROM table_name;
- SELECT unique/distinct columns example – SELECT DISTINCT column1, column2, FROM table_name;
Tips and Tricks:-
- Never return column data which is not required.
Explanation – Because by returning data you don’t need, you are causing SQL engine to perform I/O it doesn’t need to perform, wasting SQL engine resources. In addition, it increases network traffic, which can also lead to reduced Performance
What not to use: – SELECT * FROM table_name;
What to use: – SELECT column1, column2, clomn3 FROM table_name;
- Carefully evaluate your SELECT query whether DISTINCT clause is required or not.
Explanation – The DISTINCT clause should only be used in SELECT statements if you know that duplicate returned rows are a possibility, and that having duplicate rows in the result set would cause problems with your application. The DISTINCT clause creates a lot of extra work for SQL Server, and reduces the physical resources that other SQL statements have at their disposal. That’s why DISTINCT clause is used if necessary.