Select query
The SELECT
statement is one of the most important and frequently used SQL commands. It allows you to retrieve data from a database. This tutorial will guide you through the process of using the SELECT
statement in PostgreSQL.
Basic SELECT Statement
Let's start with the basic syntax of the SELECT
statement:
SELECT column1, column2, ..., columnN
FROM table_name;
In this query, column1, column2, ..., columnN
are the names of the columns you want to select from the table. If you want to select all columns, you can use the *
symbol in place of the column names:
SELECT *
FROM table_name;
The WHERE Clause
The WHERE
clause is used to filter records. It only includes records where the condition is true.
SELECT column1, column2, ..., columnN
FROM table_name
WHERE condition;
For instance, if you have a users
table and you want to select all users who live in 'New York', you can do it like this:
SELECT *
FROM users
WHERE city = 'New York';
The DISTINCT Keyword
The DISTINCT
keyword is used to return only distinct (unique) values. The following SQL statement selects only the distinct values from the "city" columns from the "users" table:
SELECT DISTINCT city
FROM users;
The ORDER BY Keyword
The ORDER BY
keyword is used to sort the result-set in ascending or descending order. The ORDER BY
keyword sorts the records in ascending order by default. If you want to sort the records in descending order, you can use the DESC
keyword.
SELECT column1, column2, ..., columnN
FROM table_name
ORDER BY column1 DESC, column2 ASC;
The LIMIT Keyword
The LIMIT
keyword is used to limit the number of records returned. The following SQL statement selects the first five records from the "users" table:
SELECT *
FROM users
LIMIT 5;
The Aggregate Functions
SQL also supports the use of aggregate functions to perform calculations on a set of values and return a single value. The most commonly used aggregate functions are COUNT()
, SUM()
, MIN()
, MAX()
, and AVG()
.
Here's how to use the COUNT()
function to count the number of users in the users
table:
SELECT COUNT(*)
FROM users;
In conclusion, the SELECT
statement is a powerful tool in SQL that allows you to retrieve the data you need from your database. With the addition of clauses like WHERE
, ORDER BY
and LIMIT
, along with aggregate functions, you can perform complex queries and data analysis. Remember to practice using these commands and functions to become more familiar and comfortable with SQL querying.