티스토리 뷰

TIL

[SQL] 기본 명령어 예시

빙빙 2021. 3. 25. 23:54

-- 데이터조회 : SELECT 컬럼명 FROM 테이블명;

SELECT * FROM examples;

--DDL(데이터 정의어)

--테이블 생성

CREATE TABLE classmates (

id INTEGER PRIMARY KEY,

name TEXT,

age INT,

address TEXT

);

--테이블 삭제

DROP TABLE classmates;

 

--ALTER

--테이블명 변경

ALTER TABLE articles RENAME TO news;

 

--컬럼 추가(NOT NULL 제약조건 처리 필요)

ALTER TABLE news

ADD COLUMN created_at TEXT;

ALTER TABLE news

ADD COLUMN created_at TEXT NOT NULL DEFAULT 1;

 

--DML(데이터 조작어)

--데이터 추가 (테이블옆에 컬럼 안쓰면 전체 컬럼에 다 들어가는 것)

INSERT INTO classmates

VALUES('홍길동',30,'서울')

--프라이머리 키를 지정하지 않으면 rowid가 생성된다

SELECT rowid, * FROM classmates;

--프라이머리 키를 쓰는것보다 rowid를 사용하는 것이 편하다.

 

--limit :몇개 가지고 올것인지

select rowid ,name from classmates limit 1;

--limit &&offset :특정한 위치부터 몇개 가지고 올건지

select rowid ,name from classmates limit 1 offset 3;

 

--where :조건

select rowid, name

from classmates

where address='서울';

 

--distinct : 중복없이

select distinct address classmates;

 

--delete:데이터 삭제 ,기본적으로 rowid(PK)기준으로 삭제한다

delete from classmates

where rowid= 2;

--

select *

from users

where age >= 30;

---

select first_name

...> from users

...> where age >= 30;

---

select age,last_name

from users

where age >= 30 and last_name='김';

---표현식

--카운트

select count(*) from users;

 

--평균

select avg(age) from users where age >= 30;

--max

select first_name,max(balance) from users;

--like

--20대인사람 찾기

select * from users where age like '2_';

--지역번호가 02인 사람 찾기

select * from users where phone like '02-%';

--order

SELECT * from users order by age asc limit 10;

 

--10개만 잔액 내림차순

SELETE last_name,first_name FROM users ORDER BY balance DESC LIMIT 10;

 

--그룹화, 그룹 이름도 지어주기

SELECT last_name, COUNT(*) AS name_count FROM users GROUP BY last_name;

'TIL' 카테고리의 다른 글

[알고리즘] 트리  (2) 2021.04.05
[GIT] branch  (0) 2021.03.26
[Git] Push error해결법  (0) 2021.03.13
[자료구조] Queue 큐  (0) 2021.03.03
백 트레킹 알고리즘, 분할정복 알고리즘, 퀵정렬  (0) 2021.02.24
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함