'old/SQL'에 해당되는 글 29건

  1. 2010.07.06 Command Line Shell For SQLite
  2. 2010.03.18 외부 키
  3. 2010.03.18 열 구성 변경
  4. 2010.03.17 용어
  5. 2010.03.17 TRANSACTION
  6. 2010.03.17 INDEX
  7. 2010.03.17 한정 술어
  8. 2010.03.17 집합 연산자
  9. 2010.03.17 VIEW
  10. 2010.03.17 JOIN
  11. 2010.03.16 Sub Query
  12. 2010.03.16 DELETE
  13. 2010.03.16 UPDATE
  14. 2010.03.16 INSERT
  15. 2010.03.15 변환 함수 (CAST)
  16. 2010.03.15 집합 함수 (AVG, SUM, COUNT, MAX, MIN)
  17. 2010.03.15 날짜함수 (GETDATE, DAY, MONTH, YEAR, DATEADD, DATEDIFF
  18. 2010.03.15 문자열 함수 (LEN, LENGTH, SUBSTRING, SUBSTR, LTRIM, RTRIM, UPPER, LOWER)
  19. 2010.03.15 수치 함수 (CEILING, CEIL, FLOOR, RAND, ROUND)
  20. 2010.03.12 기타 연산자
  21. 2010.03.12 문자 처리 연산자
  22. 2010.03.12 논리 연산자
  23. 2010.03.12 비교 연산자
  24. 2010.03.12 산술 연산자
  25. 2010.03.12 WHERE절
  26. 2010.03.12 SQL의 기본
  27. 2010.03.12 MSDE 설치 및 시동
  28. 2010.03.12 OSQL의 시동
  29. 2010.02.09 adb op for sqlite3

Command Line Shell For SQLite

The SQLite library includes a simple command-line utility named sqlite3 (or sqlite3.exe on windows) that allows the user to manually enter and execute SQL commands against an SQLite database. This document provides a brief introduction on how to use the sqlite3 program.

Getting Started

To start the sqlite3 program, just type "sqlite3" followed by the name the file that holds the SQLite database. If the file does not exist, a new one is created automatically. The sqlite3 program will then prompt you to enter SQL. Type in SQL statements (terminated by a semicolon), press "Enter" and the SQL will be executed.

For example, to create a new SQLite database named "ex1" with a single table named "tbl1", you might do this:

$ sqlite3 ex1
SQLite version 3.6.11
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> create table tbl1(one varchar(10), two smallint);
sqlite> insert into tbl1 values('hello!',10);
sqlite> insert into tbl1 values('goodbye', 20);
sqlite> select * from tbl1;
hello!|10
goodbye|20
sqlite>

You can terminate the sqlite3 program by typing your systems End-Of-File character (usually a Control-D). Use the interrupt character (usually a Control-C) to stop a long-running SQL statement.

Make sure you type a semicolon at the end of each SQL command! The sqlite3 program looks for a semicolon to know when your SQL command is complete. If you omit the semicolon, sqlite3 will give you a continuation prompt and wait for you to enter more text to be added to the current SQL command. This feature allows you to enter SQL commands that span multiple lines. For example:

sqlite> CREATE TABLE tbl2 (
   ...>   f1 varchar(30) primary key,
   ...>   f2 text,
   ...>   f3 real
   ...> );
sqlite>

Aside: Querying the SQLITE_MASTER table

The database schema in an SQLite database is stored in a special table named "sqlite_master". You can execute "SELECT" statements against the special sqlite_master table just like any other table in an SQLite database. For example:

$ sqlite3 ex1
SQLite vresion 3.6.11
Enter ".help" for instructions
sqlite> select * from sqlite_master;
    type = table
    name = tbl1
tbl_name = tbl1
rootpage = 3
     sql = create table tbl1(one varchar(10), two smallint)
sqlite>

But you cannot execute DROP TABLE, UPDATE, INSERT or DELETE against the sqlite_master table. The sqlite_master table is updated automatically as you create or drop tables and indices from the database. You can not make manual changes to the sqlite_master table.

The schema for TEMPORARY tables is not stored in the "sqlite_master" table since TEMPORARY tables are not visible to applications other than the application that created the table. The schema for TEMPORARY tables is stored in another special table named "sqlite_temp_master". The "sqlite_temp_master" table is temporary itself.

Special commands to sqlite3

Most of the time, sqlite3 just reads lines of input and passes them on to the SQLite library for execution. But if an input line begins with a dot ("."), then that line is intercepted and interpreted by the sqlite3 program itself. These "dot commands" are typically used to change the output format of queries, or to execute certain prepackaged query statements.

For a listing of the available dot commands, you can enter ".help" at any time. For example:

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
.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.
.genfkey ?OPTIONS?     Options are:
                         --no-drop: Do not drop old fkey triggers.
                         --ignore-errors: Ignore tables with fkey errors
                         --exec: Execute generated SQL immediately
                       See file tool/genfkey.README in the source 
                       distribution for further information.
.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 on TABLE
.iotrace FILE          Enable I/O diagnostic logging to FILE
.load FILE ?ENTRY?     Load an extension library
.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      Print STRING in place of NULL values
.output FILENAME       Send output to FILENAME
.output stdout         Send output to the screen
.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
.separator STRING      Change separator used by output mode and .import
.show                  Show the current values for various settings
.tables ?PATTERN?      List names of tables matching a LIKE pattern
.timeout MS            Try opening locked tables for MS milliseconds
.timer ON|OFF          Turn the CPU timer measurement on or off
.width NUM NUM ...     Set column widths for "column" mode
sqlite>

Changing Output Formats

The sqlite3 program is able to show the results of a query in eight different formats: "csv", "column", "html", "insert", "line", "list", "tabs", and "tcl". You can use the ".mode" dot command to switch between these output formats.

The default output mode is "list". In list mode, each record of a query result is written on one line of output and each column within that record is separated by a specific separator string. The default separator is a pipe symbol ("|"). List mode is especially useful when you are going to send the output of a query to another program (such as AWK) for additional processing.

sqlite> .mode list
sqlite> select * from tbl1;
hello|10
goodbye|20
sqlite>

You can use the ".separator" dot command to change the separator for list mode. For example, to change the separator to a comma and a space, you could do this:

sqlite> .separator ", "
sqlite> select * from tbl1;
hello, 10
goodbye, 20
sqlite>

In "line" mode, each column in a row of the database is shown on a line by itself. Each line consists of the column name, an equal sign and the column data. Successive records are separated by a blank line. Here is an example of line mode output:

sqlite> .mode line
sqlite> select * from tbl1;
one = hello
two = 10

one = goodbye
two = 20
sqlite>

In column mode, each record is shown on a separate line with the data aligned in columns. For example:

sqlite> .mode column
sqlite> select * from tbl1;
one         two       
----------  ----------
hello       10        
goodbye     20        
sqlite>

By default, each column is at least 10 characters wide. Data that is too wide to fit in a column is truncated. You can adjust the column widths using the ".width" command. Like this:

sqlite> .width 12 6
sqlite> select * from tbl1;
one           two   
------------  ------
hello         10    
goodbye       20    
sqlite>

The ".width" command in the example above sets the width of the first column to 12 and the width of the second column to 6. All other column widths were unaltered. You can gives as many arguments to ".width" as necessary to specify the widths of as many columns as are in your query results.

If you specify a column a width of 0, then the column width is automatically adjusted to be the maximum of three numbers: 10, the width of the header, and the width of the first row of data. This makes the column width self-adjusting. The default width setting for every column is this auto-adjusting 0 value.

The column labels that appear on the first two lines of output can be turned on and off using the ".header" dot command. In the examples above, the column labels are on. To turn them off you could do this:

sqlite> .header off
sqlite> select * from tbl1;
hello         10    
goodbye       20    
sqlite>

Another useful output mode is "insert". In insert mode, the output is formatted to look like SQL INSERT statements. You can use insert mode to generate text that can later be used to input data into a different database.

When specifying insert mode, you have to give an extra argument which is the name of the table to be inserted into. For example:

sqlite> .mode insert new_table
sqlite> select * from tbl1;
INSERT INTO 'new_table' VALUES('hello',10);
INSERT INTO 'new_table' VALUES('goodbye',20);
sqlite>

The last output mode is "html". In this mode, sqlite3 writes the results of the query as an XHTML table. The beginning <TABLE> and the ending </TABLE> are not written, but all of the intervening <TR>s, <TH>s, and <TD>s are. The html output mode is envisioned as being useful for CGI.

Writing results to a file

By default, sqlite3 sends query results to standard output. You can change this using the ".output" command. Just put the name of an output file as an argument to the .output command and all subsequent query results will be written to that file. Use ".output stdout" to begin writing to standard output again. For example:

sqlite> .mode list
sqlite> .separator |
sqlite> .output test_file_1.txt
sqlite> select * from tbl1;
sqlite> .exit
$ cat test_file_1.txt
hello|10
goodbye|20
$

Querying the database schema

The sqlite3 program provides several convenience commands that are useful for looking at the schema of the database. There is nothing that these commands do that cannot be done by some other means. These commands are provided purely as a shortcut.

For example, to see a list of the tables in the database, you can enter ".tables".

sqlite> .tables
tbl1
tbl2
sqlite>

The ".tables" command is similar to setting list mode then executing the following query:

SELECT name FROM sqlite_master 
WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%'
UNION ALL 
SELECT name FROM sqlite_temp_master 
WHERE type IN ('table','view') 
ORDER BY 1

In fact, if you look at the source code to the sqlite3 program (found in the source tree in the file src/shell.c) you'll find exactly the above query.

The ".indices" command works in a similar way to list all of the indices for a particular table. The ".indices" command takes a single argument which is the name of the table for which the indices are desired. Last, but not least, is the ".schema" command. With no arguments, the ".schema" command shows the original CREATE TABLE and CREATE INDEX statements that were used to build the current database. If you give the name of a table to ".schema", it shows the original CREATE statement used to make that table and all if its indices. We have:

sqlite> .schema
create table tbl1(one varchar(10), two smallint)
CREATE TABLE tbl2 (
  f1 varchar(30) primary key,
  f2 text,
  f3 real
)
sqlite> .schema tbl2
CREATE TABLE tbl2 (
  f1 varchar(30) primary key,
  f2 text,
  f3 real
)
sqlite>

The ".schema" command accomplishes the same thing as setting list mode, then entering the following query:

SELECT sql FROM 
   (SELECT * FROM sqlite_master UNION ALL
    SELECT * FROM sqlite_temp_master)
WHERE type!='meta'
ORDER BY tbl_name, type DESC, name

Or, if you give an argument to ".schema" because you only want the schema for a single table, the query looks like this:

SELECT sql FROM
   (SELECT * FROM sqlite_master UNION ALL
    SELECT * FROM sqlite_temp_master)
WHERE type!='meta' AND sql NOT NULL AND name NOT LIKE 'sqlite_%'
ORDER BY substr(type,2,1), name

You can supply an argument to the .schema command. If you do, the query looks like this:

SELECT sql FROM
   (SELECT * FROM sqlite_master UNION ALL
    SELECT * FROM sqlite_temp_master)
WHERE tbl_name LIKE '%s'
  AND type!='meta' AND sql NOT NULL AND name NOT LIKE 'sqlite_%'
ORDER BY substr(type,2,1), name

The "%s" in the query is replace by your argument. This allows you to view the schema for some subset of the database.

sqlite> .schema %abc%

Along these same lines, the ".table" command also accepts a pattern as its first argument. If you give an argument to the .table command, a "%" is both appended and prepended and a LIKE clause is added to the query. This allows you to list only those tables that match a particular pattern.

The ".databases" command shows a list of all databases open in the current connection. There will always be at least 2. The first one is "main", the original database opened. The second is "temp", the database used for temporary tables. There may be additional databases listed for databases attached using the ATTACH statement. The first output column is the name the database is attached with, and the second column is the filename of the external file.

sqlite> .databases

Converting An Entire Database To An ASCII Text File

Use the ".dump" command to convert the entire contents of a database into a single ASCII text file. This file can be converted back into a database by piping it back into sqlite3.

A good way to make an archival copy of a database is this:

$ echo '.dump' | sqlite3 ex1 | gzip -c >ex1.dump.gz

This generates a file named ex1.dump.gz that contains everything you need to reconstruct the database at a later time, or on another machine. To reconstruct the database, just type:

$ zcat ex1.dump.gz | sqlite3 ex2

The text format is pure SQL so you can also use the .dump command to export an SQLite database into other popular SQL database engines. Like this:

$ createdb ex2
$ sqlite3 ex1 .dump | psql ex2

Other Dot Commands

The ".explain" dot command can be used to set the output mode to "column" and to set the column widths to values that are reasonable for looking at the output of an EXPLAIN command. The EXPLAIN command is an SQLite-specific SQL extension that is useful for debugging. If any regular SQL is prefaced by EXPLAIN, then the SQL command is parsed and analyzed but is not executed. Instead, the sequence of virtual machine instructions that would have been used to execute the SQL command are returned like a query result. For example:

sqlite> .explain
sqlite> explain delete from tbl1 where two<20;
addr  opcode        p1     p2     p3          
----  ------------  -----  -----  -------------------------------------   
0     ListOpen      0      0                  
1     Open          0      1      tbl1        
2     Next          0      9                  
3     Field         0      1                  
4     Integer       20     0                  
5     Ge            0      2                  
6     Key           0      0                  
7     ListWrite     0      0                  
8     Goto          0      2                  
9     Noop          0      0                  
10    ListRewind    0      0                  
11    ListRead      0      14                 
12    Delete        0      0                  
13    Goto          0      11                 
14    ListClose     0      0

The ".timeout" command sets the amount of time that the sqlite3 program will wait for locks to clear on files it is trying to access before returning an error. The default value of the timeout is zero so that an error is returned immediately if any needed database table or index is locked.

And finally, we mention the ".exit" command which causes the sqlite3 program to exit.

Using sqlite3 in a shell script

One way to use sqlite3 in a shell script is to use "echo" or "cat" to generate a sequence of commands in a file, then invoke sqlite3 while redirecting input from the generated command file. This works fine and is appropriate in many circumstances. But as an added convenience, sqlite3 allows a single SQL command to be entered on the command line as a second argument after the database name. When the sqlite3 program is launched with two arguments, the second argument is passed to the SQLite library for processing, the query results are printed on standard output in list mode, and the program exits. This mechanism is designed to make sqlite3 easy to use in conjunction with programs like "awk". For example:

$ sqlite3 ex1 'select * from tbl1' |
>  awk '{printf "<tr><td>%s<td>%s\n",$1,$2 }'
<tr><td>hello<td>10
<tr><td>goodbye<td>20
$

Ending shell commands

SQLite commands are normally terminated by a semicolon. In the shell you can also use the word "GO" (case-insensitive) or a slash character "/" on a line by itself to end a command. These are used by SQL Server and Oracle, respectively. These won't work insqlite3_exec(), because the shell translates these into a semicolon before passing them to that function.

Compiling the sqlite3 program from sources

The source code to the sqlite3 command line interface is in a single file named "shell.c" which you can download from the SQLite website. Compile this file (together with the sqlite3 library source code to generate the executable. For example:

gcc -o sqlite3 shell.c sqlite3.c -ldl -lpthread

Command Line Shell For SQLite

The SQLite library includes a simple command-line utility named sqlite3 (or sqlite3.exe on windows) that allows the user to manually enter and execute SQL commands against an SQLite database. This document provides a brief introduction on how to use the sqlite3 program.

Getting Started

To start the sqlite3 program, just type "sqlite3" followed by the name the file that holds the SQLite database. If the file does not exist, a new one is created automatically. The sqlite3 program will then prompt you to enter SQL. Type in SQL statements (terminated by a semicolon), press "Enter" and the SQL will be executed.

For example, to create a new SQLite database named "ex1" with a single table named "tbl1", you might do this:

$ sqlite3 ex1
SQLite version 3.6.11
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> create table tbl1(one varchar(10), two smallint);
sqlite> insert into tbl1 values('hello!',10);
sqlite> insert into tbl1 values('goodbye', 20);
sqlite> select * from tbl1;
hello!|10
goodbye|20
sqlite>

You can terminate the sqlite3 program by typing your systems End-Of-File character (usually a Control-D). Use the interrupt character (usually a Control-C) to stop a long-running SQL statement.

Make sure you type a semicolon at the end of each SQL command! The sqlite3 program looks for a semicolon to know when your SQL command is complete. If you omit the semicolon, sqlite3 will give you a continuation prompt and wait for you to enter more text to be added to the current SQL command. This feature allows you to enter SQL commands that span multiple lines. For example:

sqlite> CREATE TABLE tbl2 (
   ...>   f1 varchar(30) primary key,
   ...>   f2 text,
   ...>   f3 real
   ...> );
sqlite>

Aside: Querying the SQLITE_MASTER table

The database schema in an SQLite database is stored in a special table named "sqlite_master". You can execute "SELECT" statements against the special sqlite_master table just like any other table in an SQLite database. For example:

$ sqlite3 ex1
SQLite vresion 3.6.11
Enter ".help" for instructions
sqlite> select * from sqlite_master;
    type = table
    name = tbl1
tbl_name = tbl1
rootpage = 3
     sql = create table tbl1(one varchar(10), two smallint)
sqlite>

But you cannot execute DROP TABLE, UPDATE, INSERT or DELETE against the sqlite_master table. The sqlite_master table is updated automatically as you create or drop tables and indices from the database. You can not make manual changes to the sqlite_master table.

The schema for TEMPORARY tables is not stored in the "sqlite_master" table since TEMPORARY tables are not visible to applications other than the application that created the table. The schema for TEMPORARY tables is stored in another special table named "sqlite_temp_master". The "sqlite_temp_master" table is temporary itself.

Special commands to sqlite3

Most of the time, sqlite3 just reads lines of input and passes them on to the SQLite library for execution. But if an input line begins with a dot ("."), then that line is intercepted and interpreted by the sqlite3 program itself. These "dot commands" are typically used to change the output format of queries, or to execute certain prepackaged query statements.

For a listing of the available dot commands, you can enter ".help" at any time. For example:

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
.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.
.genfkey ?OPTIONS?     Options are:
                         --no-drop: Do not drop old fkey triggers.
                         --ignore-errors: Ignore tables with fkey errors
                         --exec: Execute generated SQL immediately
                       See file tool/genfkey.README in the source 
                       distribution for further information.
.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 on TABLE
.iotrace FILE          Enable I/O diagnostic logging to FILE
.load FILE ?ENTRY?     Load an extension library
.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      Print STRING in place of NULL values
.output FILENAME       Send output to FILENAME
.output stdout         Send output to the screen
.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
.separator STRING      Change separator used by output mode and .import
.show                  Show the current values for various settings
.tables ?PATTERN?      List names of tables matching a LIKE pattern
.timeout MS            Try opening locked tables for MS milliseconds
.timer ON|OFF          Turn the CPU timer measurement on or off
.width NUM NUM ...     Set column widths for "column" mode
sqlite>

Changing Output Formats

The sqlite3 program is able to show the results of a query in eight different formats: "csv", "column", "html", "insert", "line", "list", "tabs", and "tcl". You can use the ".mode" dot command to switch between these output formats.

The default output mode is "list". In list mode, each record of a query result is written on one line of output and each column within that record is separated by a specific separator string. The default separator is a pipe symbol ("|"). List mode is especially useful when you are going to send the output of a query to another program (such as AWK) for additional processing.

sqlite> .mode list
sqlite> select * from tbl1;
hello|10
goodbye|20
sqlite>

You can use the ".separator" dot command to change the separator for list mode. For example, to change the separator to a comma and a space, you could do this:

sqlite> .separator ", "
sqlite> select * from tbl1;
hello, 10
goodbye, 20
sqlite>

In "line" mode, each column in a row of the database is shown on a line by itself. Each line consists of the column name, an equal sign and the column data. Successive records are separated by a blank line. Here is an example of line mode output:

sqlite> .mode line
sqlite> select * from tbl1;
one = hello
two = 10

one = goodbye
two = 20
sqlite>

In column mode, each record is shown on a separate line with the data aligned in columns. For example:

sqlite> .mode column
sqlite> select * from tbl1;
one         two       
----------  ----------
hello       10        
goodbye     20        
sqlite>

By default, each column is at least 10 characters wide. Data that is too wide to fit in a column is truncated. You can adjust the column widths using the ".width" command. Like this:

sqlite> .width 12 6
sqlite> select * from tbl1;
one           two   
------------  ------
hello         10    
goodbye       20    
sqlite>

The ".width" command in the example above sets the width of the first column to 12 and the width of the second column to 6. All other column widths were unaltered. You can gives as many arguments to ".width" as necessary to specify the widths of as many columns as are in your query results.

If you specify a column a width of 0, then the column width is automatically adjusted to be the maximum of three numbers: 10, the width of the header, and the width of the first row of data. This makes the column width self-adjusting. The default width setting for every column is this auto-adjusting 0 value.

The column labels that appear on the first two lines of output can be turned on and off using the ".header" dot command. In the examples above, the column labels are on. To turn them off you could do this:

sqlite> .header off
sqlite> select * from tbl1;
hello         10    
goodbye       20    
sqlite>

Another useful output mode is "insert". In insert mode, the output is formatted to look like SQL INSERT statements. You can use insert mode to generate text that can later be used to input data into a different database.

When specifying insert mode, you have to give an extra argument which is the name of the table to be inserted into. For example:

sqlite> .mode insert new_table
sqlite> select * from tbl1;
INSERT INTO 'new_table' VALUES('hello',10);
INSERT INTO 'new_table' VALUES('goodbye',20);
sqlite>

The last output mode is "html". In this mode, sqlite3 writes the results of the query as an XHTML table. The beginning <TABLE> and the ending </TABLE> are not written, but all of the intervening <TR>s, <TH>s, and <TD>s are. The html output mode is envisioned as being useful for CGI.

Writing results to a file

By default, sqlite3 sends query results to standard output. You can change this using the ".output" command. Just put the name of an output file as an argument to the .output command and all subsequent query results will be written to that file. Use ".output stdout" to begin writing to standard output again. For example:

sqlite> .mode list
sqlite> .separator |
sqlite> .output test_file_1.txt
sqlite> select * from tbl1;
sqlite> .exit
$ cat test_file_1.txt
hello|10
goodbye|20
$

Querying the database schema

The sqlite3 program provides several convenience commands that are useful for looking at the schema of the database. There is nothing that these commands do that cannot be done by some other means. These commands are provided purely as a shortcut.

For example, to see a list of the tables in the database, you can enter ".tables".

sqlite> .tables
tbl1
tbl2
sqlite>

The ".tables" command is similar to setting list mode then executing the following query:

SELECT name FROM sqlite_master 
WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%'
UNION ALL 
SELECT name FROM sqlite_temp_master 
WHERE type IN ('table','view') 
ORDER BY 1

In fact, if you look at the source code to the sqlite3 program (found in the source tree in the file src/shell.c) you'll find exactly the above query.

The ".indices" command works in a similar way to list all of the indices for a particular table. The ".indices" command takes a single argument which is the name of the table for which the indices are desired. Last, but not least, is the ".schema" command. With no arguments, the ".schema" command shows the original CREATE TABLE and CREATE INDEX statements that were used to build the current database. If you give the name of a table to ".schema", it shows the original CREATE statement used to make that table and all if its indices. We have:

sqlite> .schema
create table tbl1(one varchar(10), two smallint)
CREATE TABLE tbl2 (
  f1 varchar(30) primary key,
  f2 text,
  f3 real
)
sqlite> .schema tbl2
CREATE TABLE tbl2 (
  f1 varchar(30) primary key,
  f2 text,
  f3 real
)
sqlite>

The ".schema" command accomplishes the same thing as setting list mode, then entering the following query:

SELECT sql FROM 
   (SELECT * FROM sqlite_master UNION ALL
    SELECT * FROM sqlite_temp_master)
WHERE type!='meta'
ORDER BY tbl_name, type DESC, name

Or, if you give an argument to ".schema" because you only want the schema for a single table, the query looks like this:

SELECT sql FROM
   (SELECT * FROM sqlite_master UNION ALL
    SELECT * FROM sqlite_temp_master)
WHERE type!='meta' AND sql NOT NULL AND name NOT LIKE 'sqlite_%'
ORDER BY substr(type,2,1), name

You can supply an argument to the .schema command. If you do, the query looks like this:

SELECT sql FROM
   (SELECT * FROM sqlite_master UNION ALL
    SELECT * FROM sqlite_temp_master)
WHERE tbl_name LIKE '%s'
  AND type!='meta' AND sql NOT NULL AND name NOT LIKE 'sqlite_%'
ORDER BY substr(type,2,1), name

The "%s" in the query is replace by your argument. This allows you to view the schema for some subset of the database.

sqlite> .schema %abc%

Along these same lines, the ".table" command also accepts a pattern as its first argument. If you give an argument to the .table command, a "%" is both appended and prepended and a LIKE clause is added to the query. This allows you to list only those tables that match a particular pattern.

The ".databases" command shows a list of all databases open in the current connection. There will always be at least 2. The first one is "main", the original database opened. The second is "temp", the database used for temporary tables. There may be additional databases listed for databases attached using the ATTACH statement. The first output column is the name the database is attached with, and the second column is the filename of the external file.

sqlite> .databases

Converting An Entire Database To An ASCII Text File

Use the ".dump" command to convert the entire contents of a database into a single ASCII text file. This file can be converted back into a database by piping it back into sqlite3.

A good way to make an archival copy of a database is this:

$ echo '.dump' | sqlite3 ex1 | gzip -c >ex1.dump.gz

This generates a file named ex1.dump.gz that contains everything you need to reconstruct the database at a later time, or on another machine. To reconstruct the database, just type:

$ zcat ex1.dump.gz | sqlite3 ex2

The text format is pure SQL so you can also use the .dump command to export an SQLite database into other popular SQL database engines. Like this:

$ createdb ex2
$ sqlite3 ex1 .dump | psql ex2

Other Dot Commands

The ".explain" dot command can be used to set the output mode to "column" and to set the column widths to values that are reasonable for looking at the output of an EXPLAIN command. The EXPLAIN command is an SQLite-specific SQL extension that is useful for debugging. If any regular SQL is prefaced by EXPLAIN, then the SQL command is parsed and analyzed but is not executed. Instead, the sequence of virtual machine instructions that would have been used to execute the SQL command are returned like a query result. For example:

sqlite> .explain
sqlite> explain delete from tbl1 where two<20;
addr  opcode        p1     p2     p3          
----  ------------  -----  -----  -------------------------------------   
0     ListOpen      0      0                  
1     Open          0      1      tbl1        
2     Next          0      9                  
3     Field         0      1                  
4     Integer       20     0                  
5     Ge            0      2                  
6     Key           0      0                  
7     ListWrite     0      0                  
8     Goto          0      2                  
9     Noop          0      0                  
10    ListRewind    0      0                  
11    ListRead      0      14                 
12    Delete        0      0                  
13    Goto          0      11                 
14    ListClose     0      0

The ".timeout" command sets the amount of time that the sqlite3 program will wait for locks to clear on files it is trying to access before returning an error. The default value of the timeout is zero so that an error is returned immediately if any needed database table or index is locked.

And finally, we mention the ".exit" command which causes the sqlite3 program to exit.

Using sqlite3 in a shell script

One way to use sqlite3 in a shell script is to use "echo" or "cat" to generate a sequence of commands in a file, then invoke sqlite3 while redirecting input from the generated command file. This works fine and is appropriate in many circumstances. But as an added convenience, sqlite3 allows a single SQL command to be entered on the command line as a second argument after the database name. When the sqlite3 program is launched with two arguments, the second argument is passed to the SQLite library for processing, the query results are printed on standard output in list mode, and the program exits. This mechanism is designed to make sqlite3 easy to use in conjunction with programs like "awk". For example:

$ sqlite3 ex1 'select * from tbl1' |
>  awk '{printf "<tr><td>%s<td>%s\n",$1,$2 }'
<tr><td>hello<td>10
<tr><td>goodbye<td>20
$

Ending shell commands

SQLite commands are normally terminated by a semicolon. In the shell you can also use the word "GO" (case-insensitive) or a slash character "/" on a line by itself to end a command. These are used by SQL Server and Oracle, respectively. These won't work insqlite3_exec(), because the shell translates these into a semicolon before passing them to that function.

Compiling the sqlite3 program from sources

The source code to the sqlite3 command line interface is in a single file named "shell.c" which you can download from the SQLite website. Compile this file (together with the sqlite3 library source code to generate the executable. For example:

gcc -o sqlite3 shell.c sqlite3.c -ldl -lpthread

'old > SQL' 카테고리의 다른 글

외부 키  (0) 2010.03.18
열 구성 변경  (0) 2010.03.18
용어  (0) 2010.03.17
TRANSACTION  (0) 2010.03.17
INDEX  (0) 2010.03.17
Posted by jazzlife
,

외부 키

old/SQL 2010. 3. 18. 14:17
; 서로 다른 테이블의 열끼리 동기화

1) 정의하기


(외부키가 될)열이름 데이터 형 REFERENCES 부모 테이블명(부모 열이름)

2) 테이블 제약 조건

FOREIGN KEY (외부키 열이름) REFERENCES 부모 테이블명(부모 열이름)


3) 나중에 설정하기

(SQL server, MySQL)
ALTER TABLE
자식 테이블 명 ADD FOREIGN KEY (외부 열이름)
                                                  REFERENCES 부모 테이블명(부모 열이름);

(PostgreSQL)
ALTER TABLE
자식 테이블명 ADD FOREIGN KEY (외부 열이름)
                                             REFERENCES 부모 테이블명 부모 열이름;

'old > SQL' 카테고리의 다른 글

Command Line Shell For SQLite  (0) 2010.07.06
열 구성 변경  (0) 2010.03.18
용어  (0) 2010.03.17
TRANSACTION  (0) 2010.03.17
INDEX  (0) 2010.03.17
Posted by jazzlife
,

열 구성 변경

old/SQL 2010. 3. 18. 11:48

1) 열 추가

ALTER TABLE 테이블명 ADD 열이름 데이터형;

(Oracle)
ALTER TABLE 테이블명 ADD (열이름 데이터형);

(PostgreSQL)
ALTER TABLE 테이블명 ADD COLUMN 열이름 데이터형;

* 기본값 갖기
ALTER TABLE 테이블명 ADD 열이름 데이터형 DEFAULT 기본값;


2) 열 삭제

ALTER TABLE 테이블명 DROP COLUMN 열이름;

(Oracle)
ALTER TABLE
테이블명 DROP (열이름);

(PostgreSQL)
ALTER TABLE
테이블명 DROP 열이름;


3) 제약 조건 추가 (PRIMARY KEY, UNIQUE, CHECK 제약 조건)

ALTER TABLE 테이블명 ADD PRIMARY KEY(열이름);

ALTER TABLE 테이블명 ALTER COLUMN 열이름 데이터형 NOT NULL;

(Oracle)
ALTER TABLE
테이블명 MODIFY (item NOT NULL);

(PostgreSQL)
ALTER TABLE
테이블명 ALTER COLUMN 열이름 SET NOT NULL;


4) 테이블 이름 변경

EXEC sp_rename 원래 테이블명, 새 테이블 명

(Oracle)
RENAME
  원래 테이블명TO 새  테이블명;

(MySQL, PostgreSQL)
ALTER TABLE
 원래 테이블명 RENAME TO 새 테이블명;


5) 열 이름 변경

EXEC sp_rename 테이블명.[원래 열이름]', 새 열이름

(MySQL)
ALTER TABLE
 테이블명 HANGE code b_no INTEGER;

(PostgreSQL)
ALTER TABLE
 테이블명 RENAME COLUMN 원래 열이름 TO 새 열이름;


6) 설정 추가

(Oracle)
ALTER TABLE
 테이블명 MODIFY (열이름 DEFAULT 100);

(MySQL, PostgreSQL)
ALTER TABLE
 테이블명 ALTER COLUMN 열이름 SET DEFAULT 100;


7) 설정 해제

ALTER TABLE 테이블명 ALTER 열이름 DROP DEFAULT


8) 열 데이터형 변경

(Oracle)
ALTER TABLE
 테이블명 MODIFY (열이름 변경 후 데이터명);

(MySQL)
ALTER TABLE
 테이블명 MODIFY 열이름 변경 후 데이터형 NOT NULL;


9) 제약 조건 해제

ALTER TABLE
 테이블명 ALTER 열이름 DROP CONSTRAINT UNIQUE;

'old > SQL' 카테고리의 다른 글

Command Line Shell For SQLite  (0) 2010.07.06
외부 키  (0) 2010.03.18
용어  (0) 2010.03.17
TRANSACTION  (0) 2010.03.17
INDEX  (0) 2010.03.17
Posted by jazzlife
,

용어

old/SQL 2010. 3. 17. 18:10

동적 SQL : 상황에 따라 내용이 달라지는 SQL

저장 프로시저 : 일련의 조작을 프로그램으로 묶어서 RDBMS에 저장하는 장치

'old > SQL' 카테고리의 다른 글

외부 키  (0) 2010.03.18
열 구성 변경  (0) 2010.03.18
TRANSACTION  (0) 2010.03.17
INDEX  (0) 2010.03.17
한정 술어  (0) 2010.03.17
Posted by jazzlife
,

TRANSACTION

old/SQL 2010. 3. 17. 17:21
; 일련의 수행과정을 하나로 묶는 것

1) COMMIT : 처리 과정을 확정

BEGIN TRANSACTION;
SELECT...
INSERT...
INSERT...
.
.
.
COMMIT;



2) ROLLBACK : 처리 과정을 취소

BEGIN TRANSACTION;
SELECT...
INSERT...
INSERT...
.
.
.
ROLLBACK;


'old > SQL' 카테고리의 다른 글

열 구성 변경  (0) 2010.03.18
용어  (0) 2010.03.17
INDEX  (0) 2010.03.17
한정 술어  (0) 2010.03.17
집합 연산자  (0) 2010.03.17
Posted by jazzlife
,

INDEX

old/SQL 2010. 3. 17. 17:17
; INDEX SCAN을 위해서 만드는 목차 같은 개념


CREATE
INDEX 인덱스명 ON 테이블명(열이름);
.
.
.
DROP INDEX 인덱스명;

'old > SQL' 카테고리의 다른 글

용어  (0) 2010.03.17
TRANSACTION  (0) 2010.03.17
한정 술어  (0) 2010.03.17
집합 연산자  (0) 2010.03.17
VIEW  (0) 2010.03.17
Posted by jazzlife
,

한정 술어

old/SQL 2010. 3. 17. 17:05

; Sub Query의 결과를 비교 조건으로 사용하고 싶을 때 이용

1) ALL


SELECT menu FROM tbl_menu1 WHERE price > ALL
             (SELECT price FROM tbl_menu1 WHERE menu LIKE '%닭%');


2) EXISTS, NOT EXISTS

SELECT * FROM tbl_menber WHERE EXISTS
               (SELECT name FROM tbl_member WHERE no = 5);

SELECT * FROM tbl_menber WHERE NOT EXISTS
               (SELECT name FROM tbl_member WHERE no = 5);

3) ANY

SELECT name, price FROM tbl_stock WHERE price = ANY (SELECT price FROM tbl_stock WHERE country LIKE 'america');

'old > SQL' 카테고리의 다른 글

TRANSACTION  (0) 2010.03.17
INDEX  (0) 2010.03.17
집합 연산자  (0) 2010.03.17
VIEW  (0) 2010.03.17
JOIN  (0) 2010.03.17
Posted by jazzlife
,

집합 연산자

old/SQL 2010. 3. 17. 16:09
1) UNION : 중복되는 데이터를 정리한 후 가져옴

SELECT  lname, fname FROM tbl_club_a UNION SELECT sung, irum FROM tbl_club_b;


2) UNION ALL : 정리 안 하고 데이터 가져옴 

SELECT  lname, fname FROM tbl_club_a UNION ALL SELECT sung, irum FROM tbl_club_b;


3) INTERSECT : 일치하는 데이터만 가져옴

SELECT  lname, fname FROM tbl_club_a INTERSECT SELECT sung, irum FROM tbl_club_b;



4) EXCEPT (오라클에서는 MINUS)


SELECT  lname, fname FROM tbl_club_a EXCEPT SELECT sung, irum FROM tbl_club_b;

'old > SQL' 카테고리의 다른 글

INDEX  (0) 2010.03.17
한정 술어  (0) 2010.03.17
VIEW  (0) 2010.03.17
JOIN  (0) 2010.03.17
Sub Query  (0) 2010.03.16
Posted by jazzlife
,

VIEW

old/SQL 2010. 3. 17. 15:58
; 자주 사용하는 SELECT문을 등록하여 가상으로 만든 표

테이블 명만 'viw_xxx'로 바꿔주면 된다.

뷰 삭제하기
DROP VIEW viw_tea;

'old > SQL' 카테고리의 다른 글

한정 술어  (0) 2010.03.17
집합 연산자  (0) 2010.03.17
JOIN  (0) 2010.03.17
Sub Query  (0) 2010.03.16
DELETE  (0) 2010.03.16
Posted by jazzlife
,

JOIN

old/SQL 2010. 3. 17. 14:24

; 여러 개의 테이블이나 뷰를 연결


1) CROSS JOIN

SELECT * FROM tbl_a CROSS JOIN tbl_b;
(= SELECT * FROM tbl_a, tbl_b;)

 
id price id name id price id name
1 100 + 1 연필 = 1 100 1 연필
2 250 2 지우개 2 250 1 연필
1 100 2 지우개
2 250 2 지우개
                                                                                       
* 열 지정은 '.'피리어드로 한다. ex) tbl_a.name


2) INNER JOIN

SELECT * FROM tbl_name INNER JOIN tbl_age ON id = no;
(= SELECT * FROM tbl_name, tbl_age WHERE tbl_name.id = tbl_age.no;)

id name no age id name id age
1 kkoma 1 16 1 kkoma 1 16
2 ran + 2 7 = 2 ran 2 7
3 alex 4 14


3) LEFT, RIGHT JOIN

SELECT * FROM tbl_name LEFT JOIN tbl_age ON id = no;
SELECT * FROM tbl_name RIGHT JOIN tbl_age ON id = no;


id name id name id name id age
1 kkoma 1 16 1 kkoma 1 16
2 ran + 2 7 = 2 ran 2 7
3 alex 4 14 3 alex NULL NULL
id name id name id name id age
1 kkoma 1 16 1 kkoma 1 16
2 ran + 2 7 = 2 ran 2 7
3 alex 4 14 NULL NULL 4 14


4) FULL JOIN

SELECT * FROM tbl_name FULL JOIN tbl_age ON id = no;


id name id name id name id age
1 kkoma 1 16 1 kkoma 1 16
2 ran + 2 7 = 2 ran 2 7
3 alex 4 14 NULL NULL 4 14
3 alex NULL NULL

* 예외

(SQL SERVER)
SELECT * FROM tbl_name, tbl_age WHERE  id *= no; <- LEFT JOIN
SELECT * FROM tbl_name, tbl_age WHERE  id =* no; <- RIGHT JOIN

(ORACLE)
SELECT * FROM tbl_name, tbl_age WHERE  id = no(+); <- LEFT JOIN
SELECT * FROM tbl_name, tbl_age WHERE  id = (+)no; <- RIGHT JOIN

'old > SQL' 카테고리의 다른 글

집합 연산자  (0) 2010.03.17
VIEW  (0) 2010.03.17
Sub Query  (0) 2010.03.16
DELETE  (0) 2010.03.16
UPDATE  (0) 2010.03.16
Posted by jazzlife
,

Sub Query

old/SQL 2010. 3. 16. 14:58

1) WHERE 절에서 사용

SELECT * FROM tbl_cake WHERE price >= (SELECT AVG(price) FROM tbl_cake);


2) HAVING 절에서 사용

SELECT code, MIN(arrival) FROM tbl_stock GROUP BY code
            HAVING MIN(arrival) < (SELECT AVG(shipment) FROM tbl_stock);



3) FROM 절에서 사용

SELECT MIN(price)
            FROM (SELECT * FROM tbl_cake WHERE price >= 2500) AS c_price;



* 응용

INSERT INTO tbl_advance SELECT * FROM tbl_results
    WHERE point1 + point2  > (SELECT AVG(point1 + point2) FROM tbl_results);

UPDATE tbl_allowance SET total = (overtime + travel)
     WHERE overtime + travel < (SELECT MAX(overtitme) FROM tbl_allowance);

DELETE FROM tbl_allowance WHERE travel > (SELECT AVG(travel)
            FROM tbl_allowance WHERE overtime >= 40000);

'old > SQL' 카테고리의 다른 글

VIEW  (0) 2010.03.17
JOIN  (0) 2010.03.17
DELETE  (0) 2010.03.16
UPDATE  (0) 2010.03.16
INSERT  (0) 2010.03.16
Posted by jazzlife
,

DELETE

old/SQL 2010. 3. 16. 14:44

1) 조건과 일치하는 데이터 삭제

DELETE FROM tbl_tel WHERE name = '박화정';



2) 모든 데이터 삭제하기

DELETE FROM tbl_tel;

'old > SQL' 카테고리의 다른 글

JOIN  (0) 2010.03.17
Sub Query  (0) 2010.03.16
UPDATE  (0) 2010.03.16
INSERT  (0) 2010.03.16
변환 함수 (CAST)  (0) 2010.03.15
Posted by jazzlife
,

UPDATE

old/SQL 2010. 3. 16. 14:17
; 등록된 값을 수정하기 위해서 사용한다.

1) 하나의 값 수정하기

UPDATE tbl_lunch SET price=7600 WHERE code = 2;


2) 여러 값 수정하기

UPDATE tbl_lunch SET menu='오늘의 런치', price=7900 WHERE code = 1;



'old > SQL' 카테고리의 다른 글

Sub Query  (0) 2010.03.16
DELETE  (0) 2010.03.16
INSERT  (0) 2010.03.16
변환 함수 (CAST)  (0) 2010.03.15
집합 함수 (AVG, SUM, COUNT, MAX, MIN)  (0) 2010.03.15
Posted by jazzlife
,

INSERT

old/SQL 2010. 3. 16. 14:09

1) 열 이름 생략하고 등록하기

INSERT INTO tbl_tea VALUES (2, '홍차', 8500);




2) 특정 열에만 값 등록하기

INSERT INTO tbl_tea (name, code) VALUES ('구기자차', 3);




3) 다른 테이블에 있는 자료 가져오기

INSERT INTO tbl_petlist (id, name) SELECT no, name FROM tbl_cat;

'old > SQL' 카테고리의 다른 글

DELETE  (0) 2010.03.16
UPDATE  (0) 2010.03.16
변환 함수 (CAST)  (0) 2010.03.15
집합 함수 (AVG, SUM, COUNT, MAX, MIN)  (0) 2010.03.15
날짜함수 (GETDATE, DAY, MONTH, YEAR, DATEADD, DATEDIFF  (0) 2010.03.15
Posted by jazzlife
,

변환 함수 (CAST)

old/SQL 2010. 3. 15. 14:24
CAST 함수 : 데이터형을 변환시키는 함수

ex)
CAST(0.245 AS VARCHAR)
CAST('2010-03-01' AS DATETIME)


SELECT time AS moonjayeol, CAST(time AS DATETIME) AS nalzza
            FROM tbl_schedule;
Posted by jazzlife
,

1. AVG 함수: 평균값 구함

2. SUM 함수: 합계를 구함

3. COUNT 함수: 열의 개수를 구함


ex)

SELECT AVG(score) AS average, SUM(score) AS total_score,
             COUNT(name) AS game FROM tbl_game;

ex)- 중복데이터 제거의 예

SELECT COUNT(DISTINCT name) AS member FROM tbl_game;


4. MAX, MIN 함수 : 최대, 최소 값을 구하는 기능

ex)

SELECT name, MAX(score) AS high, MIN(score) AS low FROM tbl_game GROUP BY name;

** WHERE은 집합 함수를 사용할 수 없어서 GROUP BY, HAVING 사용

ex)

SELECT name, SUM(score) AS over300 FROM tbl_game
             GROUP BY name HAVING (SUM(score) >= 300);

Posted by jazzlife
,
1. GETDATE 함수 (=DATE, SYSDATE) : 현재 날짜와 시간을 반환

ex)
SELECT GETDATE();

* DAY(m), MONTH(m), YEAR(m)


2. DATEADD 함수 : 일 수나 시간 수를 더하는 기능

DATEADD(단위요소 지정, 더하는 값, 더할 수치)



3. DATEDIFF 함수 : 날짜형으로 된 값끼리 차를 구하는 기능


ex)
SELECT DATEADD(m, 6, date1) FROM tbl_datelist WHERE no = 1;
SELECT DATEDIFF(d, date1, date2) FROM tbl_datelist WHERE no = 2;
SELECT DATEDIFF(d, GETDATE(), '2010-03-01');




Posted by jazzlife
,
1. LEN, LENGTH 함수 : 문자열의 문자 수 반환

ex)
SELECT LEN('꽃이 피다');
SELECT sname, LEN(sname) AS result FROM tbl_stdname;


2. SUBSTR, SUBSTRING 함수 : 지정된 부분만큼 문자를 가져와 반환

ex)
SELECT fname, SUBSTRING(fname, 2, 2) AS result FROM tbl_stdname;


3. LTRIM, RTRIM 함수 : 문자열의 맨 앞이나 맨 뒤의 공백을 삭제

ex)
SELECT LTRIM(pname) AS leftsp,
             RTRIM(pname) AS rightsp FROM tbl_pet;


4. UPPER, LOWER 함수 : 대소문자 변환

ex)
SELECT sname, LOWER(sname) AS somunja FROM tbl_stdname;
SELECT  fname, UPPER(fname) AS daemunja FROM tbl_stdname;



(RDBMS 고유함수)
LAST_DAT(time) : 지정한 날짜의 최종일을 반환하는 함수
POSITON('dum' IN 'hodumaru') : 문자열의 특정 문자열의 위치를 반환하는 함수

'old > SQL' 카테고리의 다른 글

집합 함수 (AVG, SUM, COUNT, MAX, MIN)  (0) 2010.03.15
날짜함수 (GETDATE, DAY, MONTH, YEAR, DATEADD, DATEDIFF  (0) 2010.03.15
수치 함수 (CEILING, CEIL, FLOOR, RAND, ROUND)  (0) 2010.03.15
기타 연산자  (0) 2010.03.12
문자 처리 연산자  (0) 2010.03.12
Posted by jazzlife
,
1. CEILING, CEIL 함수 : 소수점 이하를 올리는 함수

2. FLOOR 함수 : 소수점 이하를 내리는 함수

ex)
USE db_picbook;
SELECT cost, CEILING(cost) AS result1,
                     FLOOR(cost) AS result2 FROM tbl_sum;


3. RAND 함수 : 0~1.0 미만의 범위의 난수를 구하는 함수

ex)
SELECT RAND();
SELECT RAND(7);


4. 그 외

함수명 기능 주의
ABS(m) m의 절대값을 반환  
ROUND(m, x) 소수점 이하 x자리에서 m을 사사오입한 값을 반환  
POWER(m, x) m을 n승한 수치를 반환 POW 함수
SQRT(m) m에 대한 제곱근을 반환 SQR 함수
MOD(m, n) m을 n으로 나눈 나머지를 반환 %연산자
SIN(m) m에 대한 사인값을 반환  
COS(m) m에 대한 코사인값을 반환  
TAN(m) m에 대한 탄젠트값을 반환  
EXP(m) m의 자수승을 반환  
LOG(m, n) 밑이 m인 n의 자연로그값을 반환  
SIGN(m) m의 부호를 반환 양:1
음:-1
0: 0

Posted by jazzlife
,

기타 연산자

old/SQL 2010. 3. 12. 21:00


; 영어에 가까운 표현을 할 수 있는 기능의 연산자


1) BETWEEN ~ AND


SELECT score FROM tbl_game WHERE (score >= 10) AND (score <= 100); 을 바꾸면?
ex)
SELECT score FROM tbl_game WHERE score BETWEEN 10 AND 100;
* 코드의 길이를 줄일 수 있다.


2) IS NULL , IS NOT NULL

ex)
SELECT * FROM tbl_bookprice WHERE price IS NOT NULL;

SELECT * FROM tbl_bookprice WHERE price IS NULL;

* 열 이름 = NULL 같은 수식은 사용할 수 없다.


3) IN , NOT IN
    ; 지정한 값과 일치하는 데이터만 가져온다.

SELECT player FROM tbl_team WHERE (backno = 5) OR (backno != 10);
SELECT player FROM tbl_team WHERE (backno != 5) AND (backno != 10);
ex)
SELECT player FROM tbl_team WHERE backno IN (5, 10,..);

SELECT player FROM tbl_team WHERE backno NOT IN (5, 10,..);
* 코드의 길이를 줄일 수 있다.




S

'old > SQL' 카테고리의 다른 글

문자열 함수 (LEN, LENGTH, SUBSTRING, SUBSTR, LTRIM, RTRIM, UPPER, LOWER)  (0) 2010.03.15
수치 함수 (CEILING, CEIL, FLOOR, RAND, ROUND)  (0) 2010.03.15
문자 처리 연산자  (0) 2010.03.12
논리 연산자  (0) 2010.03.12
비교 연산자  (0) 2010.03.12
Posted by jazzlife
,

문자 처리 연산자

old/SQL 2010. 3. 12. 20:47


; 문자를 다루기 위해서 사용


1) 문자 연결

SELECT 열이름1 || 열이름2 FROM 테이블명;


* SQL 서버의 경우 '||' 대신 '+'를 사용한다.


2) 문자열 비교

SELECT 열이름 FROM 테이블명 WHERE 비교할 열 이름 LIKE 조건;


* LIKE : 특정 문자를 가져오고 싶을 때 사용

* 조건지정
 기호           기능  사용법                          의미
  % 0~임의수의 문자열  %산% 설악산, 산촌 등 '산'이 들어간 문자열
  _ 한 문자에 해당  _해준 이해준, 민해준 등 임의의 한 문자가 들어간 문자열


ex) '이'로 시작하는 문자열을 골라내는 명령.

SELECT name FROM tbl_namecard WHERE name LIKE '이%;


'old > SQL' 카테고리의 다른 글

수치 함수 (CEILING, CEIL, FLOOR, RAND, ROUND)  (0) 2010.03.15
기타 연산자  (0) 2010.03.12
논리 연산자  (0) 2010.03.12
비교 연산자  (0) 2010.03.12
산술 연산자  (0) 2010.03.12
Posted by jazzlife
,

논리 연산자

old/SQL 2010. 3. 12. 20:08



; 여러 개의 조건을 조합하여 복잡한 조건식을 만들기 위해 사용

사용 가능한 논리 연산자 : AND , OR , NOT



ex1)

SELECT * FROM tbl_exam WHERE ((id%2)<1) AND (score_eng >= 80);


ex2)

SELECT * FROM tbl_exam WHERE (score_kor >= 90) OR (score_eng >= 90);


ex3)

SELECT * FROM tbl_exam WHERE ((score_kor + score_eng) > 150);

'old > SQL' 카테고리의 다른 글

기타 연산자  (0) 2010.03.12
문자 처리 연산자  (0) 2010.03.12
비교 연산자  (0) 2010.03.12
산술 연산자  (0) 2010.03.12
WHERE절  (0) 2010.03.12
Posted by jazzlife
,

비교 연산자

old/SQL 2010. 3. 12. 20:07



; 조건식을 만들 때 사용한다.

사용 가능한 연산자 : = , < , <= , > , >= , <> (!=)


ex1)

SELECT id, name, score_eng FROM tbl_exam WHERE score_eng > 90;


ex2)

SELECT id, name, score_kor FROM tbl_exam WHERE score_name = '김상택';

'old > SQL' 카테고리의 다른 글

문자 처리 연산자  (0) 2010.03.12
논리 연산자  (0) 2010.03.12
산술 연산자  (0) 2010.03.12
WHERE절  (0) 2010.03.12
SQL의 기본  (0) 2010.03.12
Posted by jazzlife
,

산술 연산자

old/SQL 2010. 3. 12. 19:51


; SQL에서 수치 계산을 하기 위해 사용하는 기호

사용 가능한 연산자 : + , - , * , / , %



ex1)
SELECT name, (score_kor + score_eng) AS sum FROM tbl_exam;


ex2)
SELECT name, (score_kor + score_eng) AS sum FROM tbl_exam ORDER BY average DESC;

'old > SQL' 카테고리의 다른 글

논리 연산자  (0) 2010.03.12
비교 연산자  (0) 2010.03.12
WHERE절  (0) 2010.03.12
SQL의 기본  (0) 2010.03.12
MSDE 설치 및 시동  (0) 2010.03.12
Posted by jazzlife
,

WHERE절

old/SQL 2010. 3. 12. 19:45


; 특정 조건에 맞는 데이터만 가져오고 싶을 때 사용.


ex1)
SELECT 열이름 FROM 테이블명 WHERE 조건식;


ex2)
SELECT 열이름 FROM 테이블명 ORDER BY 열이름 조건;


'old > SQL' 카테고리의 다른 글

비교 연산자  (0) 2010.03.12
산술 연산자  (0) 2010.03.12
SQL의 기본  (0) 2010.03.12
MSDE 설치 및 시동  (0) 2010.03.12
OSQL의 시동  (0) 2010.03.12
Posted by jazzlife
,

SQL의 기본

old/SQL 2010. 3. 12. 19:38
1. DB 만들기
  
CREATE DATABASE 데이터베이스명;


2. DB 지정

USE 데이터베이스명;


3. TABLE 만들기

CREATE TABLE 테이블명 (열이름 데이터형 ,.....,);

* 데이터형 :
   (정수형)    INT, SMALLINT
    (실수형)    DECIMAL, NUMERIC, REAL, FLOAT, DOUBLE PRECISION
   (문자열형) CHAR(N), VARCHAR(N), TEXT, NCHAR(N), NVARCHAR(N), NTEXT



4. 제약 조건 지정


제약조건 의미
PRIMARY KEY 데이터 중복, NULL 금지
UNIQUE 한가지 값만 갖는다
CHECK 조건식에 안 맞으면 금지
NOT NULL NULL 값 금지
DEFAULT=값 지정한 값을 초기값으로 지정

ex)
CREATE TABLE tbl_test (code INT UNIQUE, name VARCHAR(30),
                                    height FLOAT, id INT UNIQUE NOT NULL);  



5. 데이터 등록

INSERT INTO 테이블명(열이름,...,..) VALUES (열값,....,..);



6. 데이터 가져오기


   1) 테이블 전체 가져오기

SELECT * FROM 테이블명;


   2) 한열 가져오기

SELECT 열이름 FROM 테이블명;


   3) 여러열 가져오기

SELECT 열이름... FROM 테이블명;



7. 데이터 정렬

   1) 오름차순

SELECT * FROM 테이블명 ORDER BY 열이름 ASC;


   2) 내림차순

SELECT * FROM 테이블명 ORDER BY 열이름 DESC;



8. 기타 옵션


   1) 데이터 그룹화 (지정한 열을 하나로 묶기)

SELECT 열이름,... FROM 테이블명 GROUP BY 열이름;



   2) 중복 데이터 제거

SELECT DISTINCT 열이름 FROM 테이블명;



   3) 열이름 바꿔서 출력

SELECT (구)열이름 AS (신)열이름 FROM 테이블명;

'old > SQL' 카테고리의 다른 글

산술 연산자  (0) 2010.03.12
WHERE절  (0) 2010.03.12
MSDE 설치 및 시동  (0) 2010.03.12
OSQL의 시동  (0) 2010.03.12
adb op for sqlite3  (0) 2010.02.09
Posted by jazzlife
,

MSDE 설치 및 시동

old/SQL 2010. 3. 12. 18:39

MSDE 는 기존 SQL 2000 에서 사용되는 것중에 저장 프로시저 등은 제약이 있습니다.
물론 DB 공간도 최대 2Gbyte 까지만 사용을 할 수 밖에 없다.


근데 간단한 사이트 또는 저용량의 DB 를 구현 한다면, 매우 유용하게 사용 할 수 있다.

1. 설치
C:\SQL2KSP4 의 위치에 서비스팩이 위치해 있습니다.

C:\SQL2KSP4\MSDE\setup.exe sapwd=1234 disablenetworkprotocols=0 securitymode=sql
-> 한줄로 쭉~ 붙여 쓰세요..
-> SAPWD : SQL 서버의 system admin(sa)의 로그인 암호입니다.
-> DISABLENETWORKPROTOCOLS :
         
DISABLENETWORKPROTOCOLS=1로 설치하거나
         DISABLENETWORKPROTOCOLS 옵션을 넣지 않았을 경우 해당 시스템 외의 다른
         컴퓨터나 다른 서버스에서
SQL Server(MSDE)로 접근을 하지 못하게 됩니다.
-> SECURITYMODE :
         
SECURITYMODE=SQL 옵션을 주지 않을 경우 윈도우즈
인증 모드로 MSDE가 설치
         되며
이로 인해 몇몇 서비스가 SQL서버에 로그인을 하지 못하는 경우도 발생합니다.


2. osql.exe 유틸 사용을 취한 접속

-> SQL Service Manager를 실행하여 서버를 구동한 후

osql.exe -U sa -P sa암호
-> osql.exe 는 초기 암호 설정 시나 기타 간다난 사항 셋팅 시에 사용하면 편리합니다.
-> 그외 다른 사항은 외부에서 Entermanager 로 MSDE 에 접속하면 기존 SQL 서버와 같이
   보이기 때문에 그리 걱정 안하셔도 됩니다.

'old > SQL' 카테고리의 다른 글

산술 연산자  (0) 2010.03.12
WHERE절  (0) 2010.03.12
SQL의 기본  (0) 2010.03.12
OSQL의 시동  (0) 2010.03.12
adb op for sqlite3  (0) 2010.02.09
Posted by jazzlife
,

OSQL의 시동

old/SQL 2010. 3. 12. 18:30

* 설치폴더에 있는 osql.exe의 path를 환경변수에 등록하여 어디서나 실행되게 하자.

1) SQL Server Manager를 구동한다.

2) osql -U 유저아이디 -P 패스워드

'old > SQL' 카테고리의 다른 글

산술 연산자  (0) 2010.03.12
WHERE절  (0) 2010.03.12
SQL의 기본  (0) 2010.03.12
MSDE 설치 및 시동  (0) 2010.03.12
adb op for sqlite3  (0) 2010.02.09
Posted by jazzlife
,

adb op for sqlite3

old/SQL 2010. 2. 9. 16:42
[쉘 띄우기]
c:\adb shell
c:\adb -s emulator-5554 shell

[DB연결]
# sqlite3 /data/data/...../~.db
sqlite> .quit 또는 .exit

[DB나열]
sqlite> .databases

[Table 나열]
sqlite> .tables

[특정 Table의 index 나열]
sqlite> .indices ~

[테이블의 schema 보기]
sqlite> .schema ~
지정하지 않으면 전체 schema 나열

[출력 결과를 파일로 보내기]
sqlite> .output /data.../~.sql

[데이터 베이스 백업을 위한 덤프]
출력 대상 파일을 지정.
sqlite> .output /data...../~sql
테이블을 덤프
sqlite> .dump ~
콘솔화면에 뿌려보자
sqlite> .output stdout

[파일에 담긴 sql  스크립트의 실행]
sqlite> SELECT * FROM ~1;
sqlite> SELECT * FROM ~2;
sqlite> .read /data...../~.sql
sql스크립트를 실행하여 테이블 ~1과 ~2의 결과를 출력

[구분자를 이용하여 외부 자료 들여오기]
','로 구분되는 CSV 파일형식의 예
sqlite> .separator ,
sqlite> .import /data...../~.csv  ~<테이블명>

[명령 프롬프트에서 sql 명령 수행]
sqlite> .mode column
헤더로 찾기 on
sqlite> .header on
_id 11 전까지 필터링
sqlite> select * from ~ WHERE _id < 11;

[각 열의 너비 조정]
sqlite> .width 5 50

'old > SQL' 카테고리의 다른 글

산술 연산자  (0) 2010.03.12
WHERE절  (0) 2010.03.12
SQL의 기본  (0) 2010.03.12
MSDE 설치 및 시동  (0) 2010.03.12
OSQL의 시동  (0) 2010.03.12
Posted by jazzlife
,