Basic SQL Queries in PostgreSQL
1. Introduction
Structured Query Language (SQL) is the standard language for managing and manipulating databases. PostgreSQL is a powerful, open-source object-relational database system that uses SQL. This lesson covers basic SQL queries to interact with PostgreSQL databases.
2. Basic SELECT Queries
The SELECT
statement is used to select data from a database. The data returned is stored in a result table, sometimes called the result set.
SELECT column1, column2 FROM table_name;
To select all columns:
SELECT * FROM table_name;
3. Filtering Data
WHERE
clause to filter records.
SELECT column1, column2 FROM table_name WHERE condition;
Example:
SELECT * FROM employees WHERE department = 'Sales';
4. Aggregating Data
SQL provides aggregate functions to perform calculations on multiple rows of data. Common aggregate functions include:
- COUNT()
- SUM()
- AVG()
- MIN()
- MAX()
Example of using COUNT()
:
SELECT COUNT(*) FROM employees WHERE department = 'Sales';
5. Joining Tables
Joining tables allows you to combine rows from two or more tables based on a related column. The most common types of joins are:
- INNER JOIN
- LEFT JOIN
- RIGHT JOIN
- FULL OUTER JOIN
Example of an INNER JOIN:
SELECT employees.name, departments.name
FROM employees
INNER JOIN departments ON employees.department_id = departments.id;
6. Best Practices
When writing SQL queries, consider the following best practices:
- Use meaningful aliases for columns and tables.
- Always specify the columns you need instead of using
*
. - Be cautious with NULL values.
- Use comments to document complex queries.
7. FAQ
What is the difference between INNER JOIN and LEFT JOIN?
INNER JOIN returns only the rows that have matching values in both tables, while LEFT JOIN returns all rows from the left table, and the matched rows from the right table. If there is no match, NULL values will be returned for columns from the right table.
Can I use multiple conditions in a WHERE clause?
Yes, you can use multiple conditions combined with AND
and OR
. For example: WHERE condition1 AND condition2
.
What is the purpose of the GROUP BY clause?
The GROUP BY
clause is used to arrange identical data into groups. This is often used with aggregate functions to summarize data.