15 Eylül 2022 Perşembe

SQL DISTINCT

Giriş
Açıklaması şöyle
- SQL Distinct statement returns distinct values for a given column.
- SQL Distinct returns distinct combination of columns when used with multiple columns.
Örnek
Şeklen şöyle. Burada DISTINCT iki tane sütunla kullanıldığı için bunların kombinasyonunu aldığı görülebilir.

Örnek
Elimizde şöyle bir tablo olsun
Emp_id Dept_id Job_id
1      24      117
2      24      117
3      24      118
4      25      117
Bu tabloyu şöyle sorgulayalım
SELECT Dept_id, Job_id FROM Employees
Şu sonucu alırız.
24 117
24 117
24 118
25 117
24 ile başlayan satırların çift olduğu görülebilir. Bunlardan kurtulmak için şöyle yaparız.
SELECT DISTINCT Dept_id, Job_id FROM Employees
Bu durumda şu sonucu alırız.
24 117
24 118
25 117


9 Eylül 2022 Cuma

INNER JOIN USING

Giriş
Açıklaması şöyle
The USING clause works for Oracle, PostgreSQL, MySQL, and MariaDB. SQL Server doesn’t support the USING clause, so you need to use the ON clause instead.
Örnek
Şöyle yaparız
SELECT * FROM post
INNER JOIN post_comment USING(post_id)
ORDER BY post_id, post_comment_id
Çıktısı şöyle
| post_id | title     | post_comment_id | review    |
|---------|-----------|-----------------|-----------|
| 1       | Java      | 1               | Good      |
| 1       | Java      | 2               | Excellent |
| 2       | Hibernate | 3               | Awesome   |
Eğer INNER JOIN ON kullansaydık şöyle yaparız
SELECT * FROM post
  INNER JOIN post_comment ON post.post_id = post_comment.post_id
  ORDER BY post.post_id, post_comment_id
Çıktısı şöyle. İki tane post_id sütunu geldi. Birisi pos tablosundan, diğeri de post_comment tablosundan
| post_id | title     | post_comment_id | review    | post_id |
|---------|-----------|-----------------|-----------|---------|
| 1       | Java      | 1               | Good      | 1       |
| 1       | Java      | 2               | Excellent | 1       |
| 2       | Hibernate | 3               | Awesome   | 2       |



SQL EXISTS ve NOT EXISTS

Giriş
EXIST (subquery) şeklinde kullanılır.
EXIST yerine COUNT(*) kullanılması çok verimsiz.

Örnek
Şu kod yanlış
SELECT COUNT(*) FROM actor a
JOIN film_actor fa USING (actor_id) WHERE a.last_name = 'WAHLBERG'
Doğrusu şöyle
SELECT EXISTS (
  SELECT * FROM actor a
  JOIN film_actor fa USING (actor_id)
  WHERE a.last_name = 'WAHLBERG'
)
Örnek
Şöyle yaparız. Burada student tablosu üzerinde yürünüyor. Her öğrencinin başka derslere ait bir sürü notu daha student_grade tablosunda var. EXIST kullandığımız için bir öğrencinin tüm notlarını dolaşırken eğer ders ismi Math ve notu 10 ise EXISTS hemen TRUE döner ve öğrenci için çalışan döngüden çıkarız. Dolayısıyla daha hızlı
SELECT id, first_name, last_name
FROM student
WHERE EXISTS (
    SELECT 1
    FROM student_grade
    WHERE
        student_grade.student_id = student.id AND
        student_grade.grade = 10 AND
        student_grade.class_name = 'Math'
)
ORDER BY id

SELECT id, first_name, last_name
FROM student
WHERE NOT EXSITS (
    SELECT 1
    FROM student_grade
    WHERE
        student_grade.student_id = student.id AND
        student_grade.grade < 9
)
ORDER BY id
Örnek
Şöyle yaparız. Burada student tablosu üzerinde yürünüyor. Her öğrencinin başka derslere ait bir sürü notu daha student_grade tablosunda var. NOT EXIST kullandığımız için bir öğrencinin tüm notlarını dolaşırken eğer ders ismi Math ve notu 9'dan az ise NOT EXISTS hemen FALSE döner ve öğrenci için çalışan döngüden çıkarız. Dolayısıyla daha hızlı
SELECT id, first_name, last_name
FROM student
WHERE NOT EXSITS (
    SELECT 1
    FROM student_grade
    WHERE
        student_grade.student_id = student.id AND
        student_grade.grade < 9
)
ORDER BY id

5 Temmuz 2022 Salı

PostGIS ST_MaximumInscribedCircle

Giriş
Açıklaması şöyle. 3 çıktısı olan bir sonuç döner. Bunlar radius, center ve center'a en yakın nokta
Finds the largest circle that is fully contained within a geometry. Returns a record with the center point of the circle, a point on the geometry that is nearest to the center, and the radius of the circle.
Örnek
Şöyle yaparız
SELECT
  mic.radius,
  mic.center,   --already a GEOMETRY(POINT) type
  mic.nearest   --already a GEOMETRY(POINT) type
FROM
  <table> AS t,
  LATERAL ST_MaximumInscribedCircle(t.geom) AS mic
;

17 Haziran 2022 Cuma

patronictl komutu - Patroni Replication Monitoring İçindir

Giriş
Açıklaması şöyle
Patroni provide all functionality to setup, monitor and fix the replica DB using reinit command.


Zalando Operator ile kullanılıyor

patronictl komutu

list seçeneği
Örnek
Şöyle yaparız
$ kubectl exec -it rlwy-postgres-1 -n rlwy02-pgo -- /bin/bash
Defaulted container "postgres" out of: postgres, exporter

 ____        _ _
/ ___| _ __ (_) | ___
\___ \| '_ \| | |/ _ \
 ___) | |_) | | | (_) |
|____/| .__/|_|_|\___/
      |_|

This container is managed by runit, when stopping/starting services use sv

Examples:

sv stop cron
sv restart patroni

Current status: (sv status /etc/service/*)

root@rlwy-postgres-1:/home/postgres# patronictl list
2022-06-17 07:10:35,333 - WARNING - Listing members: No cluster names were provided

16 Haziran 2022 Perşembe

9 Haziran 2022 Perşembe

Sütun Tipleri - IDENTITY (Otomatik Sayı Üretir)

Giriş
Açıklaması şöyle
It is recommended to use IDENTITY instead since SERIAL has some weird behaviors.
Bu sütunlara NOT NULL + PRIMARY KEY + UNIQUE gibi özellikler de atanabilir.

Örnek
Şöyle yaparız
CREATE TABLE IF NOT EXISTS entity (
    id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    ...
)

# To see the sequence
SELECT * FROM pg_sequence WHERE seqrelid = 'entity_id_seq'::regclass;
IDENTITY Kullanımının Bazı Dezavantajları
Not : Bazıları IDENTITY yerine UUID kullanılması öneriyor. 
1. İki tane tablonun birleştirilmesinde problem oluyor. Bir açıklama şöyle
I’ve seen this over and over for the last 30 years, people let the database set the ID or Primary Key of a table from the database, at first glance this sounds simple and everyone knows you should let the database do the heavy lifting, with a numeric “Sequence” number you need to let the database do the work since there may be multiple applications or threads creating new records in the table. DON”T DO IT!

First, if and when you need to merge two databases that now have the same Primary Key ID values for the same table, your screwed. You have to come up with a scheme to change the ID’s, maybe adding 10,000 to each ID, what if you have more than 10,000 rows? The you also have to update all children records, maybe not that easy if you have constraints defined in the database.
2. Güvenlik Açıkları
Eğer bir Primary Key değerinin 100 olduğunu biliyorsam bir sonrakinin de 101 olacağını biliyorum. Bunu sorgulayarak bir güvenlik açığından faydalanabilirim.