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)
Please select at least PostgreSQL Server and pgAdmin for installation!

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:


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
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 BYcreates 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(inWHERE), hence we haveHAVING.
HAVINGadds conditions to be checked after the evaluation of theGROUP BYclause. It only involves aggregate functions, columns listed in theGROUP BYclause and subqueries.Attributes in the
SELECTclause must appear in theGROUP BYclause, 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
FROMclause orWHEREclauseComparison to a subquery should always use the quantifier
ALLorANY
Many ways to do the same thing. Just for illustration.
Last updated