Sqlite3: Difference between revisions
(→Pragma) |
|||
(3 intermediate revisions by the same user not shown) | |||
Line 145: | Line 145: | ||
== Pragma == | == Pragma == | ||
[[Sqlite3-pragma]] 항목 참조. | |||
== Statement == | == Statement == | ||
Line 203: | Line 183: | ||
[[File:Select-stmt.gif]] | [[File:Select-stmt.gif]] | ||
=== INSERT === | === INSERT/REPLACE === | ||
테이블에 데이터를 입력한다. | 테이블에 데이터를 입력한다. | ||
<source lang=sql> | <source lang=sql> | ||
Line 211: | Line 191: | ||
[[File:Insert-stmt.gif]] | [[File:Insert-stmt.gif]] | ||
==== Example ==== | |||
<source lang=sql> | <source lang=sql> | ||
INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (1, 'Paul', 32, 'California', 20000.00 ); | INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (1, 'Paul', 32, 'California', 20000.00 ); | ||
Line 223: | Line 204: | ||
INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (6, 'Kim', 22, 'South-Hall', 45000.00 ); | INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (6, 'Kim', 22, 'South-Hall', 45000.00 ); | ||
INSERT OR REPLACE INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (6, 'Kim', 22, 'New-York', 45000.00 ); | |||
</source> | </source> | ||
Line 249: | Line 232: | ||
ALTER TABLE OLD_COMPANY ADD COLUMN SEX char(1); | ALTER TABLE OLD_COMPANY ADD COLUMN SEX char(1); | ||
</source> | |||
=== JOIN === | |||
==== CROSS JOIN ==== | |||
두 개의 | |||
<source lang=sql> | |||
sqlite> select dial_mode, type from ob_plan cross join ob_destination; | |||
dial_mode|type | |||
1|1 | |||
0|1 | |||
0|1 | |||
1|1 | |||
</source> | |||
==== INNER JOIN ==== | |||
A INNER JOIN creates a new result table by combining column values of two tables(table1 and table2) based upon the join-predicate. The query compares each row of table1 with each row of table2 to find all pairs of rows which satisfy the join-oredicate. When the join-predicate is satisfied, column values for each matched pair of rows of A and B are combined into a result row. | |||
<pre> | |||
</pre> | |||
==== OUTER JOIN ==== | |||
The OUTER JOIN is an extension of the INNER JOIN. Though SQL standard defines three types of OUTER JOINs(LEFT, RIGHT, FULL). But the SQLite only supports the LEFT OUTER JOIN. | |||
<source lang=sql> | |||
</source> | </source> | ||
Latest revision as of 01:08, 22 March 2017
Overview
Sqlite3 사용법 정리.
Commands
원문은 이곳<ref>https://www.sqlite.org/cli.html</ref>을 참조하자.
sqlite> .help .backup ?DB? FILE Backup DB (default "main") to FILE .bail ON|OFF Stop after hitting an error. Default OFF .databases List names and files of attached databases .dump ?TABLE? ... Dump the database in an SQL text format If TABLE specified, only dump tables matching LIKE pattern TABLE. .echo ON|OFF Turn command echo on or off .exit Exit this program .explain ?ON|OFF? Turn output mode suitable for EXPLAIN on or off. With no args, it turns EXPLAIN on. .header(s) ON|OFF Turn display of headers on or off .help Show this message .import FILE TABLE Import data from FILE into TABLE .indices ?TABLE? Show names of all indices If TABLE specified, only show indices for tables matching LIKE pattern TABLE. .load FILE ?ENTRY? Load an extension library .log FILE|off Turn logging on or off. FILE can be stderr/stdout .mode MODE ?TABLE? Set output mode where MODE is one of: csv Comma-separated values column Left-aligned columns. (See .width) html HTML <table> code insert SQL insert statements for TABLE line One value per line list Values delimited by .separator string tabs Tab-separated values tcl TCL list elements .nullvalue STRING Use STRING in place of NULL values .open ?FILENAME? Close existing database and reopen FILENAME .output FILENAME Send output to FILENAME .output stdout Send output to the screen .print STRING... Print literal STRING .prompt MAIN CONTINUE Replace the standard prompts .quit Exit this program .read FILENAME Execute SQL in FILENAME .restore ?DB? FILE Restore content of DB (default "main") from FILE .schema ?TABLE? Show the CREATE statements If TABLE specified, only show tables matching LIKE pattern TABLE. .separator STRING Change separator used by output mode and .import .show Show the current values for various settings .stats ON|OFF Turn stats on or off .tables ?TABLE? List names of tables If TABLE specified, only list tables matching LIKE pattern TABLE. .timeout MS Try opening locked tables for MS milliseconds .trace FILE|off Output each SQL statement as it is run .vfsname ?AUX? Print the name of the VFS stack .width NUM1 NUM2 ... Set column widths for "column" mode .timer ON|OFF Turn the CPU timer measurement on or off
.tables
현재의 데이터베이스에 있는 테이블 내용을 보여준다. 특정 테이블 이름을 같이 입력할 경우, 입력한 테이블이 데이터베이스에 존재하는지를 리턴한다.
sqlite> .tables sample1 test sqlite> .tables test test sqlite> .tables test1 sqlite>
.schema
입력한 테이블의 상세 내용을 확인한다. 만약, 입력한 테이블 내용이 없을 경우, 해당 데이터베이스의 전체 테이블의 상세 내용을 출력한다.
sqlite> .schema test CREATE TABLE test(seq integer PRIMARY KEY AUTOINCREMENT, test text); sqlite> .schema CREATE TABLE test(seq integer PRIMARY KEY AUTOINCREMENT, test text); CREATE TABLE sample1(seq integer);
.headers
결과를 표시할 때, 헤더 정보를 표시할지 말지를 설정한다.
sqlite> .headers on sqlite> select * from test; seq|uniq_id 3926|ec1d7c92-83b0-4410-a6f4-897fc1522485
.mode
결과를 표시할 때, 어떤 방식으로 표시할 것인지를 설정한다.
.mode MODE ?TABLE?
다음의 표현방식 중 하나를 선택할 수 있다.
- csv - Comma-separated values - column - Left-aligned columns. (See .width) - html - HTML <table> code - insert - SQL insert statements for TABLE - line - One value per line - list - Values delimited by .separator string - tabs - Tab-separated values - tcl - TCL list elements
Datatypes
Strong classes and datatypes
Sqlite 에서는 크게 다음과 같은 분류로 데이터타입을 정의한다.
NULL. The value is a NULL value. INTEGER. The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value. REAL. The value is a floating point value, stored as an 8-byte IEEE floating point number. TEXT. The value is a text string, stored using the database encoding (UTF-8, UTF-16BE or UTF-16LE). BLOB. The value is a blob of data, stored exactly as it was input.
Boolean Datatype
SQLite 에는 Boolean 타입을 위한 데이터 타입이 없다. 대신, integer 0(false), integer 1(true) 로 저장된다.
Date and Time Datatype
SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values:
TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS"). REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar. INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.
Comparison expression
|| * / % + - << >> & | < <= > >= = == != <> IS IS NOT IN LIKE GLOB MATCH REGEXP AND OR
Pragma
Sqlite3-pragma 항목 참조.
Statement
Basic
여러개의 SQL Statement 는 다음과 같이 구성된다.
그리고 각각의 SQL Statement 들은 다음과 같이 구성된다.
CREATE TABLE
Table 을 생성한다.
<source lang=sql> CREATE TABLE t(x INTEGER PRIMARY KEY ASC, y, z); CREATE TABLE t(x INTEGER, y, z, PRIMARY KEY(x ASC)); CREATE TABLE t(x INTEGER, y, z, PRIMARY KEY(x DESC)); </source>
CREATE VEIW
TABLE 에서 특정 데이터들만의 리스트를 구성하고자 할 때, VIEW 를 사용할 수 있다. 한번 VEIW 가 생성되면, SELECT 구문의 FROM 절로 사용될 수 있다<ref>https://www.sqlite.org/lang_createview.html</ref>.
SQLITE3의 VIEW는 오직 Read(SELECT) 만 가능하며, DELETE, INSERT, UPDATE 는 불가능하다. CREATE 와 VIEW 절 사이에 "TEMP" 혹은 "TEMPORARY" 를 사용할 수 있는데, 이걸 사용하게 되면 해당 커넥션이 연결되는 동안만 생성되고 유지되는 VIEW 를 생성하게 된다.
VIEW 는 굉장히 유용하면서도 SELECT 보다 약간이지만 더 나은 성능을 발휘한다<ref>http://stackoverflow.com/questions/9282325/sqlite3-views-affect-performance</ref>.
<source lang=sql> create view if not exists sms_active as select * from sms where on_going != 0; </source>
SELECT
INSERT/REPLACE
테이블에 데이터를 입력한다. <source lang=sql> INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN); </source>
Example
<source lang=sql> INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (1, 'Paul', 32, 'California', 20000.00 );
INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (2, 'Allen', 25, 'Texas', 15000.00 );
INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );
INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );
INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (5, 'David', 27, 'Texas', 85000.00 );
INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (6, 'Kim', 22, 'South-Hall', 45000.00 );
INSERT OR REPLACE INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (6, 'Kim', 22, 'New-York', 45000.00 ); </source>
UPDATE
테이블에 입력된 데이터를 갱신한다. <source lang=sql> UPDATE table_name SET column1 = value1, column2 = value2...., columnN = valueN WHERE [condition]; </source>
<source lang=sql> UPDATE COMPANY SET ADDRESS = 'Texas' WHERE ID = 6; </source>
ALTER TABLE
테이블의 내용을 변경한다. <source lang=sql> ALTER TABLE database_name.table_name RENAME TO new_table_name; </source>
<source lang=sql> ALTER TABLE COMPANY RENAME TO OLD_COMPANY;
ALTER TABLE OLD_COMPANY ADD COLUMN SEX char(1); </source>
JOIN
CROSS JOIN
두 개의 <source lang=sql> sqlite> select dial_mode, type from ob_plan cross join ob_destination;
dial_mode|type 1|1 0|1 0|1 1|1 </source>
INNER JOIN
A INNER JOIN creates a new result table by combining column values of two tables(table1 and table2) based upon the join-predicate. The query compares each row of table1 with each row of table2 to find all pairs of rows which satisfy the join-oredicate. When the join-predicate is satisfied, column values for each matched pair of rows of A and B are combined into a result row.
OUTER JOIN
The OUTER JOIN is an extension of the INNER JOIN. Though SQL standard defines three types of OUTER JOINs(LEFT, RIGHT, FULL). But the SQLite only supports the LEFT OUTER JOIN. <source lang=sql>
</source>
Advanced
Attach
다른 데이터베이스 내용을 참조하고자 할 때 사용한다.
> attach /tmp/sqlite3/tmp.db as test;
EXPLAIN QUERY PLAN
Sqlite3 에서는 디버깅 및 High-level 디버깅을 을 위한 특수 Query를 지원한다. 이 Query를 이용하면 작성된 Query 가 정확히 어떤 Table/Index/View 등을 참조하는지 등의 정보를 확인할 수 있다.
결과값은 보통 다음의 4개의 컬럼으로 나온다. selectid, order, from 은 INTEGER 타입이고, 마지막 detail 은 TEXT 타입이다.
selectid, order, from, detail
<source lang=sql> sqlite> EXPLAIN QUERY PLAN select * from sms where on_going != 0; order|from|detail 0|0|TABLE sms
sqlite> EXPLAIN QUERY PLAN select * from sms where on_going < 0; order|from|detail 0|0|TABLE sms WITH INDEX sms_on_going </source>
Errors
unfinalized
sqlite3_close() 시, 다음과 같이 unfinalized 에러가 나올 경우, sqlite3_finalize() 를 호출해서 강제로 종료할 수 있다.
unable to close due to unfinalized statements or unfinished backups
See also
- https://www.sqlite.org/datatype3.html - Datatypes In SQLite Version 3
- https://www.sqlite.org/pragma.html - PRAGMA Statements
References
<references />