SQL과 Django ORM의 관계를 알면 좋은점
- SQL문을 직접 비교하면서 학습하시게 되면 django와 같은 프레임워크를 사용하지 않아도 다른 웹 프레임워크를 사용해서도 주로 같이 사용되는 ORM을 사용하지 않고 직접 SQL을 사용하여 유연하게 구현할 수 있는 장점이 있습니다.
- django ORM으로 코드를 작성할때, SQL문을 한번 더 고려할 수 있기 때문에 추후에 성능 분석할 때 실제 django가 수행하는 SQL을 프로파일링 할 수 있는 장점이 있습니다.
Database MySQL
DDL (Data Define Language)
- 데이터베이스의 Schema(형태)를 정의할 수 있는 쿼리문을 의미합니다.
CREATE, ALTER, DROP
이 대표적인 쿼리문 입니다.
- 데이터를 구성하는 논리적인 구조(데이터베이스 또는 테이블)을 추가하고 수정하고 삭제할 수 있습니다.
메타데이터
(데이터에 대한 데이터)를 다루는 쿼리문이라고 할 수 있습니다.
CREATE DATABASE
CREATE DATABASE my_favourite_artists;
SHOW DATABASES;
USE my_favourite_artists;
SHOW tables;
CREATE TABLE artists
(
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
PRIMARY KEY (id)
);
DESC artists;
CREATE TABLE songs
(
id INT NOT NULL AUTO_INCREMENT,
title VARCHAR(100) NOT NULL,
lyrics VARCHAR(2000),
artist_id INT,
PRIMARY KEY (id),
FOREIGN KEY (artist_id) REFERENCES artists (id)
);
DESC songs;
DML (Data Manipulation Language)
- 데이터를 조작하는 쿼리문들을 뜻합니다.
INSERT, UPDATE, DELETE
가 대표적인 쿼리문 입니다.
INSERT INTO table
INSERT INTO artists (name) VALUES ('Radio Head');
INSERT INTO artists (name) VALUES ('Pink Floid');
INSERT INTO artists (name) VALUES ('새소년');
SELECT * FROM artists;
UPDATE table SET column
UPDATE artists SET name='Pink Floyd' WHERE id=2;
SELECT * FROM artists;
DELETE FROM table
DELETE FROM artists WHERE name='새소년';
SELECT * FROM artists;
DQL (Data Query Language)
- 데이터를 쿼리하는데 사용되는 SQL문을 뜻합니다.
- 데이터베이스 서버에게 데이터를 달라고 요청합니다.
SELECT
가 대표적인 쿼리문입니다.
SELECT
SELECT * FROM artists;
SELECT * FROM songs;
SELECT songs.title FROM songs;
SELECT songs.title, songs.lyrics FROM songs;
WHERE 조건문
SELECT songs.lyrics FROM songs WHERE songs.title = '파도';
WHERE + LIKE 조건문
SELECT songs.title, songs.lyrics FROM songs WHERE songs.lyrics LIKE '%넘실넘실%';
SELECT songs.title, songs.lyrics FROM songs WHERE songs.title LIKE 'All%';
SELECT songs.title, songs.lyrics FROM songs WHERE songs.lyrics LIKE '%가져가도 돼요';
JOIN
- 연관성이 있는 두 개의 테이블을 결합시킬 수 있습니다.
SELECT artists.name, songs.title, songs.lyrics
FROM artists
JOIN songs
ON artists.id = songs.artist_id;
JOIN + WHERE + LIKE 조건문
SELECT artists.id, artists.name, songs.title
FROM artists
JOIN songs
ON artists.id = songs.artist_id
WHERE artists.name = '새소년';
SELECT artists.id, artists.name, songs.title
FROM artists
JOIN songs
ON artists.id = songs.artist_id
WHERE songs.lyrics LIKE '%you%';
SELECT artists.id, artists.name, songs.title
FROM artists
JOIN songs
ON artists.id = songs.artist_id
WHERE songs.lyrics LIKE '%you%' OR songs.lyrics LIKE '%i%';
DCL (Data Control Language)
- 데이터를 제어하는 쿼리문들을 뜻합니다.
- 데이터의 보안, 무결성, 회복, 병행 수행제어 등을 정의하는데 사용합니다.
- TCL을 포함한다.
GRANT, REVOKE
이 대표적인 쿼리문 입니다.
TCL (Transaction Control Language)
- 데이터의 일관성을 유지하면서 안정적으로 데이터를 복구시키기 위해서 사용합니다.
COMMIT, ROLLBACK, SAVEPOINT, SET TRANSACTION
Django ORM과 SQL관계 Cheatsheet
1-1. SELECT
SELECT * FROM Person;
persons = Person.objects.all()
for person in persons:
print(person.name)
print(person.gender)
print(person.age)
SELECT name, age FROM Person;
Person.objects.only('name', 'age')
SELECT DISTINCT name, age FROM Person;
Person.objects.values('name', 'age').distinct()
- Fetch specific number of rows
SELECT * FROM Person LIMIT 10;
Person.objects.all()[:10]
- LIMIT AND OFFSET keywords
- 원하는 행의 수 만큼을 건너뛰고 그 이후의 행부터 검색이 가능하다.
SELECT * FROM Person OFFSET 5 LIMIT 5;
Person.objects.all()[5:10]
1-2. WHERE Clause
SELECT * FROM Person WHERE id = 1;
Person.objects.filter(id=1)
- Filter by comparison operators
WHERE age > 18;
WHERE age >= 18;
WHERE age < 18;
WHERE age <= 18;
WHERE age != 18;
Person.objects.filter(age__gt=18)
Person.objects.filter(age__gte=18)
Person.objects.filter(age__lt=18)
Person.objects.filter(age__lte=18)
Person.objects.exclude(age=18)
SELECT * FROM Person WHERE age BETWEEN 10 AND 20;
Person.objects.filter(age__range=(10, 20))
WHERE name like '%A%';
WHERE name like binary '%A%';
WHERE name like 'A%';
WHERE name like binary 'A%';
WHERE name like '%A';
WHERE name like binary '%A';
Person.objects.filter(name__icontains='A')
Person.objects.filter(name__contains='A')
Person.objects.filter(name__istartswith='A')
Person.objects.filter(name__startswith='A')
Person.objects.filter(name__iendswith='A')
Person.objects.filter(name__endswith='A')
WHERE id in (1, 2);
Person.objects.filter(id__in=[1, 2])
- AND, OR and NOT Operators
WHERE gender='male' AND age > 25;
Person.objects.filter(gender='male', age__gt=25)
WHERE gender='male' OR age > 25;
from django.db.models import Q
Person.objects.filter(Q(gender='male') | Q(age__gt=25))
Person.objects.filter(Q(gender='male') & Q(age__gt=25))
Person.objects.filter(Q(gender='male') & ~Q(age__gt=25))
WHERE NOT gender='male';
Person.objects.exclude(gender='male')
WHERE age is NULL;
WHERE age is NOT NULL;
Person.objects.filter(age__isnull=True)
Person.objects.filter(age__isnull=False)
Person.objects.filter(age=None)
Person.objects.exclude(age=None)
1-3. ORDER BY Keyword
SELECT * FROM Person order by age;
Person.objects.order_by('age')
SELECT * FROM Person ORDER BY age DESC;
Person.objects.order_by('-age')
INSERT INTO Person VALUES ('Jack', '23', 'male');
Person.objects.create(name='jack', age=23, gender='male)
1-4. UPDATE Statement
UPDATE Person SET age = 20 WHERE id = 1;
person = Person.objects.get(id=1)
person.age = 20
person.save()
UPDATE Person SET age = age * 1.5;
from django.db.models import F
Person.objects.update(age=F('age')*1.5)
1-5. DELETE Statement
DELETE FROM Person;
Person.objects.all().delete()
DELETE FROM Person WHERE age < 10;
Person.objects.filter(age__lt=10).delete()
1-6. Aggregation (집합)
SELECT MIN(age) FROM Person;
from django.db.models import Min
Person.objects.all().aggregate(Min('age'))
{'age__min': 0}
SELECT MAX(age) FROM Person;
>>> from django.db.models import Max
>>> Person.objects.all().aggregate(Max('age'))
{'age__max': 100}
SELECT AVG(age) FROM Person;
>>> from django.db.models import Avg
>>> Person.objects.all().aggregate(Avg('age'))
{'age__avg': 50}
SELECT SUM(age) FROM Person;
>>> from django.db.models import Sum
>>> Person.objects.all().aggregate(Sum('age'))
{'age__sum': 5050}
SELECT COUNT(*) FROM Person;
Person.objects.count()
1-7. GROUP BY Statement
- Count of Person by gender
SELECT gender, COUNT(*) as count FROM Person GROUP BY gender;
Person.objects.values('gender').annotate(count=Count('gender'))
1-8. HAVING Clause
- Count of Person by gender if number of person is greater than 1
SELECT gender, COUNT('gender') as count FROM Person GROUP BY gender HAVING count > 1;
Person.objects.annotate(count=Count('gender'))
.values('gender', 'count')
.filter(count__gt=1)
1-9. JOINS
- Consider a foreign key relationship between books and publisher.
class Publisher(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)
- Fetch publisher name for a book
SELECT name
FROM Book
LEFT JOIN Publisher
ON Book.publisher_id = Publisher.id
WHERE Book.id=1;
book = Book.objects.select_related('publisher').get(id=1)
book.publisher.name
- Fetch books which have specific publisher
SELECT *
FROM Book
WHERE Book.publisher_id = 1;
publisher = Publisher.objects.prefetch_related('book_set').get(id=1)
books = publisher.book_set.all()