Database 공통

1. Database 공통

1. Database 란

  • 여러 사람이 공동으로 공유하여 사용할 목적으로, 통합하여 관리되는 저장된 형태의 데이터의 집합.
  • 자료 항목의 중복을 없애고 자료를 구조화하여 저장함으로써 자료 검색과 갱신등 운영의 효율을 높인 데이터의 집합.
  • 우리가 일상에 사용하는 모든 것들이 데이터베이스를 통해 열람하고, 사용하고, 생산하고, 수정하고, 삭제하게 된다. ex) 게시판글 작성, 카톡채팅, 게임접속, 은행거래, 웹사이트 열람...
구글 면접 질문
질문) “8세짜리 조카에게 데이터베이스(database)가 무엇인지 3문장 이내로 설명해 보세요.”

모범답안)
데이터베이스는 여러 가지 사물에 대한 많은 정보를 기억할 수 있는 기계란다. 
사람들은 이 기계에 많은 정보를 저장한 뒤 필요할 때 꺼내 쓰지. 
자, 이제 알았으니 나가서 뛰어놀렴. 

2. 데이터베이스의 종류

  1. 관계형 데이터베이스(RDB)
  2. NoSQL(Not Only SQL)
  3. 그외 (계층형 데이터베이스, 네트워크형 데이터베이스

https://honeyteacs.tistory.com/19

[SQL 코드 연습]

Microsoft Windows [Version 10.0.19043.1466]
(c) Microsoft Corporation. All rights reserved.

C:\Users\박규언>cd C:\Program Files\MySQL\MySQL Server 8.0\bin

C:\Program Files\MySQL\MySQL Server 8.0\bin>mysql -u root -p
Enter password: ****
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.0.28 MySQL Community Server - GPL

Copyright (c) 2000, 2022, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> SELECT version();
+-----------+
| version() |
+-----------+
| 8.0.28    |
+-----------+
1 row in set (0.00 sec)

mysql> status;
--------------
mysql  Ver 8.0.28 for Win64 on x86_64 (MySQL Community Server - GPL)

Connection id:          8
Current database:
Current user:           root@localhost
SSL:                    Cipher in use is TLS_AES_256_GCM_SHA384
Using delimiter:        ;
Server version:         8.0.28 MySQL Community Server - GPL
Protocol version:       10
Connection:             localhost via TCP/IP
Server characterset:    utf8mb4
Db     characterset:    utf8mb4
Client characterset:    euckr
Conn.  characterset:    euckr
TCP port:               3306
Binary data as:         Hexadecimal
Uptime:                 13 min 30 sec

Threads: 2  Questions: 6  Slow queries: 0  Opens: 117  Flush tables: 3  Open tables: 36  Queries per second avg: 0.007
--------------

mysql> select
    -> version();
+-----------+
| version() |
+-----------+
| 8.0.28    |
+-----------+
1 row in set (0.00 sec)

mysql> SELECT user();
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':' at line 1
mysql> SELECT user, host FROM mysql.user;
+------------------+-----------+
| user             | host      |
+------------------+-----------+
| mysql.infoschema | localhost |
| mysql.session    | localhost |
| mysql.sys        | localhost |
| root             | localhost |
+------------------+-----------+
4 rows in set (0.01 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sakila             |
| sys                |
| world              |
+--------------------+
6 rows in set (0.04 sec)

mysql> CREATE DATABASE webdev_db;
Query OK, 1 row affected (0.01 sec)

mysql> CREATE DATABASE webdev_db;
ERROR 1007 (HY000): Can't create database 'webdev_db'; database exists
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sakila             |
| sys                |
| webdev_db          |
| world              |
+--------------------+
7 rows in set (0.00 sec)

mysql> DROP DATABASE webdev_db;
Query OK, 0 rows affected (0.02 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sakila             |
| sys                |
| world              |
+--------------------+
6 rows in set (0.00 sec)

mysql> CREATE DATABASE mydb111;
Query OK, 1 row affected (0.00 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mydb111            |
| mysql              |
| performance_schema |
| sakila             |
| sys                |
| world              |
+--------------------+
7 rows in set (0.00 sec)

mysql> CREATE USER 'webpro' IDENTIFIED BY '1111';
Query OK, 0 rows affected (0.01 sec)

mysql> SELECT user, host FROM mysql.user;
+------------------+-----------+
| user             | host      |
+------------------+-----------+
| webpro           | %         |
| mysql.infoschema | localhost |
| mysql.session    | localhost |
| mysql.sys        | localhost |
| root             | localhost |
+------------------+-----------+
5 rows in set (0.00 sec)

mysql> quit()
    -> quit;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'quit()
quit' at line 1
mysql> quit;
Bye

C:\Program Files\MySQL\MySQL Server 8.0\bin>mysql -u webpro -p
Enter password: ****
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 10
Server version: 8.0.28 MySQL Community Server - GPL

Copyright (c) 2000, 2022, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> status;
--------------
mysql  Ver 8.0.28 for Win64 on x86_64 (MySQL Community Server - GPL)

Connection id:          10
Current database:
Current user:           webpro@localhost
SSL:                    Cipher in use is TLS_AES_256_GCM_SHA384
Using delimiter:        ;
Server version:         8.0.28 MySQL Community Server - GPL
Protocol version:       10
Connection:             localhost via TCP/IP
Server characterset:    utf8mb4
Db     characterset:    utf8mb4
Client characterset:    euckr
Conn.  characterset:    euckr
TCP port:               3306
Binary data as:         Hexadecimal
Uptime:                 32 min 35 sec

Threads: 2  Questions: 26  Slow queries: 0  Opens: 149  Flush tables: 3  Open tables: 68  Queries per second avg: 0.013
--------------

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
+--------------------+
1 row in set (0.00 sec)

mysql> quit;
Bye

C:\Program Files\MySQL\MySQL Server 8.0\bin>mysql -u root -p
Enter password: ****
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 11
Server version: 8.0.28 MySQL Community Server - GPL

Copyright (c) 2000, 2022, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> DROP USER 'webpro';
Query OK, 0 rows affected (0.01 sec)

mysql> SELECT user, host FROM mysql.user;
+------------------+-----------+
| user             | host      |
+------------------+-----------+
| mysql.infoschema | localhost |
| mysql.session    | localhost |
| mysql.sys        | localhost |
| root             | localhost |
+------------------+-----------+
4 rows in set (0.00 sec)

mysql> CREATE USER 'myuser111' IDENTIFIED BY '1234';
Query OK, 0 rows affected (0.01 sec)

mysql> SELECT user, host FROM mysql.user;
+------------------+-----------+
| user             | host      |
+------------------+-----------+
| myuser111        | %         |
| mysql.infoschema | localhost |
| mysql.session    | localhost |
| mysql.sys        | localhost |
| root             | localhost |
+------------------+-----------+
5 rows in set (0.00 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mydb111            |
| mysql              |
| performance_schema |
| sakila             |
| sys                |
| world              |
+--------------------+
7 rows in set (0.00 sec)

mysql> grant all privileges on mydb111.* to 'myuser111'@%';
    '> grant all privileges on mydb111.* to 'myuser111'@%';
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%';
grant all privileges on mydb111.* to 'myuser111'@%'' at line 1
mysql> grant all privileges on mydb111.* to 'myuser111'@'%';
Query OK, 0 rows affected (0.01 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.01 sec)

mysql> quit;
Bye

C:\Program Files\MySQL\MySQL Server 8.0\bin>mysql -u myuser111 -p
Enter password: ****
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 12
Server version: 8.0.28 MySQL Community Server - GPL

Copyright (c) 2000, 2022, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mydb111            |
+--------------------+
2 rows in set (0.01 sec)

mysql> status;
--------------
mysql  Ver 8.0.28 for Win64 on x86_64 (MySQL Community Server - GPL)

Connection id:          12
Current database:
Current user:           myuser111@localhost
SSL:                    Cipher in use is TLS_AES_256_GCM_SHA384
Using delimiter:        ;
Server version:         8.0.28 MySQL Community Server - GPL
Protocol version:       10
Connection:             localhost via TCP/IP
Server characterset:    utf8mb4
Db     characterset:    utf8mb4
Client characterset:    euckr
Conn.  characterset:    euckr
TCP port:               3306
Binary data as:         Hexadecimal
Uptime:                 44 min 21 sec

Threads: 2  Questions: 43  Slow queries: 0  Opens: 182  Flush tables: 3  Open tables: 101  Queries per second avg: 0.016
--------------

mysql> use mydb111;
Database changed
mysql> status;
--------------
mysql  Ver 8.0.28 for Win64 on x86_64 (MySQL Community Server - GPL)

Connection id:          12
Current database:       mydb111
Current user:           myuser111@localhost
SSL:                    Cipher in use is TLS_AES_256_GCM_SHA384
Using delimiter:        ;
Server version:         8.0.28 MySQL Community Server - GPL
Protocol version:       10
Connection:             localhost via TCP/IP
Server characterset:    utf8mb4
Db     characterset:    utf8mb4
Client characterset:    euckr
Conn.  characterset:    euckr
TCP port:               3306
Binary data as:         Hexadecimal
Uptime:                 44 min 48 sec

Threads: 2  Questions: 48  Slow queries: 0  Opens: 182  Flush tables: 3  Open tables: 101  Queries per second avg: 0.017
--------------

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mydb111            |
+--------------------+
2 rows in set (0.00 sec)

mysql> use information_schema;
Database changed
mysql> show tables;
+---------------------------------------+
| Tables_in_information_schema          |
+---------------------------------------+
| ADMINISTRABLE_ROLE_AUTHORIZATIONS     |
| APPLICABLE_ROLES                      |
| CHARACTER_SETS                        |
| CHECK_CONSTRAINTS                     |
| COLLATION_CHARACTER_SET_APPLICABILITY |
| COLLATIONS                            |
| COLUMN_PRIVILEGES                     |
| COLUMN_STATISTICS                     |
| COLUMNS                               |
| COLUMNS_EXTENSIONS                    |
| ENABLED_ROLES                         |
| ENGINES                               |
| EVENTS                                |
| FILES                                 |
| INNODB_BUFFER_PAGE                    |
| INNODB_BUFFER_PAGE_LRU                |
| INNODB_BUFFER_POOL_STATS              |
| INNODB_CACHED_INDEXES                 |
| INNODB_CMP                            |
| INNODB_CMP_PER_INDEX                  |
| INNODB_CMP_PER_INDEX_RESET            |
| INNODB_CMP_RESET                      |
| INNODB_CMPMEM                         |
| INNODB_CMPMEM_RESET                   |
| INNODB_COLUMNS                        |
| INNODB_DATAFILES                      |
| INNODB_FIELDS                         |
| INNODB_FOREIGN                        |
| INNODB_FOREIGN_COLS                   |
| INNODB_FT_BEING_DELETED               |
| INNODB_FT_CONFIG                      |
| INNODB_FT_DEFAULT_STOPWORD            |
| INNODB_FT_DELETED                     |
| INNODB_FT_INDEX_CACHE                 |
| INNODB_FT_INDEX_TABLE                 |
| INNODB_INDEXES                        |
| INNODB_METRICS                        |
| INNODB_SESSION_TEMP_TABLESPACES       |
| INNODB_TABLES                         |
| INNODB_TABLESPACES                    |
| INNODB_TABLESPACES_BRIEF              |
| INNODB_TABLESTATS                     |
| INNODB_TEMP_TABLE_INFO                |
| INNODB_TRX                            |
| INNODB_VIRTUAL                        |
| KEY_COLUMN_USAGE                      |
| KEYWORDS                              |
| OPTIMIZER_TRACE                       |
| PARAMETERS                            |
| PARTITIONS                            |
| PLUGINS                               |
| PROCESSLIST                           |
| PROFILING                             |
| REFERENTIAL_CONSTRAINTS               |
| RESOURCE_GROUPS                       |
| ROLE_COLUMN_GRANTS                    |
| ROLE_ROUTINE_GRANTS                   |
| ROLE_TABLE_GRANTS                     |
| ROUTINES                              |
| SCHEMA_PRIVILEGES                     |
| SCHEMATA                              |
| SCHEMATA_EXTENSIONS                   |
| ST_GEOMETRY_COLUMNS                   |
| ST_SPATIAL_REFERENCE_SYSTEMS          |
| ST_UNITS_OF_MEASURE                   |
| STATISTICS                            |
| TABLE_CONSTRAINTS                     |
| TABLE_CONSTRAINTS_EXTENSIONS          |
| TABLE_PRIVILEGES                      |
| TABLES                                |
| TABLES_EXTENSIONS                     |
| TABLESPACES                           |
| TABLESPACES_EXTENSIONS                |
| TRIGGERS                              |
| USER_ATTRIBUTES                       |
| USER_PRIVILEGES                       |
| VIEW_ROUTINE_USAGE                    |
| VIEW_TABLE_USAGE                      |
| VIEWS                                 |
+---------------------------------------+
79 rows in set (0.03 sec)

mysql> use mydb111;
Database changed
mysql> show tables;
Empty set (0.00 sec)

mysql> CREATE TABLE items (
    -> id int,
    -> name varchar(20)
    -> );
Query OK, 0 rows affected (0.05 sec)

mysql> show tables;
+-------------------+
| Tables_in_mydb111 |
+-------------------+
| items             |
+-------------------+
1 row in set (0.00 sec)

mysql> DESC items;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int         | YES  |     | NULL    |       |
| name  | varchar(20) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.01 sec)

mysql> DROP TABLE items;
Query OK, 0 rows affected (0.19 sec)

mysql> show tables;
Empty set (0.03 sec)

mysql> DROP TABLE items;
ERROR 1051 (42S02): Unknown table 'mydb111.items'
mysql> DROP TABLE IF EXISTS items;
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> CREATE TABLE items (
    -> id int primary key auto_increment,
    -> content varchar(200),
    -> created_on datetime DEFAULT now(), -- 디폴트값은 '현재시간'
    -> due_date date,
    -> `use` int(1) -- 정수 1자리 타입 컬럼 use
    -> );
Query OK, 0 rows affected, 1 warning (0.06 sec)

mysql> desc items;
+------------+--------------+------+-----+-------------------+-------------------+
| Field      | Type         | Null | Key | Default           | Extra             |
+------------+--------------+------+-----+-------------------+-------------------+
| id         | int          | NO   | PRI | NULL              | auto_increment    |
| content    | varchar(200) | YES  |     | NULL              |                   |
| created_on | datetime     | YES  |     | CURRENT_TIMESTAMP | DEFAULT_GENERATED |
| due_date   | date         | YES  |     | NULL              |                   |
| use        | int          | YES  |     | NULL              |                   |
+------------+--------------+------+-----+-------------------+-------------------+
5 rows in set (0.01 sec)

mysql> SELECT * FROM items;
Empty set (0.01 sec)

mysql> INSERT INTO items(content) values('스포애니');
Query OK, 1 row affected (0.01 sec)

mysql> SELECT * FROM items;
+----+----------+---------------------+----------+------+
| id | content  | created_on          | due_date | use  |
+----+----------+---------------------+----------+------+
|  1 | 스포애니 | 2022-03-15 22:41:02 | NULL     | NULL |
+----+----------+---------------------+----------+------+
1 row in set (0.01 sec)

mysql> INSERT INTO items(content) values('스포애니');
Query OK, 1 row affected (0.00 sec)

mysql> SELECT * FROM items;
+----+----------+---------------------+----------+------+
| id | content  | created_on          | due_date | use  |
+----+----------+---------------------+----------+------+
|  1 | 스포애니 | 2022-03-15 22:41:02 | NULL     | NULL |
|  2 | 스포애니 | 2022-03-15 22:43:01 | NULL     | NULL |
+----+----------+---------------------+----------+------+
2 rows in set (0.00 sec)

mysql> INSERT INTO items(content, due_date, `use`)
    -> VALUES ('스포애니', '2022-05-01', 2);
Query OK, 1 row affected (0.00 sec)

mysql> SELECT * FROM items;
+----+----------+---------------------+------------+------+
| id | content  | created_on          | due_date   | use  |
+----+----------+---------------------+------------+------+
|  1 | 스포애니 | 2022-03-15 22:41:02 | NULL       | NULL |
|  2 | 스포애니 | 2022-03-15 22:43:01 | NULL       | NULL |
|  3 | 스포애니 | 2022-03-15 22:45:27 | 2022-05-01 |    2 |
+----+----------+---------------------+------------+------+
3 rows in set (0.00 sec)

mysql> CREATE TABLE phonebook (
    ->   id INT PRIMARY KEY AUTO_INCREMENT,
    ->   name VARCHAR(80) NOT NULL,
    ->   phonenum VARCHAR(20) DEFAULT '010-0000-000',
    ->   email VARCHAR(100),
    ->   regDate DATETIME DEFAULT now()
    -> );
Query OK, 0 rows affected (0.03 sec)

mysql> show tables;
+-------------------+
| Tables_in_mydb111 |
+-------------------+
| items             |
| phonebook         |
+-------------------+
2 rows in set (0.00 sec)

mysql> DESC phonebook;
+----------+--------------+------+-----+-------------------+-------------------+
| Field    | Type         | Null | Key | Default           | Extra             |
+----------+--------------+------+-----+-------------------+-------------------+
| id       | int          | NO   | PRI | NULL              | auto_increment    |
| name     | varchar(80)  | NO   |     | NULL              |                   |
| phonenum | varchar(20)  | YES  |     | 010-0000-000      |                   |
| email    | varchar(100) | YES  |     | NULL              |                   |
| regDate  | datetime     | YES  |     | CURRENT_TIMESTAMP | DEFAULT_GENERATED |
+----------+--------------+------+-----+-------------------+-------------------+
5 rows in set (0.03 sec)

mysql> ALTER TABLE phonebook
    -> MODIFY COLUMN phonenum varchar(35) UNIQUE;
Query OK, 0 rows affected (0.05 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> DESC phonebook;
+----------+--------------+------+-----+-------------------+-------------------+
| Field    | Type         | Null | Key | Default           | Extra             |
+----------+--------------+------+-----+-------------------+-------------------+
| id       | int          | NO   | PRI | NULL              | auto_increment    |
| name     | varchar(80)  | NO   |     | NULL              |                   |
| phonenum | varchar(35)  | YES  | UNI | NULL              |                   |
| email    | varchar(100) | YES  |     | NULL              |                   |
| regDate  | datetime     | YES  |     | CURRENT_TIMESTAMP | DEFAULT_GENERATED |
+----------+--------------+------+-----+-------------------+-------------------+
5 rows in set (0.01 sec)

mysql> ALTER TABLE phonebook
    -> ADD COLUMN age INT(3) DEFAULT 1 CHECK(age >= 0);
Query OK, 0 rows affected, 1 warning (0.09 sec)
Records: 0  Duplicates: 0  Warnings: 1

mysql> DESC phonebook;
+----------+--------------+------+-----+-------------------+-------------------+
| Field    | Type         | Null | Key | Default           | Extra             |
+----------+--------------+------+-----+-------------------+-------------------+
| id       | int          | NO   | PRI | NULL              | auto_increment    |
| name     | varchar(80)  | NO   |     | NULL              |                   |
| phonenum | varchar(35)  | YES  | UNI | NULL              |                   |
| email    | varchar(100) | YES  |     | NULL              |                   |
| regDate  | datetime     | YES  |     | CURRENT_TIMESTAMP | DEFAULT_GENERATED |
| age      | int          | YES  |     | 1                 |                   |
+----------+--------------+------+-----+-------------------+-------------------+
6 rows in set (0.01 sec)

mysql> ALTER TABLE phonebook
    -> DROP email;
Query OK, 0 rows affected (0.05 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc phonebook;
+----------+-------------+------+-----+-------------------+-------------------+
| Field    | Type        | Null | Key | Default           | Extra             |
+----------+-------------+------+-----+-------------------+-------------------+
| id       | int         | NO   | PRI | NULL              | auto_increment    |
| name     | varchar(80) | NO   |     | NULL              |                   |
| phonenum | varchar(35) | YES  | UNI | NULL              |                   |
| regDate  | datetime    | YES  |     | CURRENT_TIMESTAMP | DEFAULT_GENERATED |
| age      | int         | YES  |     | 1                 |                   |
+----------+-------------+------+-----+-------------------+-------------------+
5 rows in set (0.00 sec)

mysql> CREATE TABLE test_book(
    -> bk_uid INT PRIMARY KEY AUTO_INCREMENT,
    -> bk_name VARCHAR(20) NOT NULL,
    -> bk_author VARCHAR(30),
    -> bk_issuedate DATE,
    -> bk_price FLOAT
    -> );
Query OK, 0 rows affected (0.04 sec)

mysql> CREATE TABLE test_movie(
    -> no INT PRIMARY KEY AUTO_INCREMENT,
    -> title VARCHAR(25) NOT NULL,
    -> director VARCHAR(30),
    -> distributor VARCHAR(30),
    -> open_at DATE
    -> );
Query OK, 0 rows affected (0.02 sec)

mysql> SHOW tables;
+-------------------+
| Tables_in_mydb111 |
+-------------------+
| items             |
| phonebook         |
| test_book         |
| test_movie        |
+-------------------+
4 rows in set (0.01 sec)
  • 잘 짜놓은 쿼리문 하나, 열페이지 코드 안부럽다
  • 쿼리문을 잘 만들어야, 코딩이 덜 고생한다. 쿼리문 몇줄이면 끝날 일도, 프로그램으로 코딩하면 수십페이지가 넘어갈수도 있다
  • 쿼리문의 기본 문법은 간단하다, 그러나, 주어진 과제를 어떻게 쿼리 문을 작성하느냐는 결과와 성능에 큰 차이가 있을수 있다.
  • 많은 훈련과 경험에서 우러나온 경륜과 내공이 빛을 발하는 분야(?)

좋은 웹페이지 즐겨찾기