sungyup's.

PostgreSQL / Intro / 1.1 Intro

1.1Intro

Intro

SQLDatabase들과 상호작용하기 위한 언어이다. Postgres는 이 데이터베이스의 일종으로, PostgreSQL은 Postgres와 상호작용하기 위한 언어이다.

Postgres 학습의 목적은 다음과 같다.

  • Writing efficient queries to retrieve information
  • Designing the schema, or structure of the database
  • Understanding when to use advanced features
  • Managing the database in a production environment (백업 / 스케일링 등)

Database Design

ex) largest cities in the world라는 db가 있으면,

  • what kind of thing : cities
    • ⇒ 테이블 명을 ‘cities’로 지어야지
  • what properties : name, country, population, area
    • ⇒ name, country, …라는 columns을 만들어야지
  • type of data : name-string, country-stirng, population-number, area-number, …
    • ⇒ 각 column들에 타입들 지정해야지
sql
CREATE TABLE cities ( name VARCHAR(50), country VARCHAR(50), population INTEGER, area INTEGER );
  • Keyword : db에 뭔가를 하고 싶다고 말하는 구문들, 언제나 대문자로 씀
  • Identifiers : db에 어떤걸 다루고 있는지 말하는 구문들, 언제나 소문자로 씀
  • VARCHAR : Variable length character
  • INTEGER : 정수(약 -20억 ~ 20억)

Inserting Data

sql
INSERT INTO cities (name, country, population, area) VALUES ('Tokyo', 'Japan', 38505000, 8223);

복수 데이터는 아래와 같이

sql
INSERT INTO cities (name, country, population, area) VALUES ('Delhi', 'India', 28125000, 2240), ('Shanghai','China', 22125000, 4015), ('Sao Paulo', 'Brazi', 20935000, 3043);

Retrieving Data

sql
SELECT * FROM cities

Calculated Columns

데이터베이스에서 조회할 때 값을 계산하여 조회 가능

sql
SELECT name, population / area FROM cities;
  • +, -, *, / 뿐 아니라 ^(거듭제곱), |/(Square root), @(절댓값), %(나머지)도 쓸 수 있음
sql
SELECT name, population/area AS population_density FROM cities;

위와 같은 방식으로 column에 이름을 붙일 수도 있음

String Operators and Functions

  • || : join two strings
  • CONCAT : join two strings
sql
SELECT name || ', ' || country AS location FROM cities; // 또는, SELECT CONCAT(name, ', ', country) AS location FROM cities;
  • LENGTH() : number of characters in a string
  • LOWER() : lower case string
  • UPPER() : upper case string
PreviousNo previous post