SQL Select Statement – Tutorial with Examples

The SELECT statement is one of the most commonly used statements in SQL, and it is used to retrieve data from a database table. The SELECT statement allows you to retrieve specific columns from one or more tables. In this article, we will discuss the basics of the SELECT statement and how to use it effectively.

Syntax

The basic syntax of the SELECT statement is as follows:

SELECT column1, column2, ...
FROM table_name;

In the example above, we are retrieving the values of two columns (column1 and column2) from a table named `table_name`. The `SELECT` keyword is followed by a list of column names, separated by commas. The `FROM` keyword is used to specify the name of the table that contains the data we want to retrieve. The semicolon (;) at the end of the statement is used to indicate the end of the statement.

Retrieving All Columns

If you want to retrieve all columns from a table, you can use the wildcard character (*) instead of specifying a list of column names. For example:

SELECT *
FROM table_name;

This will retrieve all columns from the `table_name` table.

Example

Let’s say we have a table named `customers` with the following data:

id name city
1 John London
2 Sarah Paris
3 Mike Berlin

To retrieve the name and city columns from the `customers` table, we can use the following SELECT statement:

SELECT name, city
FROM customers;

This will return the following result:

name city
John London
Sarah Paris
Mike Berlin

As you can see, the SELECT statement allows us to retrieve specific columns from a table and represent the data in a clear and organized manner.

Distinct Rows

The SELECT statement can also retrieve only distinct (unique) rows from a table. To do this, we use the DISTINCT keyword:

SELECT DISTINCT column1, column2, ...
FROM table_name;

For example, let’s say we have a table named `orders` with the following data:

id product customer
1 Apple John
2 Banana Sarah
3 Apple John

To retrieve the unique customer names from the `orders` table, we can use the following SELECT statement:

SELECT DISTINCT customer
FROM orders;

This will return the following result:

customer
John
Sarah

As you can see, the SELECT statement with the DISTINCT keyword allows us to retrieve only the unique values from a table.

Conclusion

The SELECT statement is a fundamental and essential part of SQL and it is used to retrieve data from a database table. The SELECT statement allows you to specify which columns to retrieve, and it also provides options to retrieve unique or all rows. In this article, we have covered the basics of the SELECT statement and how to use it effectively. Stay tuned for more articles to expand your SQL knowledge and skills.

Leave a Reply

Your email address will not be published. Required fields are marked *