SQL Basics & PostgreSQL

Let's run some SQL together!

Refer to this repo for the complete code.

PostgreSQL Setup

Installation

PostgreSQL Download Package Installer(EDB)

Selecting components

In case you still forget to select pgAdmin, you can always downloaded it separately here

Database Connection

When you open up pgAdmin, click on Servers, there should already be a default Server PostgreSQL <version>, with a postgres database in it. In case you don't, we can also create a new server and database with the following steps:

create server
create database

After you are connected to the database, you can open the query tool and run your SQL queries there.

CRUD

Create Table

Insert

Update

Delete

Drop

Simple Queries

Algebraic Queries

Inner Join

Left Outer Join

Here is an excellent article explaining the different join concepts, do give it a read!

OUTER JOINS are joins that return matched values and unmatched values from either or both tables. In the case of left outer join, we return matched values and unmatched values from the table to the left of the JOIN keyword.

Set Operators

UNION, INTERSECT, EXCEPT

They eliminate duplicates unless annotated with the keyword ALL.

To use the set operators on two tables, they must satisfy the condition:

  • The two queries must be union-compatible.

  • They must return the same number of columns with the same domains in the same order.

Aggregate Queries

COUNT, MAX, MIN, AVG, SUM, STDDEV, ...

Group By, Having

  • GROUP BY creates groups of records that have the same values for the specified fields before computing the aggregate functions. Without a clause, only one group is formed implicitly by SQL as soon as an aggregate function is called.

    • Aggregate functions cannot appear before GROUP BY(in WHERE), hence we have HAVING.

  • HAVING adds conditions to be checked after the evaluation of the GROUP BY clause. It only involves aggregate functions, columns listed in the GROUP BY clause and subqueries.

  • Attributes in the SELECT clause must appear in the GROUP BY clause, unless it is used in an aggregate function.

A slightly complicated query:

Try to figure out what it does!

Nested Queries

Nest a subquery in a query.

  • Subqueries can be used only in FROM clause or WHERE clause

  • Comparison to a subquery should always use the quantifier ALL or ANY

Many ways to do the same thing. Just for illustration.

Last updated