DEV Community

badruti94
badruti94

Posted on

Catatan Belajar SQL

So this is what I note from learning SQL

# Sample DB PostgreSQL
This is sample DB that I download from Google
here is the link and here is the ERD Diagram

Image description

IN
The IN operator allows you to specify multiple values in a WHERE clause.
Example :

SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');
Enter fullscreen mode Exit fullscreen mode

BETWEEN
The BETWEEN operator selects values within a given range. The values can be numbers, text, or dates.
Example :

SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;
Enter fullscreen mode Exit fullscreen mode

UNION
The following SQL statement returns the cities (only distinct values) from both the "Customers" and the "Suppliers" table
Example :

SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;
Enter fullscreen mode Exit fullscreen mode

HAVING
The HAVING clause was added to SQL because the WHERE keyword cannot be used with aggregate functions.
Example :

SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;
Enter fullscreen mode Exit fullscreen mode

CASE
The CASE expression goes through conditions and returns a value when the first condition is met (like an if-then-else statement). So, once a condition is true, it will stop reading and return the result. If no conditions are true, it returns the value in the ELSE clause.

Example :

SELECT OrderID, Quantity,
CASE
    WHEN Quantity > 30 THEN 'The quantity is greater than 30'
    WHEN Quantity = 30 THEN 'The quantity is 30'
    ELSE 'The quantity is under 30'
END AS QuantityText
FROM OrderDetails;

Enter fullscreen mode Exit fullscreen mode

NOT NULL
It is not possible to test for NULL values with comparison operators, such as =, <, or <>.

We will have to use the IS NULL and IS NOT NULL operators instead.

Example :

--is null
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NULL;

--is not null
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NOT NULL;
Enter fullscreen mode Exit fullscreen mode

EXTRACT (FOR DATE)

We use EXTRACT function in PostgreSQL to get YEAR or MONTH from date type

Example ::

select
date_part('YEAR', last_update) as year, date_part('MONTH', last_update) as month   
from film f ;
Enter fullscreen mode Exit fullscreen mode

Reference:
https://www.postgresqltutorial.com/postgresql-date-functions/postgresql-date_part/

Source:
w3shoools

Top comments (0)