Published on

Sql Notları

Authors
  • avatar
    Name
    Orkun Gunay
    Twitter

Asagidaki notlari w3schools sql tutorial sayfasinda calisirken tuttum. Sitedeki northwind sample database'i bu repo'dan mysql'e import edip calistim.

Some of The Most Important SQL Commands

  • SELECT - extracts data from a database. mantiksal isleme sirasi;
    • FROM
    • ON
    • JOIN
    • WHERE
    • GROUP BY
    • WITH CUBE or WITH ROLLUP
    • HAVING
    • SELECT
    • DISTINCT
    • ORDER BY
    • TOP

HAVING - Gruplanan ya da hesaplanan alanlarin sinirlanmasi icin kullanilan bir kisimdir. WHERE kismi ile karistirilmamasi gerekir.

UPDATE          # updates data in a database
DELETE          # deletes data from a database
INSERT INTO     # inserts new data into a database
CREATE DATABASE # creates a new database
ALTER DATABASE  # modifies a database
CREATE TABLE    # creates a new table
ALTER TABLE     # modifies a table
DROP TABLE      # deletes a table
CREATE INDEX    # creates an index (search key)
DROP INDEX      # deletes an index

Operators in the WHERE Clouse

= eual > greater than < less than >= greater than or equal <= less than or equal <> not equal. (some versions of SQL may be !=) BETWEEN between a certain range LIKE search for a pattern IN to specify multiple possible values for a column ORDER BY several columns example; customers tablosundan country'e ve customername'e göre ORDER BY yaptığımızda, country'e göre sıralama, aynı country'dekileri ise customername'e göre sıralamak için kullanılır. The customerid column is an auto-increment field and will be generated automatically when a new record is inserted into the table update syntax'ini kullanırken dikkat edilmesi gereken, asla ve asla where clause'un unutulmaması, eğer unutursan bütün tabloyu update edersin... The following SQL statement selects all customers that are from the same countries as the suppliers:

SELECT * FROM Customers
WHERE Country IN (SELECT Country FROM Suppliers);
  • sutunda birden cok data'yi cekmek icin where clause'da IN kullanılır.
select
    *
from
    tablo_adi
where
    sutun_adi IN (
        'deger_1',
        'deger_2',
    );
  • Time'a göre sorguda hata alınırsa (string, float, integer birarda olduğunda) dönüştürülüp sorgulanabilir;
select
    *
from
    tablo_adi
where
     TO_CHAR(insert_time, 'DD-MM-YYYY') = '25-02-2021';

set define off insert ve update öncesi kullanılıyor. scriptteki bazı karakterlerlere kızıyorsa (& gibi) bu komut kullanılabilir.

  • tabloda update ornegi;
UPDATE
    tablo_adi
SET
    key = value,
    END_DATE = TO_DATE('31-MAR-21 23:59:59', 'DD/MM/YYYY HH24:MI:SS')
WHERE
    sutun_adi = 'string';
COMMIT;
  • NOT IN çalışma
CREATE TABLE sales (
    customer_id NUMBER,
    product_id NUMBER,
    order_date DATE NOT NULL,
    total NUMBER(9, 2) DEFAULT 0 NOT NULL,
    PRIMARY KEY(
        customer_id,
        product_id,
        order_date
    )
);

INSERT INTO
    sales(customer_id, product_id, order_date, total)
VALUES
(1, 2, CURRENT_DATE, 10);

INSERT INTO
    sales(customer_id, product_id, order_date, total)
VALUES
(2, 2, DATE '2017-05-01', 9);

CREATE TABLE discounts (
    discount_id NUMBER GENERATED BY DEFAULT AS IDENTITY,
    discount_name VARCHAR2(255) NOT NULL,
    amount NUMBER(3, 1) NOT NULL,
    start_date DATE NOT NULL,
    expired_date DATE NOT NULL
);

INSERT INTO
    discounts(discount_name, amount, start_date, expired_date)
VALUES
(
        'Summer Promotion',
        9.5,
        DATE '2017-05-01',
        DATE '2017-08-31'
    );

INSERT INTO
    discounts(discount_name, amount, start_date, expired_date)
VALUES
(
        'Winter Promotion 2017',
        10.5,
        CURRENT_DATE,
        DATE '2017-12-31'
    );

ALTER TABLE
    sales RENAME COLUMN total TO amount;

update
    discounts
set
    amount = 10
where
    discount_name = 'Summer Promotion';

select * from sales;
select * from discounts;

select
    discount_name
from
    discounts
where
    amount not in (
        select
            amount
        from
            sales
        where
            customer_id = 1
    );
  • select sorgusu tablodaki her value2 değerine göre curl komutunu satır olarak başar
select
    distinct 'curl --location --request POST ''http://adres'' \
    --header ''Content-Type: text/plain'' \
    --data ''{
    "key": "value",
    "key2": "' || value2 || '" } '''
from tablo_adi
where key='value';
  • select çıktısının arasına kendi yazacağını ekleme, örneğin bir shell script'in adını.
select distinct
    'sh dosya.sh <parametre> ' || to_char (transaction_date, 'YYYY-MM-DD') || ' >>/tmp/dosya.txt'
from
    tablo_adi
where
    kosul='';

ornek cikti:

sh findsms.sh <parametre> 2018-02-26 >>/tmp/dosya.txt
sh findsms.sh <parametre> 2018-03-04 >>/tmp/dosya.txt
sh findsms.sh <parametre> 2018-03-01 >>/tmp/dosya.txt
  • tablo join'leyerek data cekme
select * from tablo_1 as 1, tablo_2 as 2
where 1.kolon_1=2.kolon_1
and 2.kolon_2 in (
...
);

2 tablonun birbirine JOIN komutu ile bağlanmasında INNER, OUTER, CROSS olmak üzere 3 farklı seçenek bulunmaktadır.

  • INNER: her 2 tablonun da eşleşen alanlarının seçilmesi sağlanır. (Kesişim kümesi)
  • OUTER:

Tabloların birbirine bağlanması ilişkili alanın eşlenerek bağlanan tabloda karşılığının aranması için kullanılır. Veri birleştirme ise, birbiri ile aynı sayıda ve türde alanları olan veri kümelerinin alt alta birleştirilmesi, kesişim kümelerinin ve farklarının bulunması işlemidir.

[//]: # Regex on PL/SQL