PostgreSQL – WHERE Clause

The WHERE clause is used in a SELECT statement to filter rows from a table based on a specified condition. It allows you to retrieve only the rows that meet the specified criteria.

The basic syntax of using the WHERE clause is as follows:

SELECT column1, column2, ... FROM table_name WHERE condition;

Here’s a breakdown of the different parts of the WHERE clause:

  • column1, column2, ...: The columns you want to retrieve data from.
  • table_name: The name of the table from which you want to retrieve data.
  • condition: The condition that specifies the filtering criteria for the rows you want to retrieve. It’s typically a combination of column comparisons and logical operators.

For example, let’s say you have a table named employees with columns employee_id, first_name, last_name, and salary. You might write a SELECT statement with a WHERE clause to retrieve only the employees whose salary is greater than a certain value:

SELECT first_name, last_name, salary FROM employees WHERE salary > 50000;

You can use various comparison operators (=, >, <, >=, <=, <>, !=) along with logical operators (AND, OR, NOT) to create complex conditions. Parentheses can be used to group conditions.

Here’s an example with multiple conditions:

SELECT first_name, last_name, salary FROM employees WHERE department_id = 2 AND salary > 50000;

In this query, we’re retrieving the first name, last name, and salary of employees from department 2 whose salary is greater than 50000.

The WHERE clause is essential for querying specific subsets of data from a table and is a fundamental part of SQL queries.

Similar Posts