[MYSQL] 명령어 모음

2007. 12. 5. 15:41

# root암호설정 - root로 로그인하여 해야함
% mysqladmin -u root password '변경암호'
% mysqladmin -u root -p기존암호 password '변경암호'


root암호변경설정
PLEASE REMEMBER TO SET A PASSWORD FOR THE MySQL root USER !
This is done with:
/usr/bin/mysqladmin -u root -p password 'new-password'
/usr/bin/mysqladmin -u root -h ns.dbakorea.pe.kr -p password 'new-password'


DB작업
DB생성: mysql> create database DB명 ( or % mysqladmin -u root -p create DB명 )
DB삭제: mysql> drop database DB명
DB사용: mysql> use DB명 (엄밀히 말하자면, 사용할 'default database'를 선택하는 것이다.)
DB변경: mysql> alter database db명 DEFAULT CHARACTER SET charset (4.1이상에서만 available)



This article comes from dbakorea.pe.kr (Leave this line as is) MySQL 연결
mysql -u 사용자 -p DB명 ( or % mysqladmin -u root -p drop DB명 )

데이터파일 실행(sql*loader기능)
mysql>load data infile "데이터파일" into table 테이블명 ;
데이터파일에서 컬럼구분은 탭문자, Null값은 /n로 입력
데이터파일의 위치는 /home/kang/load.txt 와 같이 절대경로로 지정할것.

질의 파일 실행
쉘프롬프트상에서
mysql -u 사용자 -p DB명 < 질의파일
or
mysql프롬프트상에서
mysql> source 질의파일

쉘프롬프트상에서 질의 실행
dbakorea@lion board]$ mysql mysql -u root -pxxxx -e \r
>        "INSERT INTO db VALUES(
>        'localhost', 'aaa', 'aaa',
>        'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y')"


사용자 생성 & 사용자에게 DB할당
shell> mysql --user=root -p mysql

mysql> INSERT INTO user VALUES('localhost','사용자',PASSWORD('비밀번호'),'Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y');
mysql> INSERT INTO user VALUES('%','사용자',PASSWORD('비밀번호'),'Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y');

mysql> INSERT INTO db(Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv) VALUES ('localhost','DB명','사용자','Y','Y','Y','Y','Y','Y');
mysql> INSERT INTO db(Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv) VALUES('%','DB명','사용자','Y','Y','Y','Y','Y','Y');

mysql> FLUSH PRIVILEGES; (or shell prompt: mysqladmin -u root -pxxxx reload)

CASE 2: GRANT명령을 이용한 사용자 생성(이 방법이 권장된다)
kang이라는 DB를 만들고, 이 DB를 아래에서 나열된 권한을 가진 kang이라는 사용자를 생성
create database kang;
grant SELECT,INSERT,UPDATE,DELETE,CREATE,DROP on kang.* to kang@localhost identified by 'kang';
grant SELECT,INSERT,UPDATE,DELETE,CREATE,DROP on kang.* to kang@'%' identified by 'kang';

mysql> create database kang;
Query OK, 1 row affected (0.00 sec)

mysql> grant SELECT,INSERT,UPDATE,DELETE,CREATE,DROP on kang.* to kang@localhost identified by 'kang';
Query OK, 0 rows affected (0.00 sec)

mysql> grant SELECT,INSERT,UPDATE,DELETE,CREATE,DROP on kang.* to kang@'%' identified by 'kang';
Query OK, 0 rows affected (0.01 sec)

mysql>

여러가지 명령정리
mysql> show variables;                               서버의 variables(설정사항)출력
mysql> show variables like 'have_inno%'                   조건에 맞는 variables만 출력
mysql> show databases;                               database목록
mysql> show tables;                                 현재DB의 테이블목록(temporary table은 출력하지 않음)
mysql> show tables from db명;                          지정된 db명이 소유한 테이블목록
mysql> show tables like 'mem%';                         조건에 맞는 테이블목록만 출력
mysql> show index from 테이블명;                        인덱스 보기
mysql> show columns from 테이블명;                       테이블구조(describe 테이블명, explain 테이블명)
mysql> show table status;                             현재 DB의 테이블들의 상태(row수,table type,row길이,..)
mysql> show table status from db명;                      지정된 DB의 테이블들의 상태(row수,table type,row길이,..)
mysql> show create table 테이블명;                       해당 테이블 생성 SQL문 출력
mysql> rename table 테이블1 to 테이블2;                   테이블명 변경(ALTER TABLE 테이블1 RENAME TO 테이블2)
mysql> rename table 테이블1 to 테이블2, 테이블3 to 테이블4;      rename multiple tables
mysql> rename table db1명.테이블명 to db2명.테이블명;          테이블을 다른 DB로 이동
mysql> alter table 테이블명 add 컬럼명 데이터타입;            컬럼추가
mysql> alter table 테이블명 del 컬럼명;                   컬럼제거
mysql> alter table 테이블명 modify 컬럼명 컬럼타입;           컬럼명에 지정된 컬럼타입의 변경
mysql> alter table 테이블명 change old컬럼명 new컬럼명 컬럼타입   컬럼명 변경
mysql> alter table 테이블명 type=innodb;                   테이블type변경
mysql> create table 테이블명(..) type=heap min_rows=10000;       10000row를 수용할 수 있을 만큼 메모리할당(heap type이므로)
mysql> select version();                             MySQL서버버전 출력
mysql> create table 테이블2 as select * from 테이블1;          테이블1과 동일한 테이블 생성(with 데이터, as는 생략가능)
mysql> create table 테이블2 as select * from 테이블1 where 1=2;   테이블1과 동일한 구조의 테이블 생성(without 데이터, 1=2는 0으로 할수도 있다.)
mysql> insert into 테이블2 select * from 테이블1;             테이블1의 데이터를 테이블2에 insert


테이블이 존재여부 파악
DROP TABLE IF EXISTS 테이블명;
CREATE TABLE 테이블명 (...);
프로그래밍 언어에서 COUNT(*)를 사용하여 질의가 성공하면 테이블이 존재함을 파악할 수 있다.
ISAM, MyISAM의 경우 COUNT(*)가 최적화되어 상관없으나, BDB, InnoDB의 경우 full scan이 발생하므로 사용하지 마라.
대신 select * from 테이블명 where 0; 을 사용하라. 질의가 성공하면 테이블이 존재하는 것이고, 아니면 존재하지 않는 것이다.



접속
mysql {-h 접속호스트} -u 사용자 -p 사용DB
-h로 다른 서버에 존재하는 MySQL접속시 다음과 같이 MySQL DB에 설정해줘야 한다.
mysql> INSERT INTO user VALUES('접근을 허용할 호스트ip','사용자',PASSWORD('비밀번호'),'Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y');
mysql> INSERT INTO db(Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv) VALUES('접근을 허용할 호스트ip','사용DB','사용자','Y','Y','Y','Y','Y','Y');
mysql> FLUSH PRIVILEGES; or 쉴프롬프트상에서 % mysqladmin -u root -p flush-privileges


검색조건(where)
regular expression을 지원하다니 신기하군..
mysql> select * from work where 열명 regexp "정규표현식";


백업 & 복구
mysqldump {-h 호스트} -u 사용자 -p DB명 > 백업파일
mysql {-h 호스트} -u 사용자 -p DB명 < 백업파일

mysqldump -u root -p --opt db_dbakorea > dbakorea.sql
mysqldump -u root -p --opt db_board | mysql ---host=remote-host -C database (상이한 머쉰)
mysql -u dbakorea -p db_dbakorea < dbakorea.sql

mysqldump -u root -p --opt db_dbakorea | mysql ---host=ns.dbakorea.pe.kr -C db_dbakorea

테이블 생성구문만을 화면에서 보려면 다음과 같이 --no-data를 사용한다. 테이블명을 생략하면 모든 테이블 출력
mysqldump -u 유저명 -p --no-data db명 테이블명

테이블 검사
isamchk

오라클 sysdate와 동일
insert into test values('12', now());

유닉스 time()함수 리턴값 사용
FROM_UNIXTIME(954788684)
UNIX_TIMESTAMP("2001-04-04 :04:04:04")

MySQL 디폴트 DB&로그파일 위치
/var/lib/mysql
/var/lib디렉토리는 여러 프로세스들이 사용하는 데이터를 저장하는 일종의 파일시스템상의 데이터베이스라고 볼 수 있다.

replace
해당 레코드 존재하면 update하고, 존재하지 않는다면 insert한다.(insert문법과 동일)
replace into test values('maddog','kang myung gyu')'

explain
explain 질의문: 지정한 질의문이 어떻게 실행될 건지를 보여줌
mysql> explain select u.uid, u.name, a.name from sm_user u, sm_addr a where u.uid=a.uid;
+-------+------+-----------------+-----------------+---------+-------+------+-------+
| table | type | possible_keys  | key         | key_len | ref  | rows | Extra |
+-------+------+-----------------+-----------------+---------+-------+------+-------+
| u   | ALL | PRIMARY      | NULL        |   NULL | NULL | 370 |     |
| a   | ref | sm_addr_uid_idx | sm_addr_uid_idx |    11 | u.uid |  11 |     |
+-------+------+-----------------+-----------------+---------+-------+------+-------+
2 rows in set (0.01 sec)


temporary table
크기가 큰 테이블에 있는 subset에 대한 질의라면 subset을 temporary table에 저장한 후 질의하는 것이 더 빠를 경우가 있다.
temporary table는 세션내에서만 유효하고(현재 사용자만이 볼수 있다는 뜻), 세션종료시 자동적으로 drop된다.

create temporary table (...);
create temporary table (...) type=heap;     디스크가 아닌 메모리에 테이블 생성

존재하는 permanent table의 테이블명과 동일하게 생성할 수 있으며,
temporary table은 permanent table보다 우선시되어 처리된다.
4.0.7의 감마버전에서 테스트하면 결과는 약간 달라진다. 버그인건지..

mysql> create table test (id varchar(10));
Query OK, 0 rows affected (0.01 sec)

mysql> insert into test values('dbakorea');
Query OK, 1 row affected (0.00 sec)

mysql> create temporary table test(id varchar(10));
Query OK, 0 rows affected (0.00 sec)

mysql> select * from test;
Empty set (0.00 sec)

mysql> drop table test;
Query OK, 0 rows affected (0.00 sec)

mysql> select * from test;
+----------+
| id     |
+----------+
| dbakorea |
+----------+
1 row in set (0.00 sec)



Table Type에 다른 Files on Disk

ISAM  .frm (definition) .ISD (data) .ISM (indexes)
MyISAM .frm (definition) .MYD (data) .MYI (indexes)
MERGE .frm (definition) .MRG (list of constituent MyISAM table names)
HEAP  .frm (definition)
BDB   .frm (definition) .db (data and indexes)
InnoDB .frm (definition)

보통 mysqldump를 사용하여 백업을 수행하여 다른 DB서버에 데이터를 restore하면 된다.
MySQL은 별다른 작업없이 데이터파일을 단순히 복사(copy)하는 것만으로도 다른 서버에
DB을 이동시킬 수 있다. 하지만, 이런 방식이 지원되지 않는 table type도 있다.

ISAM: machine-dependent format하기때문에..
BDB : .db파일에 이미 테이블위치가 encode되어 있기때문에..
MyISAM, InnoDB, MERGE :가능(machine-independent format)

별다른 지정을 하지 않았다면 디폴트 TABLE type이 MyISAM이므로, 무난히 migration할 수 있다.
floating-point컬럼(FLOAT,DOUBLE)이 있다면 이러한 방식이 실패할 수 도 있다.

쉘에서는 mysql이 되는데 PHP에서 mysql.sock error를 내면서 MySQL이 안되는 경우
mysql.sock은 /tmp 아니면 /var/lib/mysql에 생기게 된다.
나의 경우, /var/lib/mysql에 mysql.sock파일이 있는데 PHP에서는 /tmp에서 찾으려하면서 에러를 발생했다.
/usr/bin/safe_mysqld파일에서 다음과 같이 수정한다.
주석(#)이 달린 것이 원래것이고 그 밑에 있는것이 수정한 것이다.

# MYSQL_UNIX_PORT=${MYSQL_UNIX_PORT:-/var/lib/mysql/mysql.sock}
MYSQL_UNIX_PORT=${MYSQL_UNIX_PORT:-/tmp/mysql.sock}

위와 같이 하니 /usr/bin/mysql이 /var/lib/mysql/mysql.sock에서 소켓파일을 찾으려 했다.
socket file을 지정하는 --socket이라는 옵션으로 다음과 같이 지정하면 된다.

mysql --socket=/tmp/mysql.sock -u dbakorea -p db_test

하지만 mysql실행시마다 이렇게 써줘야한다는 것이 상당히 귀찮다. 옵션이 바로 적용되게 설정하자.
mysql은 설정사항을 다음 3가지 파일에서 검색한다.

/etc/my.cnf        global options(MySQL 전체적으로 사용되는 옵션 정의)
mysql-data-dir/my.cnf 특정 DB에 적용되는 option (/var/lib/mysql/my.cnf)
~/.my.cnf         사용자 각각의 설정('~'문자는 사용자의 홈디렉토리는 의미)

/usr/share/mysql디렉토리에 예제가 있으므로 참고한다.
소켓파일의 지정은 다음줄을 넣어주면 된다.

socket       = /tmp/mysql.sock


== /etc/my.cnf예 ==
# The following options will be passed to all MySQL clients
[client]
#password     = your_password
port        = 3306
socket       = /tmp/mysql.sock

# Here follows entries for some specific programs

# The MySQL server
[mysqld]
port        = 3306
socket       = /tmp/mysql.sock



MySQL에서 통계처리시
orderby, groupby 는 sort_buffer를 늘여준다.(show variables)

live table(smslog)에서 모든 질의를 처리하지 말고 summary table에 질의결과를 저장해 재질의 처리한다.
summary table이 heap-type table가 가능한지 확인할 것.

INSERT INTO tblTemp2 (fldID) SELECT tblTemp1.fldOrder_ID FROM tblTemp1 WHERE
   tblTemp1.fldOrder_ID > 100;


join이 subselect보다 빠르다.
join시 사용되는 컬럼은 동일한 column type과 길이를 가져야만 최적의 속도를 보장한다.
즉, 동일 column type이지만 길이가 다르다면(char(11), char(10)), 동일한 컬럼도메인으로 변경해주는 것이 좋다.
where의 in은 optimize되어 있으므로 빠르다
insert,select는 동시에 수행가능하다.(어떻게?)
explain으로 질의과정 점검


varchar to/from char
conversion varchar를 char로 변경할 경우 모든 컬럼타입을 동시에 변경해야 한다.
반대의 경우, 하나만 char->charchar변경시 다른 모든 컬럼도 varchar로 변경됨
참.. 특이하구만..

mysql> CREATE TABLE chartbl (name VARCHAR(40), address VARCHAR(80));
Query OK, 0 rows affected (0.05 sec)

mysql> desc chartbl;
+---------+-------------+------+-----+---------+-------+
| Field  | Type     | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| name   | varchar(40) | YES |   | NULL   |     |
| address | varchar(80) | YES |   | NULL   |     |
+---------+-------------+------+-----+---------+-------+
2 rows in set (0.03 sec)

mysql> alter table chartbl modify name char(40);
Query OK, 0 rows affected (0.02 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> desc chartbl;
+---------+-------------+------+-----+---------+-------+
| Field  | Type     | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| name   | varchar(40) | YES |   | NULL   |     |
| address | varchar(80) | YES |   | NULL   |     |
+---------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql> alter table chartbl modify name char(40), modify address char(80);
Query OK, 0 rows affected (0.01 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> desc chartbl;
+---------+----------+------+-----+---------+-------+
| Field  | Type   | Null | Key | Default | Extra |
+---------+----------+------+-----+---------+-------+
| name   | char(40) | YES |   | NULL   |     |
| address | char(80) | YES |   | NULL   |     |
+---------+----------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql>


"For each article, find the dealer(s) with the most expensive price."

표준안
   SELECT article, dealer, price
   FROM  shop s1
   WHERE price=(SELECT MAX(s2.price)
             FROM shop s2
             WHERE s1.article = s2.article);

수정안(최적화)
   CREATE TEMPORARY TABLE tmp (
         article INT(4) UNSIGNED ZEROFILL DEFAULT '0000' NOT NULL,
         price  DOUBLE(16,2)         DEFAULT '0.00' NOT NULL);

   LOCK TABLES shop read;

   INSERT INTO tmp SELECT article, MAX(price) FROM shop GROUP BY article;

   SELECT shop.article, dealer, shop.price FROM shop, tmp
   WHERE shop.article=tmp.article AND shop.price=tmp.price;

   UNLOCK TABLES;

   DROP TABLE tmp;



==============================================================================
MySQL 특성정리
==============================================================================
primary key, foreign key지원
index 지원(15개컬럼, 256byte까지)
MySQL에서의 Stored Script개념 => SQL server language
commit-rollback개념 => lock tables(lock table test write -> 트랜잭션.. -> unlock tables)
컬럼명길이: 64자까지, 컬럼 Alias: 256자까지
not case-sensitive: keywords, functions, column, index명
case-sensitive: database, table, alias명
키워드,함수명은 대소문자구별이 없지만, db명과 table명은 Unix계열이라면 case-sensitive하다.
(이는 오브젝트명이 OS의 fs에 따라 저장되기 때문이다. 서버의 lower_case_table_names 변수를
1로 설정하면 오브젝트명은 모두 소문자로 저장되므로 유닉스-윈도간 호환성을 높일 수 있다.

지원되지 않는 부분:
Stored Procedure(5.0이상부터 지원된다고 함)
View(5.0이상부터 지원된다고 함)
Trigger(5.0이상부터 지원된다고 함)
subquery(4.1이상부터 지원된다고 함)
union, union all(4.0이상부터 지원됨)

[테이블 type에 따른 인덱스 특성]
Index Characteristic        ISAM   MyISAM         HEAP     BDB           InnoDB
NULL values allowed         No    Yes           As of 4.0.2 Yes           Yes
Columns per index          16    16            16       16            16
Indexes per table          16    32            32       31            32
Maximum index row size (bytes) 256   500           500      500/1024        500/1024
Index column prefixes allowed  Yes   Yes           Yes      Yes           No
BLOB/TEXT indexes allowed     No    Yes(255 bytes max) No       Yes (255 bytes max) No


인덱스 생성
- alter table을 이용한 인덱스 생성이 더 flexible함
- 인덱스명은 생략가능

ALTER TABLE 테이블명 ADD INDEX 인덱스명 (인덱스컬럼);
ALTER TABLE 테이블명 ADD UNIQUE 인덱스명 (인덱스컬럼);
ALTER TABLE 테이블명 ADD PRIMARY KEY (인덱스컬럼);
ALTER TABLE 테이블명 ADD FULLTEXT (인덱스컬럼);

CREATE INDEX 인덱스명 ON 테이블명 (인덱스컬럼);
CREATE UNIQUE INDEX 인덱스명 ON 테이블명 (인덱스컬럼);
CREATE FULLTEXT INDEX 인덱스명 ON 테이블명 (인덱스컬럼);

unique인덱스와 primary key인덱스와의 차이
unique은 null허용하지만, primary key는 null허용 안함
unique은 하나의 테이블에 여러개 올 수 있지만, primary key는 하나만 존재

테이블생성시 지정
CREATE TABLE 테이블명
(
... column declarations ...
INDEX 인덱스명 (인덱스컬럼),
UNIQUE 인덱스명 (인덱스컬럼),
PRIMARY KEY (인덱스컬럼),
FULLTEXT 인덱스명 (인덱스컬럼),
...

);


index prefix 생성
- 컬럼의 전체길이중 일부만 인덱스로 사용
- supported for ISAM, MyISAM, HEAP, and BDB tables, but not for InnoDB tables
- 지정되는 길이는 byte단위가 아닌 charater단위이므로, multi-byte character일 경우 주의
- blob, text 컬럼타입일 경우, index prefix 가 유용(255 길이까지 가능)

CREATE TABLE 테이블명
(
name CHAR(30) NOT NULL,
address CHAR(60) NOT NULL,
INDEX (name(10),address(10))
);


인덱스 삭제
DROP INDEX 인덱스명 ON 테이블명;
ALTER TABLE 테이블명 DROP INDEX 인덱스명;
ALTER TABLE 테이블명 DROP PRIMARY KEY;


outer join

[MySQL]
left outer joing : SELECT t1.*, t2.* FROM t1 LEFT OUTER JOIN t2 ON t1.i1 = t2.i2;
right outer joing: SELECT t1.*, t2.* FROM t1 RIGHT OUTER JOIN t2 ON t1.i1 = t2.i2;

[Oracle]
left outer joing : SELECT t1.*, t2.* FROM t1, t2 where t1.i1 = t2.i2(+);
right outer joing: SELECT t1.*, t2.* FROM t1, t2 where t1.i1(+) = t2.i2;

SELECT
student.name, student.student_id,
event.date, event.event_id, event.type
FROM
student, event
LEFT JOIN score ON student.student_id = score.student_id
       AND event.event_id = score.event_id
WHERE
score.score IS NULL
ORDER BY
student.student_id, event.event_id;


:= 문장을 이용한 변수의 설정

현재 dbakorea의 데이터베이스강좌게시판에 등록된 총 게시물은 43개이다. 43개의 강좌를 읽은 수(hit수)는 각각 다르다.
평균 hit수를 구해 보자.

mysql> select @total_hit := sum(hit), @total_record := count(*) from zetyx_board_database;
+------------------------+---------------------------+
| @total_hit := sum(hit) | @total_record := count(*) |
+------------------------+---------------------------+
|             3705 |                43 |
+------------------------+---------------------------+
1 row in set (0.00 sec)

mysql> select @total_hit/@total_record as 평균HIT;
+-----------------+
| 평균HIT      |
+-----------------+
| 86.162790697674 |
+-----------------+
1 row in set (0.00 sec)



select substring(subject from 9) from zetyx_board_database where substring(subject, 1, 8) = '[ORACLE]';


보통 상용DBMS들이 row-level locking을 지원한다. 쉽게 말해 레코드단위로 락킹한다는 말이다.
반면, MySQL의 MyISAM 테이블타입은 table-level locking을 사용한다.
쉽게 말하면, insert, update, delete작업은 전체 테이블에 락을 걸고 처리된다는 것이다.
row-level락보다 비효율적이지만,.. MySQL은 빠르기 때문에 이 단점이 상쇄된다.

Compressed MyISAM(packed MyISAM)
정적인 테이블데이터는 압축하여 20-60%정도의 공간을 절약할 수 있다.
Production데이터를 CD로 받아서 차후 디스크에 풀지 않고 CD자체로 바로 사용할 수도 있다.
gzip등으로 백업받으면 이를 푸는 과정이 필요할 것이다.
% myisampack dbakorea.myi

데이터베이스 게시판의 Merge Table에 좀 더 자세한 내용을 적어 두었다.


RAID Table
1개의 테이블은 OS상에 3개의 파일로 구성된다.
스키마파일(.frm), data파일(.myd), index파일(.myi)
MySQL의 RAID테이블은 데이터파일(.myd)을 여러개의 파일들로 구성하는 것이다.

create table raid_test (...)
type=myisam raid_type=striped raid_chunks=4 raid_chunsize=8

테이블을 4개의 데이터파일로 나누고, 8kb단위로(8kb stripe) 라운드로빈 방식으로 write가 이루어진다.
Posted by 나비:D
:
help_topic_id name help_category_id description example url
0 JOIN 6 MySQL supports the following JOIN syntaxes for the table_references part of SELECT statements and multiple-table DELETE and UPDATE statements: table_reference, table_reference table_reference [INNER | CROSS] JOIN table_reference [join_condition] table_reference STRAIGHT_JOIN table_reference table_reference LEFT [OUTER] JOIN table_reference join_condition table_reference NATURAL [LEFT [OUTER]] JOIN table_reference { OJ table_reference LEFT OUTER JOIN table_reference ON conditional_expr } table_reference RIGHT [OUTER] JOIN table_reference join_condition table_reference NATURAL [RIGHT [OUTER]] JOIN table_reference table_reference is defined as: tbl_name [[AS] alias] [[USE INDEX (key_list)] | [IGNORE INDEX (key_list)] | [FORCE INDEX (key_list)]] join_condition is defined as: ON conditional_expr | USING (column_list) mysql> SELECT table1.* FROM table1 -> LEFT JOIN table2 ON table1.id=table2.id -> WHERE table2.id IS NULL;  
1 HEX 23 HEX(N_or_S) If N_OR_S is a number, returns a string representation of the hexadecimal value of N, where N is a longlong (BIGINT) number. This is equivalent to CONV(N,10,16). From MySQL 4.0.1 and up, if N_OR_S is a string, returns a hexadecimal string of N_OR_S where each character in N_OR_S is converted to two hexadecimal digits. mysql> SELECT HEX(255); -> 'FF' mysql> SELECT 0x616263; -> 'abc' mysql> SELECT HEX('abc'); -> 616263  
2 REPLACE 23 REPLACE(str,from_str,to_str) Returns the string str with all occurrences of the string from_str replaced by the string to_str. mysql> SELECT REPLACE('www.mysql.com', 'w', 'Ww'); -> 'WwWwWw.mysql.com'  
3 REPEAT 23 REPEAT(str,count) Returns a string consisting of the string str repeated count times. If count <= 0, returns an empty string. Returns NULL if str or count are NULL. mysql> SELECT REPEAT('MySQL', 3); -> 'MySQLMySQLMySQL'  
4 CONTAINS 11 Contains(g1,g2) Returns 1 or 0 to indicate whether or not g1 completely contains g2.    
5 SRID 19 SRID(g) Returns an integer indicating the Spatial Reference System ID for the geometry value g. In MySQL, the SRID value is just an integer associated with the geometry value. All calculations are done assuming Euclidean (planar) geometry. mysql> SELECT SRID(GeomFromText('LineString(1 1,2 2)',101)); +-----------------------------------------------+ | SRID(GeomFromText('LineString(1 1,2 2)',101)) | +-----------------------------------------------+ | 101 | +-----------------------------------------------+  
6 CURRENT_TIMESTAMP 14 CURRENT_TIMESTAMP CURRENT_TIMESTAMP() CURRENT_TIMESTAMP and CURRENT_TIMESTAMP() are synonyms for NOW().    
7 VARIANCE 12 VARIANCE(expr) Returns the population standard variance of expr. This is an extension to standard SQL, available in MySQL 4.1 or later. As of MySQL 5.0.3, the standard SQL function VAR_POP() can be used instead.    
8 VAR_SAMP 12 VAR_SAMP(expr) Returns the sample variance of expr. That is, the denominator is the number of rows minus one. This function was added in MySQL 5.0.3.    
9 CONCAT 23 CONCAT(str1,str2,...) Returns the string that results from concatenating the arguments. Returns NULL if any argument is NULL. May have one or more arguments. If all arguments are non-binary strings, the result is a non-binary string. If the arguments include any binary strings, the result is a binary string. A numeric argument is converted to its equivalent binary string form. mysql> SELECT CONCAT('My', 'S', 'QL'); -> 'MySQL' mysql> SELECT CONCAT('My', NULL, 'QL'); -> NULL mysql> SELECT CONCAT(14.3); -> '14.3'  
10 GEOMETRY HIERARCHY 24 Geometry is the base class. It's an abstract class. The instantiable subclasses of Geometry are restricted to zero-, one-, and two-dimensional geometric objects that exist in two-dimensional coordinate space. All instantiable geometry classes are defined so that valid instances of a geometry class are topologically closed (that is, all defined geometries include their boundary). The base Geometry class has subclasses for Point, Curve, Surface, and GeometryCollection: --- Point represents zero-dimensional objects. --- Curve represents one-dimensional objects, and has subclass LineString, with sub-subclasses Line and LinearRing. --- Surface is designed for two-dimensional objects and has subclass Polygon. --- GeometryCollection has specialized zero-, one-, and two-dimensional collection classes named MultiPoint, MultiLineString, and MultiPolygon for modeling geometries corresponding to collections of Points, LineStrings, and Polygons, respectively. MultiCurve and MultiSurface are introduced as abstract superclasses that generalize the collection interfaces to handle Curves and Surfaces. Geometry, Curve, Surface, MultiCurve, and MultiSurface are defined as non-instantiable classes. They define a common set of methods for their subclasses and are included for extensibility. Point, LineString, Polygon, GeometryCollection, MultiPoint, MultiLineString, and MultiPolygon are instantiable classes.    
11 CHAR FUNCTION 23 CHAR(N,...) CHAR() interprets the arguments as integers and returns a string consisting of the characters given by the code values of those integers. NULL values are skipped. mysql> SELECT CHAR(77,121,83,81,'76'); -> 'MySQL' mysql> SELECT CHAR(77,77.3,'77.3'); -> 'MMM'  
12 DATETIME 1 A date and time combination. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59'. MySQL displays DATETIME values in 'YYYY-MM-DD HH:MM:SS' format, but allows you to assign values to DATETIME columns using either strings or numbers.    
13 LOWER 23 LOWER(str) Returns the string str with all characters changed to lowercase according to the current character set mapping (the default is ISO-8859-1 Latin1). mysql> SELECT LOWER('QUADRATICALLY'); -> 'quadratically'  
14 MONTH 14 MONTH(date) Returns the month for date, in the range 1 to 12. mysql> SELECT MONTH('1998-02-03'); -> 2  
15 TINYINT 1 TINYINT[(M)] [UNSIGNED] [ZEROFILL] A very small integer. The signed range is -128 to 127. The unsigned range is 0 to 255.    
16 ISCLOSED 18 IsClosed(ls) Returns 1 if the LineString value ls is closed (that is, its StartPoint() and EndPoint() values are the same). Returns 0 if ls is not closed, and -1 if it is NULL. mysql> SET @ls = 'LineString(1 1,2 2,3 3)'; mysql> SELECT IsClosed(GeomFromText(@ls)); +-----------------------------+ | IsClosed(GeomFromText(@ls)) | +-----------------------------+ | 0 | +-----------------------------+  
17 MASTER_POS_WAIT 21 MASTER_POS_WAIT(log_name,log_pos[,timeout]) This function is useful for control of master/slave synchronization. It blocks until the slave has read and applied all updates up to the specified position in the master log. The return value is the number of log events it had to wait for to get to the specified position. The function returns NULL if the slave SQL thread is not started, the slave's master information is not initialized, the arguments are incorrect, or an error occurs. It returns -1 if the timeout has been exceeded. If the slave SQL thread stops while MASTER_POS_WAIT() is waiting, the function returns NULL. If the slave is past the specified position, the function returns immediately. SELECT MASTER_POS_WAIT('master_log_file', master_log_pos)  
18 ^ 27 ^ Bitwise XOR: mysql> SELECT 1 ^ 1; -> 0 mysql> SELECT 1 ^ 0; -> 1 mysql> SELECT 11 ^ 3; -> 8  
19 DROP VIEW 24 DROP VIEW removes one or more views. You must have the DROP privilege for each view. You can use the keywords IF EXISTS to prevent an error from occurring for views that don't exist. When this clause is given, a NOTE is generated for each non-existent view. See also : [SHOW WARNINGS, , SHOW WARNINGS]. RESTRICT and CASCADE, if given, are parsed and ignored. DROP VIEW [IF EXISTS] view_name [, view_name] ... [RESTRICT | CASCADE]  
20 DATE OPERATIONS 14 DATE_ADD(date,INTERVAL expr type) DATE_SUB(date,INTERVAL expr type) These functions perform date arithmetic. date is a DATETIME or DATE value specifying the starting date. expr is an expression specifying the interval value to be added or subtracted from the starting date. expr is a string; it may start with a '-' for negative intervals. type is a keyword indicating how the expression should be interpreted. mysql> SELECT '1997-12-31 23:59:59' + INTERVAL 1 SECOND; -> '1998-01-01 00:00:00' mysql> SELECT INTERVAL 1 DAY + '1997-12-31'; -> '1998-01-01' mysql> SELECT '1998-01-01' - INTERVAL 1 SECOND; -> '1997-12-31 23:59:59' mysql> SELECT DATE_ADD('1997-12-31 23:59:59', -> INTERVAL 1 SECOND); -> '1998-01-01 00:00:00' mysql> SELECT DATE_ADD('1997-12-31 23:59:59', -> INTERVAL 1 DAY); -> '1998-01-01 23:59:59' mysql> SELECT DATE_ADD('1997-12-31 23:59:59', -> INTERVAL '1:1' MINUTE_SECOND); -> '1998-01-01 00:01:00' mysql> SELECT DATE_SUB('1998-01-01 00:00:00', -> INTERVAL '1 1:1:1' DAY_SECOND); -> '1997-12-30 22:58:59' mysql> SELECT DATE_ADD('1998-01-01 00:00:00', -> INTERVAL '-1 10' DAY_HOUR); -> '1997-12-30 14:00:00' mysql> SELECT DATE_SUB('1998-01-02', INTERVAL 31 DAY); -> '1997-12-02' mysql> SELECT DATE_ADD('1992-12-31 23:59:59.000002', -> INTERVAL '1.999999' SECOND_MICROSECOND); -> '1993-01-01 00:00:01.000001'  
21 WITHIN 11 Within(g1,g2) Returns 1 or 0 to indicate whether or not g1 is spatially within g2.    
22 WEEK 14 WEEK(date[,mode]) The function returns the week number for date. The two-argument form of WEEK() allows you to specify whether the week starts on Sunday or Monday and whether the return value should be in the range from 0 to 53 or from 1 to 53. If the mode argument is omitted, the value of the default_week_format system variable is used (or 0 before MySQL 4.0.14). See also : [Server system variables]. The following table describes how the mode argument works: First day Mode of week Range Week 1 is the first week... 0 Sunday 0-53 with a Sunday in this year 1 Monday 0-53 with more than 3 days this year 2 Sunday 1-53 with a Sunday in this year 3 Monday 1-53 with more than 3 days this year 4 Sunday 0-53 with more than 3 days this year 5 Monday 0-53 with a Monday in this year 6 Sunday 1-53 with more than 3 days this year 7 Monday 1-53 with a Monday in this year A mode value of 3 can be used as of MySQL 4.0.5. Values of 4 and above can be used as of MySQL 4.0.17. mysql> SELECT WEEK('1998-02-20'); -> 7 mysql> SELECT WEEK('1998-02-20',0); -> 7 mysql> SELECT WEEK('1998-02-20',1); -> 8 mysql> SELECT WEEK('1998-12-31',1); -> 53  
23 LOCK 10 LOCK TABLES locks tables for the current thread. If any of the tables are locked by other threads, it blocks until all locks can be acquired. UNLOCK TABLES releases any locks held by the current thread. All tables that are locked by the current thread are implicitly unlocked when the thread issues another LOCK TABLES, or when the connection to the server is closed. A table lock protects only against inappropriate reads or writes by other clients. The client holding the lock, even a read lock, can perform table-level operations such as DROP TABLE. LOCK TABLES tbl_name [AS alias] {READ [LOCAL] | [LOW_PRIORITY] WRITE} [, tbl_name [AS alias] {READ [LOCAL] | [LOW_PRIORITY] WRITE}] ... UNLOCK TABLES  
24 CHECK 7 Checks a table or tables for errors. CHECK TABLE works for MyISAM and InnoDB tables. For MyISAM tables, the key statistics are updated. As of MySQL 5.0.2, CHECK TABLE also can check views for problems, such as tables that are referenced in the view definition that no longer exist. CHECK TABLE tbl_name [, tbl_name] ... [option] ... option = {QUICK | FAST | MEDIUM | EXTENDED | CHANGED}  
25 RESET SLAVE 7 RESET SLAVE Makes the slave forget its replication position in the master's binary logs. This statement is meant to be used for a clean start: It deletes the *master.info and *relay-log.info files, all the relay logs, and starts a new relay log. Note: All relay logs are deleted, even if they have not been totally executed by the slave SQL thread. (This is a condition likely to exist on a replication slave if you have issued a STOP SLAVE statement or if the slave is highly loaded.) Connection information stored in the *master.info file is immediately reset using any values specified in the corresponding startup options. This information includes values such as master host, master port, master user, and master password. If the slave SQL thread was in the middle of replicating temporary tables when it was stopped, and RESET SLAVE is issued, these replicated temporary tables are deleted on the slave. This statement was named FLUSH SLAVE before MySQL 3.23.26.    
26 POLYGON 2 Polygon(ls1,ls2,...) Constructs a WKB Polygon value from a number of WKB LineString arguments. If any argument does not represent the WKB of a LinearRing (that is, not a closed and simple LineString) the return value is NULL.    
27 MINUTE 14 MINUTE(time) Returns the minute for time, in the range 0 to 59. mysql> SELECT MINUTE('98-02-03 10:05:03'); -> 5  
28 DAY 14 DAY(date) DAY() is a synonym for DAYOFMONTH(). It is available as of MySQL 4.1.1.    
29 MID 23 MID(str,pos,len) MID(str,pos,len) is a synonym for SUBSTRING(str,pos,len).    
30 REPLACE INTO 6 REPLACE works exactly like INSERT, except that if an old record in the table has the same value as a new record for a PRIMARY KEY or a UNIQUE index, the old record is deleted before the new record is inserted. See also : [INSERT, ,INSERT]. Note that unless the table has a PRIMARY KEY or UNIQUE index, using a REPLACE statement makes no sense. It becomes equivalent to INSERT, because there is no index to be used to determine whether a new row duplicates another. Values for all columns are taken from the values specified in the REPLACE statement. Any missing columns are set to their default values, just as happens for INSERT. You can't refer to values from the current row and use them in the new row. If you use an assignment such as SET col_name = col_name + 1, the reference to the column name on the right hand side is treated as DEFAULT(col_name), so the assignment is equivalent to SET col_name = DEFAULT(col_name) + 1. To be able to use REPLACE, you must have INSERT and DELETE privileges for the table. REPLACE [LOW_PRIORITY | DELAYED] [INTO] tbl_name [(col_name,...)] VALUES ({expr | DEFAULT},...),(...),...  
31 UUID 21 UUID() Returns a Universal Unique Identifier (UUID) generated according to ``DCE 1.1: Remote Procedure Call'' (Appendix A) CAE (Common Applications Environment) Specifications published by The Open Group in October 1997 (Document Number C706). A UUID is designed as a number that is globally unique in space and time. Two calls to UUID() are expected to generate two different values, even if these calls are performed on two separate computers that are not connected to each other. A UUID is a 128-bit number represented by a string of five hexadecimal numbers in aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee format: --- The first three numbers are generated from a timestamp. --- The fourth number preserves temporal uniqueness in case the timestamp value loses monotonicity (for example, due to daylight saving time). --- The fifth number is an IEEE 802 node number that provides spatial uniqueness. A random number is substituted if the latter is not available (for example, because the host computer has no Ethernet card, or we do not know how to find the hardware address of an interface on your operating system). In this case, spatial uniqueness cannot be guaranteed. Nevertheless, a collision should have /very/ low probability. Currently, the MAC address of an interface is taken into account only on FreeBSD and Linux. On other operating systems, MySQL uses a randomly generated 48-bit number. mysql> SELECT UUID(); -> '6ccd780c-baba-1026-9564-0040f4311e29'  
32 LINESTRING 2 LineString(pt1,pt2,...) Constructs a WKB LineString value from a number of WKB Point arguments. If any argument is not a WKB Point, the return value is NULL. If the number of Point arguments is less than two, the return value is NULL.    
33 CONNECTION_ID 25 CONNECTION_ID() Returns the connection ID (thread ID) for the connection. Every connection has its own unique ID. mysql> SELECT CONNECTION_ID(); -> 23786  
34 DELETE 6 DELETE deletes rows from tbl_name that satisfy the condition given by where_definition, and returns the number of records deleted. If you issue a DELETE statement with no WHERE clause, all rows are deleted. A faster way to do this, when you don't want to know the number of deleted rows, is to use TRUNCATE TABLE. See also : [TRUNCATE, , TRUNCATE]. DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM tbl_name [WHERE where_definition] [ORDER BY ...] [LIMIT row_count]  
35 ROUND 4 ROUND(X) ROUND(X,D) Returns the argument X, rounded to the nearest integer. With two arguments, returns X rounded to D decimals. D can be negative to round D digits left of the decimal point of the value X. mysql> SELECT ROUND(-1.23); -> -1 mysql> SELECT ROUND(-1.58); -> -2 mysql> SELECT ROUND(1.58); -> 2 mysql> SELECT ROUND(1.298, 1); -> 1.3 mysql> SELECT ROUND(1.298, 0); -> 1 mysql> SELECT ROUND(23.298, -1); -> 20  
36 NULLIF 9 NULLIF(expr1,expr2) Returns NULL if expr1 = expr2 is true, else returns expr1. This is the same as CASE WHEN expr1 = expr2 THEN NULL ELSE expr1 END. mysql> SELECT NULLIF(1,1); -> NULL mysql> SELECT NULLIF(1,2); -> 1  
37 STOP SLAVE 7 STOP SLAVE [thread_type [, thread_type] ... ] thread_type: IO_THREAD | SQL_THREAD Stops the slave threads. STOP SLAVE requires the SUPER privilege. Like START SLAVE, as of MySQL 4.0.2, this statement may be used with the IO_THREAD and SQL_THREAD options to name the thread or threads to stop.    
38 TIMEDIFF 14 TIMEDIFF(expr,expr2) TIMEDIFF() returns the time between the start time expr and the end time expr2. expr and expr2 are time or date-and-time expressions, but both must be of the same type. mysql> SELECT TIMEDIFF('2000:01:01 00:00:00', -> '2000:01:01 00:00:00.000001'); -> '-00:00:00.000001' mysql> SELECT TIMEDIFF('1997-12-31 23:59:59.000001', -> '1997-12-30 01:01:01.000002'); -> '46:58:57.999999'  
39 RELATED 11 Related(g1,g2,pattern_matrix) Returns 1 or 0 to indicate whether or not the spatial relationship specified by pattern_matrix exists between g1 and g2. Returns -1 if the arguments are NULL. The pattern matrix is a string. Its specification will be noted here if this function is implemented.    
40 LINEFROMTEXT 3 LineFromText(wkt[,srid]) LineStringFromText(wkt[,srid]) Constructs a LINESTRING value using its WKT representation and SRID.    
41 SHOW MASTER STATUS 6 SHOW MASTER STATUS Provides status information on the binary log files of the master.    
42 ADDTIME 14 ADDTIME(expr,expr2) ADDTIME() adds expr2 to expr and returns the result. expr is a time or datetime expression, and expr2 is a time expression. mysql> SELECT ADDTIME('1997-12-31 23:59:59.999999', -> '1 1:1:1.000002'); -> '1998-01-02 01:01:01.000001' mysql> SELECT ADDTIME('01:00:00.999999', '02:00:00.999998'); -> '03:00:01.999997'  
43 SPATIAL 24 MySQL can create spatial indexes using syntax similar to that for creating regular indexes, but extended with the SPATIAL keyword. Spatial columns that are indexed currently must be declared NOT NULL. The following examples demonstrate how to create spatial indexes. With CREATE TABLE: mysql> CREATE TABLE geom (g GEOMETRY NOT NULL, SPATIAL INDEX(g)); With ALTER TABLE: mysql> ALTER TABLE geom ADD SPATIAL INDEX(g); With CREATE INDEX: mysql> CREATE SPATIAL INDEX sp_index ON geom (g); To drop spatial indexes, use ALTER TABLE or DROP INDEX: With ALTER TABLE: mysql> ALTER TABLE geom DROP INDEX g; With DROP INDEX: mysql> DROP INDEX sp_index ON geom; Example: Suppose that a table geom contains more than 32,000 geometries, which are stored in the column g of type GEOMETRY. The table also has an AUTO_INCREMENT column fid for storing object ID values.    
44 TIMESTAMPDIFF 14 TIMESTAMPDIFF(interval,datetime_expr1,datetime_expr2) Returns the integer difference between the date or datetime expressions datetime_expr1 and datetime_expr2. The unit for the result is given by the interval argument. The legal values for interval are the same as those listed in the description of the TIMESTAMPADD() function.    
45 UPPER 23 UPPER(str) Returns the string str with all characters changed to uppercase according to the current character set mapping (the default is ISO-8859-1 Latin1). mysql> SELECT UPPER('Hej'); -> 'HEJ'  
46 FROM_UNIXTIME 14 FROM_UNIXTIME(unix_timestamp) FROM_UNIXTIME(unix_timestamp,format) Returns a representation of the unix_timestamp argument as a value in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS format, depending on whether the function is used in a string or numeric context. mysql> SELECT FROM_UNIXTIME(875996580); -> '1997-10-04 22:23:00' mysql> SELECT FROM_UNIXTIME(875996580) + 0; -> 19971004222300 If format is given, the result is formatted according to the format string. format may contain the same specifiers as those listed in the entry for the DATE_FORMAT() function. mysql> SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(), -> '%Y %D %M %h:%i:%s %x'); -> '2003 6th August 06:22:58 2003'  
47 MEDIUMBLOB 1 MEDIUMBLOB A BLOB column with a maximum length of 16,777,215 (2^24 - 1) bytes.    
48 IFNULL 9 IFNULL(expr1,expr2) If expr1 is not NULL, IFNULL() returns expr1, else it returns expr2. IFNULL() returns a numeric or string value, depending on the context in which it is used. mysql> SELECT IFNULL(1,0); -> 1 mysql> SELECT IFNULL(NULL,10); -> 10 mysql> SELECT IFNULL(1/0,10); -> 10 mysql> SELECT IFNULL(1/0,'yes'); -> 'yes'  
49 LEAST 26 LEAST(value1,value2,...) With two or more arguments, returns the smallest (minimum-valued) argument. The arguments are compared using the following rules. --- If the return value is used in an INTEGER context or all arguments are integer-valued, they are compared as integers. --- If the return value is used in a REAL context or all arguments are real-valued, they are compared as reals. --- If any argument is a case-sensitive string, the arguments are compared as case-sensitive strings. --- In other cases, the arguments are compared as case-insensitive strings. mysql> SELECT LEAST(2,0); -> 0 mysql> SELECT LEAST(34.0,3.0,5.0,767.0); -> 3.0 mysql> SELECT LEAST('B','A','C'); -> 'A'  
50 = 26 = Equal: mysql> SELECT 1 = 0; -> 0 mysql> SELECT '0' = 0; -> 1 mysql> SELECT '0.0' = 0; -> 1 mysql> SELECT '0.01' = 0; -> 0 mysql> SELECT '.01' = 0.01; -> 1  
51 REVERSE 23 REVERSE(str) Returns the string str with the order of the characters reversed. mysql> SELECT REVERSE('abc'); -> 'cba'  
52 ISNULL 26 ISNULL(expr) If expr is NULL, ISNULL() returns 1, otherwise it returns 0. mysql> SELECT ISNULL(1+1); -> 0 mysql> SELECT ISNULL(1/0); -> 1  
53 BINARY 1 BINARY(M) The BINARY type is similar to the CHAR type, but stores binary byte strings rather than non-binary character strings. This type was added in MySQL 4.1.2.    
54 BOUNDARY 19 Boundary(g) Returns a geometry that is the closure of the combinatorial boundary of the geometry value g.    
55 CREATE USER 7 The CREATE USER statement creates new MySQL accounts. To use it, you must have the global CREATE USER privilege or the INSERT privilege for the mysql database. For each account, CREATE USER creates a new record in the mysql.user table that has no privileges. An error occurs if the account already exists. The account can be given a password with the optional IDENTIFIED BY clause. The user value and the password are given the same way as for the GRANT statement. In particular, to specify the password in plain text, omit the PASSWORD keyword. To specify the password as the hashed value as returned by the PASSWORD() function, include the keyword PASSWORD. See also : [GRANT, , GRANT]. The CREATE USER statement was added in MySQL 5.0.2. @subsubsection DROP USER Syntax DROP USER user [, user] ... The DROP USER statement deletes one or more MySQL accounts. To use it, you must have the global CREATE USER privilege or the DELETE privilege for the mysql database. Each account is named using the same format as for GRANT or REVOKE; for example, 'jeffrey'@@'localhost'. The user and host parts of the account name correspond to the User and Host column values of the user table record for the account. DROP USER was added in MySQL 4.1.1 and originally removed only accounts that have no privileges. In MySQL 5.0.2, it was modified to also remove account privileges. This means that the procedure for removing an account depends on your version of MySQL. As of MySQL 5.0.2, remove an account and its privileges as follows: DROP USER user; The statement removes privilege records for the account from all grant tables. From MySQL 4.1.1 to 5.0.1, DROP USER deletes only MySQL accounts that don't have any privileges. In these MySQL versions, it serves only to remove each account record from the user table. To remove a MySQL account, you should use the following procedure, performing the steps in the order shown: @enumerate --- Use SHOW GRANTS to determine what privileges the account has. See also : [SHOW GRANTS, , SHOW GRANTS]. --- Use REVOKE to revoke the privileges displayed by SHOW GRANTS. This removes records for the account from all the grant tables except the user table, and revokes any global privileges listed in the user table. See also : [GRANT, , GRANT]. --- Delete the account by using DROP USER to remove the user table record. @end enumerate DROP USER does not automatically close any open user sessions. Rather, in the event that a user with an open session is dropped, the command does not take effect until that user's session is closed. Once the session is closed, the user is dropped, and that user's next attempt to log in will fail. This is by design. Before MySQL 4.1.1, DROP USER is not available. You should first revoke the account privileges as just described. Then delete the user table record and flush the grant tables like this: mysql> DELETE FROM mysql.user -> WHERE User='user_name' and Host='host_name'; mysql> FLUSH PRIVILEGES; @subsubsection GRANT and REVOKE Syntax GRANT priv_type [(column_list)] [, priv_type [(column_list)]] ... ON [object_type] {tbl_name | * | *.* | db_name.*} TO user [IDENTIFIED BY [PASSWORD] 'password'] [, user [IDENTIFIED BY [PASSWORD] 'password']] ... [REQUIRE NONE | [{SSL| X509}] [CIPHER 'cipher' [AND]] [ISSUER 'issuer' [AND]] [SUBJECT 'subject']] [WITH with_option [with_option] ...] object_type = TABLE | FUNCTION | PROCEDURE with_option = GRANT OPTION | MAX_QUERIES_PER_HOUR count | MAX_UPDATES_PER_HOUR count | MAX_CONNECTIONS_PER_HOUR count | MAX_USER_CONNECTIONS count REVOKE priv_type [(column_list)] [, priv_type [(column_list)]] ... ON [object_type] {tbl_name | * | *.* | db_name.*} FROM user [, user] ... REVOKE ALL PRIVILEGES, GRANT OPTION FROM user [, user] ... The GRANT and REVOKE statements allow system administrators to create MySQL user accounts and to grant rights to and revoke them from accounts. GRANT and REVOKE are implemented in MySQL 3.22.11 or later. For earlier MySQL versions, these statements do nothing. MySQL account information is stored in the tables of the mysql database. This database and the access control system are discussed extensively in [MySQL Database Administration], which you should consult for additional details. If the grant tables contain privilege records that contain mixed-case database or table names and the lower_case_table_names system variable is set, REVOKE cannot be used to revoke the privileges. It will be necessary to manipulate the grant tables directly. (GRANT will not create such records when lower_case_table_names is set, but such records might have been created prior to setting the variable.) Privileges can be granted at several levels: Global level Global privileges apply to all databases on a given server. These privileges are stored in the mysql.user table. GRANT ALL ON *.* and REVOKE ALL ON *.* grant and revoke only global privileges. Database level Database privileges apply to all objects in a given database. These privileges are stored in the mysql.db and mysql.host tables. GRANT ALL ON db_name.* and REVOKE ALL ON db_name.* grant and revoke only database privileges. Table level Table privileges apply to all columns in a given table. These privileges are stored in the mysql.tables_priv table. GRANT ALL ON db_name.tbl_name and REVOKE ALL ON db_name.tbl_name grant and revoke only table privileges. Column level Column privileges apply to single columns in a given table. These privileges are stored in the mysql.columns_priv table. When using REVOKE, you must specify the same columns that were granted. Routine level The CREATE ROUTINE, ALTER ROUTINE, EXECUTE, and GRANT privileges apply to stored routines. They can be granted at the global and database levels. Also, except for CREATE ROUTINE, these privileges can be granted at the routine level for individual routines and are stored in the mysql.procs_priv table. The object_type clause was added in MySQL 5.0.6. It should be specified as TABLE, FUNCTION, or PROCEDURE when the following object is a table, a stored function, or a stored procedure. To use this clause when upgrading from a version of MySQL older than 5.0.6, you must upgrade your grant tables. See also : [Upgrading-grant-tables]. CREATE USER user [IDENTIFIED BY [PASSWORD] 'password'] [, user [IDENTIFIED BY [PASSWORD] 'password']] ...  
56 POINT 2 Point(x,y) Constructs a WKB Point using its coordinates.    
57 CURRENT_USER 25 CURRENT_USER() Returns the username and hostname combination that the current session was authenticated as. This value corresponds to the MySQL account that determines your access privileges. It can be different from the value of USER(). mysql> SELECT USER(); -> 'davida@localhost' mysql> SELECT * FROM mysql.user; ERROR 1044: Access denied for user ''@'localhost' to database 'mysql' mysql> SELECT CURRENT_USER(); -> '@localhost'  
58 LCASE 23 LCASE(str) LCASE() is a synonym for LOWER().    
59 <= 26 <= Less than or equal: mysql> SELECT 0.1 <= 2; -> 1  
60 UPDATE 6 The UPDATE statement updates columns in existing table rows with new values. The SET clause indicates which columns to modify and the values they should be given. The WHERE clause, if given, specifies which rows should be updated. Otherwise, all rows are updated. If the ORDER BY clause is specified, the rows are updated in the order that is specified. The LIMIT clause places a limit on the number of rows that can be updated. The UPDATE statement supports the following modifiers: --- If you specify the LOW_PRIORITY keyword, execution of the UPDATE is delayed until no other clients are reading from the table. --- If you specify the IGNORE keyword, the update statement does not abort even if errors occur during the update. Rows for which duplicate-key conflicts occur are not updated. Rows for which columns are updated to values that would cause data conversion errors are updated to the closet valid values instead. UPDATE [LOW_PRIORITY] [IGNORE] tbl_name SET col_name1=expr1 [, col_name2=expr2 ...] [WHERE where_definition] [ORDER BY ...] [LIMIT row_count]  
61 DROP INDEX 28 DROP INDEX drops the index named index_name from the table tbl_name. In MySQL 3.22 or later, DROP INDEX is mapped to an ALTER TABLE statement to drop the index. See also : [ALTER TABLE, , ALTER TABLE]. DROP INDEX doesn't do anything prior to MySQL 3.22. DROP INDEX index_name ON tbl_name  
62 MATCH AGAINST 23 As of MySQL 3.23.23, MySQL has support for full-text indexing and searching. A full-text index in MySQL is an index of type FULLTEXT. FULLTEXT indexes are used with MyISAM tables only and can be created from CHAR, VARCHAR, or TEXT columns at CREATE TABLE time or added later with ALTER TABLE or CREATE INDEX. For large datasets, it is much faster to load your data into a table that has no FULLTEXT index, then create the index with ALTER TABLE (or CREATE INDEX). Loading data into a table that has an existing FULLTEXT index could be significantly slower. mysql> SELECT id, body, MATCH (title,body) AGAINST -> ('Security implications of running MySQL as root') AS score -> FROM articles WHERE MATCH (title,body) AGAINST -> ('Security implications of running MySQL as root'); +----+-------------------------------------+-----------------+ | id | body | score | +----+-------------------------------------+-----------------+ | 4 | 1. Never run mysqld as root. 2. ... | 1.5219271183014 | | 6 | When configured properly, MySQL ... | 1.3114095926285 | +----+-------------------------------------+-----------------+ 2 rows in set (0.00 sec)  
63 ABS 4 ABS(X) Returns the absolute value of X. mysql> SELECT ABS(2); -> 2 mysql> SELECT ABS(-32); -> 32  
64 POLYFROMWKB 13 PolyFromWKB(wkb[,srid]) PolygonFromWKB(wkb[,srid]) Constructs a POLYGON value using its WKB representation and SRID.    
65 NOT LIKE 23 expr NOT LIKE pat [ESCAPE 'escape-char'] This is the same as NOT (expr LIKE pat [ESCAPE 'escape-char']).    
66 SPACE 23 SPACE(N) Returns a string consisting of N space characters. mysql> SELECT SPACE(6); -> ' '  
67 MBR DEFINITION 8 Every geometry occupies some position in space. The exterior of a geometry is all space not occupied by the geometry. The interior is the space occupied by the geometry. The boundary is the interface between the geometry's interior and exterior. --- Its MBR (Minimum Bounding Rectangle), or Envelope. This is the bounding geometry, formed by the minimum and maximum (X,Y) coordinates: ((MINX MINY, MAXX MINY, MAXX MAXY, MINX MAXY, MINX MINY))  
68 GEOMETRYCOLLECTION 2 GeometryCollection(g1,g2,...) Constructs a WKB GeometryCollection. If any argument is not a well-formed WKB representation of a geometry, the return value is NULL.    
69 * 4 * Multiplication: mysql> SELECT 3*5; -> 15 mysql> SELECT 18014398509481984*18014398509481984.0; -> 324518553658426726783156020576256.0 mysql> SELECT 18014398509481984*18014398509481984; -> 0  
70 TIMESTAMP 1 TIMESTAMP[(M)] A timestamp. The range is '1970-01-01 00:00:00' to partway through the year 2037. A TIMESTAMP column is useful for recording the date and time of an INSERT or UPDATE operation. The first TIMESTAMP column in a table is automatically set to the date and time of the most recent operation if you don't assign it a value yourself. You can also set any TIMESTAMP column to the current date and time by assigning it a NULL value. From MySQL 4.1 on, TIMESTAMP is returned as a string with the format 'YYYY-MM-DD HH:MM:SS'. If you want to obtain the value as a number, you should add +0 to the timestamp column. Different timestamp display widths are not supported. In MySQL 4.0 and earlier, TIMESTAMP values are displayed in YYYYMMDDHHMMSS, YYMMDDHHMMSS, YYYYMMDD, or YYMMDD format, depending on whether M is 14 (or missing), 12, 8, or 6, but allows you to assign values to TIMESTAMP columns using either strings or numbers. The M argument affects only how a TIMESTAMP column is displayed, not storage. Its values always are stored using four bytes each. From MySQL 4.0.12, the --new option can be used to make the server behave as in MySQL 4.1. Note that TIMESTAMP(M) columns where M is 8 or 14 are reported to be numbers, whereas other TIMESTAMP(M) columns are reported to be strings. This is just to ensure that you can reliably dump and restore the table with these types.    
71 DES_DECRYPT 17 DES_DECRYPT(crypt_str[,key_str]) Decrypts a string encrypted with DES_ENCRYPT(). On error, this function returns NULL. Note that this function works only if MySQL has been configured with SSL support. See also : [Secure connections]. If no key_str argument is given, DES_DECRYPT() examines the first byte of the encrypted string to determine the DES key number that was used to encrypt the original string, and then reads the key from the DES key file to decrypt the message. For this to work, the user must have the SUPER privilege. The key file can be specified with the --des-key-file server option. If you pass this function a key_str argument, that string is used as the key for decrypting the message. If the crypt_str argument doesn't look like an encrypted string, MySQL returns the given crypt_str.    
72 CHECKSUM 7 Reports a table checksum. If QUICK is specified, the live table checksum is reported if it is available, or NULL otherwise. This is very fast. A live checksum is enabled by specifying the CHECKSUM=1 table option, currently supported only for MyISAM tables. See also : [CREATE TABLE, , CREATE TABLE]. In EXTENDED mode the whole table is read row by row and the checksum is calculated. This can be very slow for large tables. By default, if neither QUICK nor EXTENDED is specified, MySQL returns a live checksum if the table storage engine supports it and scans the table otherwise. CHECKSUM TABLE returns NULL for non-existent tables. As of MySQL 5.0.3, a warning is generated for this condition. This statement is implemented in MySQL 4.1.1. @subsubsection OPTIMIZE TABLE Syntax OPTIMIZE [LOCAL | NO_WRITE_TO_BINLOG] TABLE tbl_name [, tbl_name] ... OPTIMIZE TABLE should be used if you have deleted a large part of a table or if you have made many changes to a table with variable-length rows (tables that have VARCHAR, BLOB, or TEXT columns). Deleted records are maintained in a linked list and subsequent INSERT operations reuse old record positions. You can use OPTIMIZE TABLE to reclaim the unused space and to defragment the data file. CHECKSUM TABLE tbl_name [, tbl_name] ... [ QUICK | EXTENDED ]  
73 ENDPOINT 18 EndPoint(ls) Returns the Point that is the end point of the LineString value ls. mysql> SET @ls = 'LineString(1 1,2 2,3 3)'; mysql> SELECT AsText(EndPoint(GeomFromText(@ls))); +-------------------------------------+ | AsText(EndPoint(GeomFromText(@ls))) | +-------------------------------------+ | POINT(3 3) | +-------------------------------------+  
74 CACHE INDEX 6 The CACHE INDEX statement assigns table indexes to a specific key cache. It is used only for MyISAM tables. The following statement assigns indexes from the tables t1, t2, and t3 to the key cache named hot_cache: mysql> CACHE INDEX t1, t2, t3 IN hot_cache; +---------+--------------------+----------+----------+ | Table | Op | Msg_type | Msg_text | +---------+--------------------+----------+----------+ | test.t1 | assign_to_keycache | status | OK | | test.t2 | assign_to_keycache | status | OK | | test.t3 | assign_to_keycache | status | OK | +---------+--------------------+----------+----------+ CACHE INDEX tbl_index_list [, tbl_index_list] ... IN key_cache_name tbl_index_list: tbl_name [[INDEX|KEY] (index_name[, index_name] ...)]  
75 COMPRESS 23 COMPRESS(string_to_compress) Compresses a string. This function requires MySQL to have been compiled with a compression library such as zlib. Otherwise, the return value is always NULL. The compressed string can be uncompressed with UNCOMPRESS(). mysql> SELECT LENGTH(COMPRESS(REPEAT('a',1000))); -> 21 mysql> SELECT LENGTH(COMPRESS('')); -> 0 mysql> SELECT LENGTH(COMPRESS('a')); -> 13 mysql> SELECT LENGTH(COMPRESS(REPEAT('a',16))); -> 15  
76 COUNT 12 COUNT(expr) Returns a count of the number of non-NULL values in the rows retrieved by a SELECT statement. mysql> SELECT student.student_name,COUNT(*) -> FROM student,course -> WHERE student.student_id=course.student_id -> GROUP BY student_name;  
77 INSERT 23 INSERT(str,pos,len,newstr) Returns the string str, with the substring beginning at position pos and len characters long replaced by the string newstr. Returns the original string if pos is not within the length of the string. Replaces the rest of the string from position pos is len is not within the length of the rest of the string. Returns NULL if any argument is null. mysql> SELECT INSERT('Quadratic', 3, 4, 'What'); -> 'QuWhattic' mysql> SELECT INSERT('Quadratic', -1, 4, 'What'); -> 'Quadratic' mysql> SELECT INSERT('Quadratic', 3, 100, 'What'); -> 'QuWhat'  
78 HANDLER 6 The HANDLER statement provides direct access to table storage engine interfaces. It is available for MyISAM tables as MySQL 4.0.0 and InnoDB tables as of MySQL 4.0.3. HANDLER tbl_name OPEN [ AS alias ] HANDLER tbl_name READ index_name { = | >= | <= | < } (value1,value2,...) [ WHERE where_condition ] [LIMIT ... ] HANDLER tbl_name READ index_name { FIRST | NEXT | PREV | LAST } [ WHERE where_condition ] [LIMIT ... ] HANDLER tbl_name READ { FIRST | NEXT } [ WHERE where_condition ] [LIMIT ... ] HANDLER tbl_name CLOSE  
79 MLINEFROMTEXT 3 MLineFromText(wkt[,srid]) MultiLineStringFromText(wkt[,srid]) Constructs a MULTILINESTRING value using its WKT representation and SRID.    
80 GEOMCOLLFROMWKB 13 GeomCollFromWKB(wkb[,srid]) GeometryCollectionFromWKB(wkb[,srid]) Constructs a GEOMETRYCOLLECTION value using its WKB representation and SRID.    
81 RENAME TABLE 28 RENAME TABLE tbl_name TO new_tbl_name [, tbl_name2 TO new_tbl_name2] ... This statement renames one or more tables. It was added in MySQL 3.23.23. The rename operation is done atomically, which means that no other thread can access any of the tables while the rename is running. For example, if you have an existing table old_table, you can create another table new_table that has the same structure but is empty, and then replace the existing table with the empty one as follows: CREATE TABLE new_table (...); RENAME TABLE old_table TO backup_table, new_table TO old_table;  
82 BOOLEAN 1 BOOL BOOLEAN These are synonyms for TINYINT(1). The BOOLEAN synonym was added in MySQL 4.1.0. A value of zero is considered false. Non-zero values are considered true. In the future, full boolean type handling will be introduced in accordance with standard SQL.    
83 DEFAULT 21 DEFAULT(col_name) Returns the default value for a table column. Starting from MySQL 5.0.2, you get an error if the column doesn't have a default value. mysql> UPDATE t SET i = DEFAULT(i)+1 WHERE id < 100;  
84 TINYTEXT 1 TINYTEXT A TEXT column with a maximum length of 255 (2^8 - 1) characters.    
85 DECODE 17 DECODE(crypt_str,pass_str) Decrypts the encrypted string crypt_str using pass_str as the password. crypt_str should be a string returned from ENCODE().    
86 <=> 26 <=> NULL-safe equal. This operator performs an equality comparison like the = operator, but returns 1 rather than NULL if both operands are NULL, and 0 rather than NULL if one operand is NULL. mysql> SELECT 1 <=> 1, NULL <=> NULL, 1 <=> NULL; -> 1, 1, 0 mysql> SELECT 1 = 1, NULL = NULL, 1 = NULL; -> 1, NULL, NULL  
87 LOAD DATA FROM MASTER 6 LOAD DATA FROM MASTER Takes a snapshot of the master and copies it to the slave. It updates the values of MASTER_LOG_FILE and MASTER_LOG_POS so that the slave starts replicating from the correct position. Any table and database exclusion rules specified with the --replicate-*-do-* and --replicate-*-ignore-* options are honored. --replicate-rewrite-db is /not/ taken into account (because one user could, with this option, set up a non-unique mapping such as --replicate-rewrite-db=db1->db3 and --replicate-rewrite-db=db2->db3, which would confuse the slave when it loads the master's tables). Use of this statement is subject to the following conditions: --- It works only with MyISAM tables. Attempting to load a non-MyISAM table results in the error: ERROR 1189 (08S01): Net error reading from master --- It acquires a global read lock on the master while taking the snapshot, which prevents updates on the master during the load operation. In the future, it is planned to make this statement work with InnoDB tables and to remove the need for a global read lock by using non-blocking online backup. If you are loading big tables, you might have to increase the values of net_read_timeout and net_write_timeout on both your master and slave servers. See also : [Server system variables]. Note that LOAD DATA FROM MASTER does /not/ copy any tables from the mysql database. This makes it easy to have different users and privileges on the master and the slave. The LOAD DATA FROM MASTER statement requires the replication account that is used to connect to the master to have the RELOAD and SUPER privileges on the master and the SELECT privilege for all master tables you want to load. All master tables for which the user does not have the SELECT privilege are ignored by LOAD DATA FROM MASTER. This is because the master hides them from the user: LOAD DATA FROM MASTER calls SHOW DATABASES to know the master databases to load, but SHOW DATABASES returns only databases for which the user has some privilege. See [SHOW DATABASES, , SHOW DATABASES]. On the slave's side, the user that issues LOAD DATA FROM MASTER should have grants to drop and create the databases and tables that are copied.    
88 RESET 6 The RESET statement is used to clear the state of various server operations. It also acts as a stronger version of the FLUSH statement. See also : [FLUSH, , FLUSH]. RESET reset_option [, reset_option] ...  
89 GET_LOCK 21 GET_LOCK(str,timeout) Tries to obtain a lock with a name given by the string str, with a timeout of timeout seconds. Returns 1 if the lock was obtained successfully, 0 if the attempt timed out (for example, because another client has previously locked the name), or NULL if an error occurred (such as running out of memory or the thread was killed with mysqladmin kill). If you have a lock obtained with GET_LOCK(), it is released when you execute RELEASE_LOCK(), execute a new GET_LOCK(), or your connection terminates (either normally or abnormally). This function can be used to implement application locks or to simulate record locks. Names are locked on a server-wide basis. If a name has been locked by one client, GET_LOCK() blocks any request by another client for a lock with the same name. This allows clients that agree on a given lock name to use the name to perform cooperative advisory locking. mysql> SELECT GET_LOCK('lock1',10); -> 1 mysql> SELECT IS_FREE_LOCK('lock2'); -> 1 mysql> SELECT GET_LOCK('lock2',10); -> 1 mysql> SELECT RELEASE_LOCK('lock2'); -> 1 mysql> SELECT RELEASE_LOCK('lock1'); -> NULL  
90 UCASE 23 UCASE(str) UCASE() is a synonym for UPPER().    
91 MPOLYFROMWKB 13 MPolyFromWKB(wkb[,srid]) MultiPolygonFromWKB(wkb[,srid]) Constructs a MULTIPOLYGON value using its WKB representation and SRID.    
92 DO 6 DO executes the expressions but doesn't return any results. This is shorthand for SELECT expr, ..., but has the advantage that it's slightly faster when you don't care about the result. DO is useful mainly with functions that have side effects, such as RELEASE_LOCK(). DO expr [, expr] ...  
93 CURTIME 14 CURTIME() Returns the current time as a value in 'HH:MM:SS' or HHMMSS format, depending on whether the function is used in a string or numeric context. mysql> SELECT CURTIME(); -> '23:50:26' mysql> SELECT CURTIME() + 0; -> 235026  
94 BIGINT 1 BIGINT[(M)] [UNSIGNED] [ZEROFILL] A large integer. The signed range is -9223372036854775808 to 9223372036854775807. The unsigned range is 0 to 18446744073709551615.    
95 CHAR_LENGTH 23 CHAR_LENGTH(str) Returns the length of the string str, measured in characters. A multi-byte character counts as a single character. This means that for a string containing five two-byte characters, LENGTH() returns 10, whereas CHAR_LENGTH() returns 5.    
96 SET 6 SET sets different types of variables that affect the operation of the server or your client. It can be used to assign values to user variables or system variables. SET variable_assignment [, variable_assignment] ... variable_assignment: user_var_name = expr | [GLOBAL | SESSION] system_var_name = expr | @@[global. | session.]system_var_name = expr  
97 DATE 1 A date. The supported range is '1000-01-01' to '9999-12-31'. MySQL displays DATE values in 'YYYY-MM-DD' format, but allows you to assign values to DATE columns using either strings or numbers.    
98 CONV 23 CONV(N,from_base,to_base) Converts numbers between different number bases. Returns a string representation of the number N, converted from base from_base to base to_base. Returns NULL if any argument is NULL. The argument N is interpreted as an integer, but may be specified as an integer or a string. The minimum base is 2 and the maximum base is 36. If to_base is a negative number, N is regarded as a signed number. Otherwise, N is treated as unsigned. CONV() works with 64-bit precision. mysql> SELECT CONV('a',16,2); -> '1010' mysql> SELECT CONV('6E',18,8); -> '172' mysql> SELECT CONV(-17,10,-18); -> '-H' mysql> SELECT CONV(10+'10'+'10'+0xa,10,10); -> '40'  
99 EXTRACT 14 EXTRACT(type FROM date) The EXTRACT() function uses the same kinds of interval type specifiers as DATE_ADD() or DATE_SUB(), but extracts parts from the date rather than performing date arithmetic. mysql> SELECT EXTRACT(YEAR FROM '1999-07-02'); -> 1999 mysql> SELECT EXTRACT(YEAR_MONTH FROM '1999-07-02 01:02:03'); -> 199907 mysql> SELECT EXTRACT(DAY_MINUTE FROM '1999-07-02 01:02:03'); -> 20102 mysql> SELECT EXTRACT(MICROSECOND -> FROM '2003-01-02 10:30:00.00123'); -> 123  
100 ENCRYPT 17 ENCRYPT(str[,salt]) Encrypt str using the Unix crypt() system call. The salt argument should be a string with two characters. (As of MySQL 3.22.16, salt may be longer than two characters.) If no salt argument is given, a random value is used. mysql> SELECT ENCRYPT('hello'); -> 'VxuFAJXVARROc'  
101 OLD_PASSWORD 17 OLD_PASSWORD(str) OLD_PASSWORD() is available as of MySQL 4.1, when the implementation of PASSWORD() was changed to improve security. OLD_PASSWORD() returns the value of the pre-4.1 implementation of PASSWORD(). [Password hashing]. PASSWORD(str) Calculates and returns a password string from the plaintext password str, or NULL if the argument was NULL. This is the function that is used for encrypting MySQL passwords for storage in the Password column of the user grant table.    
102 FORMAT 21 FORMAT(X,D) Formats the number X to a format like '#,###,###.##', rounded to D decimals, and returns the result as a string. If D is 0, the result has no decimal point or fractional part. mysql> SELECT FORMAT(12332.123456, 4); -> '12,332.1235' mysql> SELECT FORMAT(12332.1,4); -> '12,332.1000' mysql> SELECT FORMAT(12332.2,0); -> '12,332'  
103 || 20 OR || Logical OR. When both operands are non-NULL, the result is 1 if any operand is non-zero, and 0 otherwise. With a NULL operand, the result is 1 if the other operand is non-zero, and NULL otherwise. If both operands are NULL, the result is NULL. mysql> SELECT 1 || 1; -> 1 mysql> SELECT 1 || 0; -> 1 mysql> SELECT 0 || 0; -> 0 mysql> SELECT 0 || NULL; -> NULL mysql> SELECT 1 || NULL; -> 1  
104 CASE 9 CASE value WHEN [compare-value] THEN result [WHEN [compare-value] THEN result ...] [ELSE result] END CASE WHEN [condition] THEN result [WHEN [condition] THEN result ...] [ELSE result] END The first version returns the result where value=compare-value. The second version returns the result for the first condition that is true. If there was no matching result value, the result after ELSE is returned, or NULL if there is no ELSE part. mysql> SELECT CASE 1 WHEN 1 THEN 'one' -> WHEN 2 THEN 'two' ELSE 'more' END; -> 'one' mysql> SELECT CASE WHEN 1>0 THEN 'true' ELSE 'false' END; -> 'true' mysql> SELECT CASE BINARY 'B' -> WHEN 'a' THEN 1 WHEN 'b' THEN 2 END; -> NULL  
105 BIT_LENGTH 23 BIT_LENGTH(str) Returns the length of the string str in bits. mysql> SELECT BIT_LENGTH('text'); -> 32  
106 EXTERIORRING 0 ExteriorRing(poly) Returns the exterior ring of the Polygon value poly as a LineString. mysql> SET @poly = -> 'Polygon((0 0,0 3,3 3,3 0,0 0),(1 1,1 2,2 2,2 1,1 1))'; mysql> SELECT AsText(ExteriorRing(GeomFromText(@poly))); +-------------------------------------------+ | AsText(ExteriorRing(GeomFromText(@poly))) | +-------------------------------------------+ | LINESTRING(0 0,0 3,3 3,3 0,0 0) | +-------------------------------------------+  
107 GEOMFROMWKB 13 GeomFromWKB(wkb[,srid]) GeometryFromWKB(wkb[,srid]) Constructs a geometry value of any type using its WKB representation and SRID.    
108 SHOW SLAVE HOSTS 6 SHOW SLAVE HOSTS Displays a list of slaves currently registered with the master. Any slave not started with the --report-host=slave_name option is not visible in that list.    
109 START TRANSACTION 10 By default, MySQL runs with autocommit mode enabled. This means that as soon as you execute a statement that updates (modifies) a table, MySQL stores the update on disk. If you are using transaction-safe tables (like InnoDB or BDB), you can disable autocommit mode with the following statement: SET AUTOCOMMIT=0; After disabling autocommit mode by setting the AUTOCOMMIT variable to zero, you must use COMMIT to store your changes to disk or ROLLBACK if you want to ignore the changes you have made since the beginning of your transaction. If you want to disable autocommit mode for a single series of statements, you can use the START TRANSACTION statement: START TRANSACTION; SELECT @A:=SUM(salary) FROM table1 WHERE type=1; UPDATE table2 SET summary=@A WHERE type=1; COMMIT;  
110 BETWEEN AND 26 expr BETWEEN min AND max If expr is greater than or equal to min and expr is less than or equal to max, BETWEEN returns 1, otherwise it returns 0. This is equivalent to the expression (min <= expr AND expr <= max) if all the arguments are of the same type. Otherwise type conversion takes place according to the rules described at the beginning of this section, but applied to all the three arguments. Note: Before MySQL 4.0.5, arguments were converted to the type of expr instead. mysql> SELECT 1 BETWEEN 2 AND 3; -> 0 mysql> SELECT 'b' BETWEEN 'a' AND 'c'; -> 1 mysql> SELECT 2 BETWEEN 2 AND '3'; -> 1 mysql> SELECT 2 BETWEEN 2 AND 'x-3'; -> 0  
111 MULTIPOLYGON 2 MultiPolygon(poly1,poly2,...) Constructs a WKB MultiPolygon value from a set of WKB Polygon arguments. If any argument is not a WKB Polygon, the return value is NULL.    
112 TIME_FORMAT 14 TIME_FORMAT(time,format) This is used like the DATE_FORMAT() function, but the format string may contain only those format specifiers that handle hours, minutes, and seconds. Other specifiers produce a NULL value or 0.    
113 LEFT 23 LEFT(str,len) Returns the leftmost len characters from the string str. mysql> SELECT LEFT('foobarbar', 5); -> 'fooba'  
114 FLUSH QUERY CACHE 7 You can defragment the query cache to better utilize its memory with the FLUSH QUERY CACHE statement. The statement does not remove any queries from the cache. The RESET QUERY CACHE statement removes all query results from the query cache. The FLUSH TABLES statement also does this.    
115 RAND 4 RAND() RAND(N) Returns a random floating-point value in the range from 0 to 1.0. If an integer argument N is specified, it is used as the seed value (producing a repeatable sequence). mysql> SELECT RAND(); -> 0.9233482386203 mysql> SELECT RAND(20); -> 0.15888261251047 mysql> SELECT RAND(20); -> 0.15888261251047 mysql> SELECT RAND(); -> 0.63553050033332 mysql> SELECT RAND(); -> 0.70100469486881  
116 RPAD 23 RPAD(str,len,padstr) Returns the string str, right-padded with the string padstr to a length of len characters. If str is longer than len, the return value is shortened to len characters. mysql> SELECT RPAD('hi',5,'?'); -> 'hi???' mysql> SELECT RPAD('hi',1,'?'); -> 'h'  
117 INSERT INTO 6 INSERT inserts new rows into an existing table. The INSERT ... VALUES and INSERT ... SET forms of the statement insert rows based on explicitly specified values. The INSERT ... SELECT form inserts rows selected from another table or tables. The INSERT ... VALUES form with multiple value lists is supported in MySQL 3.22.5 or later. The INSERT ... SET syntax is supported in MySQL 3.22.10 or later. INSERT ... SELECT is discussed further in See also : [INSERT SELECT, , INSERT SELECT]. INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE] [INTO] tbl_name [(col_name,...)] VALUES ({expr | DEFAULT},...),(...),... [ ON DUPLICATE KEY UPDATE col_name=expr, ... ]  
118 RESTORE 7 RESTORE TABLE tbl_name [, tbl_name] ... FROM '/path/to/backup/directory' Restores the table or tables from a backup that was made with BACKUP TABLE. Existing tables are not overwritten; if you try to restore over an existing table, you get an error. Just as BACKUP TABLE, RESTORE TABLE currently works only for MyISAM tables. The directory should be specified as a full pathname. The backup for each table consists of its *.frm format file and *.MYD data file. The restore operation restores those files, then uses them to rebuild the *.MYI index file. Restoring takes longer than backing up due to the need to rebuild the indexes. The more indexes the table has, the longer it takes.    
119 CREATE DATABASE 28 CREATE DATABASE creates a database with the given name. To use CREATE DATABASE, you need the CREATE privilege on the database. CREATE {DATABASE | SCHEMA} [IF NOT EXISTS] db_name [create_specification [, create_specification] ...] create_specification: [DEFAULT] CHARACTER SET charset_name | [DEFAULT] COLLATE collation_name  
120 VAR_POP 12 VAR_POP(expr) Returns the population standard variance of expr. It considers rows as the whole population, not as a sample, so it has the number of rows as the denominator. This function was added in MySQL 5.0.3. Before 5.0.3, you can use VARIANCE(), which is equivalent but not standard SQL.    
121 ELT 23 ELT(N,str1,str2,str3,...) Returns str1 if N = 1, str2 if N = 2, and so on. Returns NULL if N is less than 1 or greater than the number of arguments. ELT() is the complement of FIELD(). mysql> SELECT ELT(1, 'ej', 'Heja', 'hej', 'foo'); -> 'ej' mysql> SELECT ELT(4, 'ej', 'Heja', 'hej', 'foo'); -> 'foo'  
122 ALTER VIEW 24 This statement changes the definition of an existing view. The syntax is similar to that for CREATE VIEW. See also : [CREATE VIEW, , CREATE VIEW]. This statement requires the CREATE VIEW and DELETE privileges for the view, and some privilege for each column referred to in the SELECT statement. ALTER [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}] VIEW view_name [(column_list)] AS select_statement [WITH [CASCADED | LOCAL] CHECK OPTION]  
123 ~ 27 ~ Invert all bits. mysql> SELECT 5 & ~1; -> 4  
124 CONCAT_WS 23 CONCAT_WS(separator,str1,str2,...) CONCAT_WS() stands for CONCAT With Separator and is a special form of CONCAT(). The first argument is the separator for the rest of the arguments. The separator is added between the strings to be concatenated. The separator can be a string as can the rest of the arguments. If the separator is NULL, the result is NULL. The function skips any NULL values after the separator argument. mysql> SELECT CONCAT_WS(',','First name','Second name','Last Name'); -> 'First name,Second name,Last Name' mysql> SELECT CONCAT_WS(',','First name',NULL,'Last Name'); -> 'First name,Last Name'  
125 ROW_COUNT 25 ROW_COUNT() ROW_COUNT() returns the number of rows updated, inserted, or deleted by the preceding statement. This is the same as the row count that the mysql client displays and the value from the mysql_affected_rows() C API function. mysql> INSERT INTO t VALUES(1),(2),(3); Query OK, 3 rows affected (0.00 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql> SELECT ROW_COUNT(); +-------------+ | ROW_COUNT() | +-------------+ | 3 | +-------------+ 1 row in set (0.00 sec) mysql> DELETE FROM t WHERE i IN(1,2); Query OK, 2 rows affected (0.00 sec) mysql> SELECT ROW_COUNT(); +-------------+ | ROW_COUNT() | +-------------+ | 2 | +-------------+ 1 row in set (0.00 sec)  
126 ASIN 4 ASIN(X) Returns the arc sine of X, that is, the value whose sine is X. Returns NULL if X is not in the range -1 to 1. mysql> SELECT ASIN(0.2); -> 0.201358 mysql> SELECT ASIN('foo'); -> 0.000000  
127 FUNCTION 22 A user-defined function (UDF) is a way to extend MySQL with a new function that works like a native (built-in) MySQL function such as ABS() or CONCAT(). function_name is the name that should be used in SQL statements to invoke the function. The RETURNS clause indicates the type of the function's return value. shared_library_name is the basename of the shared object file that contains the code that implements the function. The file must be located in a directory that is searched by your system's dynamic linker. To create a function, you must have the INSERT and privilege for the mysql database. To drop a function, you must have the DELETE privilege for the mysql database. This is because CREATE FUNCTION adds a row to the mysql.func system table that records the function's name, type, and shared library name, and DROP FUNCTION deletes the function's row from that table. If you do not have this table, you should run the mysql_fix_privilege_tables script to create it. See also : [Upgrading-grant-tables]. CREATE [AGGREGATE] FUNCTION function_name RETURNS {STRING|INTEGER|REAL} SONAME shared_library_name DROP FUNCTION function_name  
128 SIGN 4 SIGN(X) Returns the sign of the argument as -1, 0, or 1, depending on whether X is negative, zero, or positive. mysql> SELECT SIGN(-32); -> -1 mysql> SELECT SIGN(0); -> 0 mysql> SELECT SIGN(234); -> 1  
129 SEC_TO_TIME 14 SEC_TO_TIME(seconds) Returns the seconds argument, converted to hours, minutes, and seconds, as a value in 'HH:MM:SS' or HHMMSS format, depending on whether the function is used in a string or numeric context. mysql> SELECT SEC_TO_TIME(2378); -> '00:39:38' mysql> SELECT SEC_TO_TIME(2378) + 0; -> 3938  
130 YEAR TYPE 1 YEAR[(2|4)] A year in two-digit or four-digit format. The default is four-digit format. In four-digit format, the allowable values are 1901 to 2155, and 0000. In two-digit format, the allowable values are 70 to 69, representing years from 1970 to 2069. MySQL displays YEAR values in YYYY format, but allows you to assign values to YEAR columns using either strings or numbers. The YEAR type is unavailable prior to MySQL 3.22.    
131 FLOAT 1 FLOAT(p) [UNSIGNED] [ZEROFILL] A floating-point number. p represents the precision. It can be from 0 to 24 for a single-precision floating-point number and from 25 to 53 for a double-precision floating-point number. These types are like the FLOAT and DOUBLE types described immediately following. FLOAT(p) has the same range as the corresponding FLOAT and DOUBLE types, but the display width and number of decimals are undefined. As of MySQL 3.23, this is a true floating-point value. In earlier MySQL versions, FLOAT(p) always has two decimals. This syntax is provided for ODBC compatibility. Using FLOAT might give you some unexpected problems because all calculations in MySQL are done with double precision. See also : [No matching rows]. FLOAT[(M,D)] [UNSIGNED] [ZEROFILL] A small (single-precision) floating-point number. Allowable values are -3.402823466E+38 to -1.175494351E-38, 0, and 1.175494351E-38 to 3.402823466E+38. If UNSIGNED is specified, negative values are disallowed. M is the display width and D is the number of significant digits. FLOAT without arguments or FLOAT(p) (where p is in the range from 0 to 24) stands for a single-precision floating-point number.    
132 LOCATE 23 LOCATE(substr,str) LOCATE(substr,str,pos) The first syntax returns the position of the first occurrence of substring substr in string str. The second syntax returns the position of the first occurrence of substring substr in string str, starting at position pos. Returns 0 if substr is not in str.    
133 CHARSET 25 CHARSET(str) Returns the character set of the string argument. mysql> SELECT CHARSET('abc'); -> 'latin1' mysql> SELECT CHARSET(CONVERT('abc' USING utf8)); -> 'utf8' mysql> SELECT CHARSET(USER()); -> 'utf8'  
134 PURGE MASTER LOGS BEFORE TO 6 PURGE {MASTER | BINARY} LOGS TO 'log_name' PURGE {MASTER | BINARY} LOGS BEFORE 'date' Deletes all the binary logs listed in the log index that are strictly prior to the specified log or date. The logs also are removed from the list recorded in the log index file, so that the given log becomes the first.    
135 SUBDATE 14 SUBDATE(date,INTERVAL expr type) SUBDATE(expr,days) When invoked with the INTERVAL form of the second argument, SUBDATE() is a synonym for DATE_SUB(). For information on the INTERVAL argument, see the discussion for DATE_ADD(). mysql> SELECT DATE_SUB('1998-01-02', INTERVAL 31 DAY); -> '1997-12-02' mysql> SELECT SUBDATE('1998-01-02', INTERVAL 31 DAY); -> '1997-12-02' As of MySQL 4.1.1, the second syntax is allowed, where expr is a date or datetime expression and days is the number of days to be subtracted from expr. mysql> SELECT SUBDATE('1998-01-02 12:00:00', 31); -> '1997-12-02 12:00:00' Note that you can't use format "%X%V" to convert a year-week string to date as a year-week doesn't uniquely identify a year-month if the week crosses a month boundary. If you want to convert a year-week to a date you can do it by also specifying the week day: mysql> select str_to_date('200442 Monday', '%X%V %W'); -> 2004-10-18    
136 DAYOFYEAR 14 DAYOFYEAR(date) Returns the day of the year for date, in the range 1 to 366. mysql> SELECT DAYOFYEAR('1998-02-03'); -> 34  
137 % 4 MOD(N,M) N % M N MOD M Modulo operation. Returns the remainder of N divided by M. mysql> SELECT MOD(234, 10); -> 4 mysql> SELECT 253 % 7; -> 1 mysql> SELECT MOD(29,9); -> 2 mysql> SELECT 29 MOD 9; -> 2  
138 LONGTEXT 1 LONGTEXT A TEXT column with a maximum length of 4,294,967,295 or 4GB (2^32 - 1) characters. Up to MySQL 3.23, the client/server protocol and MyISAM tables had a limit of 16MB per communication packet / table row. From MySQL 4.0, the maximum allowed length of LONGTEXT columns depends on the configured maximum packet size in the client/server protocol and available memory.    
139 DISJOINT 11 Disjoint(g1,g2) Returns 1 or 0 to indicate whether or not g1 is spatially disjoint from (does not intersect) g2.    
140 KILL 6 Each connection to mysqld runs in a separate thread. You can see which threads are running with the SHOW PROCESSLIST statement and kill a thread with the KILL thread_id statement. As of MySQL 5.0.0, KILL allows the optional CONNECTION or QUERY modifiers: --- KILL CONNECTION is the same as KILL with no modifier: It terminates the connection associated with the given thread_id. --- KILL QUERY terminates the statement that the connection currently is executing, but leaves the connection intact. If you have the PROCESS privilege, you can see all threads. If you have the SUPER privilege, you can kill all threads and statements. Otherwise, you can see and kill only your own threads and statements. You can also use the mysqladmin processlist and mysqladmin kill commands to examine and kill threads. Note: You currently cannot use KILL with the Embedded MySQL Server library, because the embedded server merely runs inside the threads of the host application, it does not create connection threads of its own. KILL [CONNECTION | QUERY] thread_id  
141 ASTEXT 3 AsText(g) Converts a value in internal geometry format to its WKT representation and returns the string result. mysql> SELECT AsText(g) FROM geom; +-------------------------+ | AsText(p1) | +-------------------------+ | POINT(1 1) | | LINESTRING(0 0,1 1,2 2) | +-------------------------+  
142 LPAD 23 LPAD(str,len,padstr) Returns the string str, left-padded with the string padstr to a length of len characters. If str is longer than len, the return value is shortened to len characters. mysql> SELECT LPAD('hi',4,'??'); -> '??hi' mysql> SELECT LPAD('hi',1,'??'); -> 'h'  
143 OVERLAPS 11 Overlaps(g1,g2) Returns 1 or 0 to indicate whether or not g1 spatially overlaps g2. The term /spatially overlaps/ is used if two geometries intersect and their intersection results in a geometry of the same dimension but not equal to either of the given geometries.    
144 NUMGEOMETRIES 5 NumGeometries(gc) Returns the number of geometries in the GeometryCollection value gc. mysql> SET @gc = 'GeometryCollection(Point(1 1),LineString(2 2, 3 3))'; mysql> SELECT NumGeometries(GeomFromText(@gc)); +----------------------------------+ | NumGeometries(GeomFromText(@gc)) | +----------------------------------+ | 2 | +----------------------------------+  
145 SET GLOBAL SQL_SLAVE_SKIP_COUNTER 7 SET GLOBAL SQL_SLAVE_SKIP_COUNTER = n Skip the next n events from the master. This is useful for recovering from replication stops caused by a statement. This statement is valid only when the slave thread is not running. Otherwise, it produces an error. Before MySQL 4.0, omit the GLOBAL keyword from the statement.    
146 MONTHNAME 14 MONTHNAME(date) Returns the full name of the month for date. mysql> SELECT MONTHNAME('1998-02-05'); -> 'February'  
147 MBREQUAL 8 MBREqual(g1,g2) Returns 1 or 0 to indicate whether or not the Minimum Bounding Rectangles of the two geometries g1 and g2 are the same.    
148 CHANGE MASTER TO 6 CHANGE MASTER TO master_def [, master_def] ... master_def: MASTER_HOST = 'host_name' | MASTER_USER = 'user_name' | MASTER_PASSWORD = 'password' | MASTER_PORT = port_num | MASTER_CONNECT_RETRY = count | MASTER_LOG_FILE = 'master_log_name' | MASTER_LOG_POS = master_log_pos | RELAY_LOG_FILE = 'relay_log_name' | RELAY_LOG_POS = relay_log_pos | MASTER_SSL = {0|1} | MASTER_SSL_CA = 'ca_file_name' | MASTER_SSL_CAPATH = 'ca_directory_name' | MASTER_SSL_CERT = 'cert_file_name' | MASTER_SSL_KEY = 'key_file_name' | MASTER_SSL_CIPHER = 'cipher_list' Changes the parameters that the slave server uses for connecting to and communicating with the master server. MASTER_USER, MASTER_PASSWORD, MASTER_SSL, MASTER_SSL_CA, MASTER_SSL_CAPATH, MASTER_SSL_CERT, MASTER_SSL_KEY, and MASTER_SSL_CIPHER provide information for the slave about how to connect to its master. The relay log options (RELAY_LOG_FILE and RELAY_LOG_POS) are available beginning with MySQL 4.0. The SSL options (MASTER_SSL, MASTER_SSL_CA, MASTER_SSL_CAPATH, MASTER_SSL_CERT, MASTER_SSL_KEY, and MASTER_SSL_CIPHER) are available beginning with MySQL 4.1.1. You can change these options even on slaves that are compiled without SSL support. They are saved to the *master.info file, but are ignored until you use a server that has SSL support enabled. If you don't specify a given parameter, it keeps its old value, except as indicated in the following discussion. For example, if the password to connect to your MySQL master has changed, you just need to issue these statements to tell the slave about the new password: mysql> STOP SLAVE; -- if replication was running mysql> CHANGE MASTER TO MASTER_PASSWORD='new3cret'; mysql> START SLAVE; -- if you want to restart replication There is no need to specify the parameters that do not change (host, port, user, and so forth). MASTER_HOST and MASTER_PORT are the hostname (or IP address) of the master host and its TCP/IP port. Note that if MASTER_HOST is equal to localhost, then, like in other parts of MySQL, the port may be ignored (if Unix socket files can be used, for example). If you specify MASTER_HOST or MASTER_PORT, the slave assumes that the master server is different than before (even if you specify a host or port value that is the same as the current value.) In this case, the old values for the master binary log name and position are considered no longer applicable, so if you do not specify MASTER_LOG_FILE and MASTER_LOG_POS in the statement, MASTER_LOG_FILE='' and MASTER_LOG_POS=4 are silently appended to it. MASTER_LOG_FILE and MASTER_LOG_POS are the coordinates at which the slave I/O thread should begin reading from the master the next time the thread starts. If you specify either of them, you can't specify RELAY_LOG_FILE or RELAY_LOG_POS. If neither of MASTER_LOG_FILE or MASTER_LOG_POS are specified, the slave uses the last coordinates of the /slave SQL thread/ before CHANGE MASTER was issued. This ensures that replication has no discontinuity, even if the slave SQL thread was late compared to the slave I/O thread, when you just want to change, say, the password to use. This safe behavior was introduced starting from MySQL 4.0.17 and 4.1.1. (Before these versions, the coordinates used were the last coordinates of the slave I/O thread before CHANGE MASTER was issued. This caused the SQL thread to possibly lose some events from the master, thus breaking replication.) CHANGE MASTER /deletes all relay log files/ and starts a new one, unless you specify RELAY_LOG_FILE or RELAY_LOG_POS. In that case, relay logs are kept; as of MySQL 4.1.1 the relay_log_purge global variable is set silently to 0. CHANGE MASTER TO updates the contents of the *master.info and *relay-log.info files. CHANGE MASTER is useful for setting up a slave when you have the snapshot of the master and have recorded the log and the offset corresponding to it. After loading the snapshot into the slave, you can run CHANGE MASTER TO MASTER_LOG_FILE='log_name_on_master', MASTER_LOG_POS=log_offset_on_master on the slave. Examples: mysql> CHANGE MASTER TO -> MASTER_HOST='master2.mycompany.com', -> MASTER_USER='replication', -> MASTER_PASSWORD='bigs3cret', -> MASTER_PORT=3306, -> MASTER_LOG_FILE='master2-bin.001', -> MASTER_LOG_POS=4, -> MASTER_CONNECT_RETRY=10; mysql> CHANGE MASTER TO -> RELAY_LOG_FILE='slave-relay-bin.006', -> RELAY_LOG_POS=4025;    
149 DROP DATABASE 28 DROP DATABASE drops all tables in the database and deletes the database. Be /very/ careful with this statement! To use DROP DATABASE, you need the DROP privilege on the database. In MySQL 3.22 or later, you can use the keywords IF EXISTS to prevent an error from occurring if the database doesn't exist. DROP SCHEMA can be used as of MySQL 5.0.2. DROP {DATABASE | SCHEMA} [IF EXISTS] db_name  
150 TIMESTAMP FUNCTION 14 TIMESTAMP(expr) TIMESTAMP(expr,expr2) With one argument, returns the date or datetime expression expr as a datetime value. With two arguments, adds the time expression expr2 to the date or datetime expression expr and returns a datetime value. mysql> SELECT TIMESTAMP('2003-12-31'); -> '2003-12-31 00:00:00' mysql> SELECT TIMESTAMP('2003-12-31 12:00:00','12:00:00'); -> '2004-01-01 00:00:00'  
151 CHARACTER_LENGTH 23 CHARACTER_LENGTH(str) CHARACTER_LENGTH() is a synonym for CHAR_LENGTH().    
152 CREATE VIEW ALGORITHM MERGE TEMPTABLE WITH CHECK OPTION 24   CREATE [OR REPLACE] [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}] VIEW view_name [(column_list)] AS select_statement [WITH [CASCADED | LOCAL] CHECK OPTION]  
153 TIMESTAMPDIFF FUNCTION 14   mysql> SELECT TIMESTAMPDIFF(MONTH,'2003-02-01','2003-05-01'); -> 3 mysql> SELECT TIMESTAMPDIFF(YEAR,'2002-05-01','2001-01-01'); -> -1  
154 CRC32 4 CRC32(expr) Computes a cyclic redundancy check value and returns a 32-bit unsigned value. The result is NULL if the argument is NULL. The argument is expected be a string and is treated as one if it is not. mysql> SELECT CRC32('MySQL'); -> 3259397556  
155 XOR 20 XOR Logical XOR. Returns NULL if either operand is NULL. For non-NULL operands, evaluates to 1 if an odd number of operands is non-zero, otherwise 0 is returned. mysql> SELECT 1 XOR 1; -> 0 mysql> SELECT 1 XOR 0; -> 1 mysql> SELECT 1 XOR NULL; -> NULL mysql> SELECT 1 XOR 1 XOR 1; -> 1  
156 STARTPOINT 18 StartPoint(ls) Returns the Point that is the start point of the LineString value ls. mysql> SET @ls = 'LineString(1 1,2 2,3 3)'; mysql> SELECT AsText(StartPoint(GeomFromText(@ls))); +---------------------------------------+ | AsText(StartPoint(GeomFromText(@ls))) | +---------------------------------------+ | POINT(1 1) | +---------------------------------------+  
157 MPOLYFROMTEXT 3 MPolyFromText(wkt[,srid]) MultiPolygonFromText(wkt[,srid]) Constructs a MULTIPOLYGON value using its WKT representation and SRID.    
158 MBRINTERSECTS 8 MBRIntersects(g1,g2) Returns 1 or 0 to indicate whether or not the Minimum Bounding Rectangles of the two geometries g1 and g2 intersect.    
159 BIT_OR 12 BIT_OR(expr) Returns the bitwise OR of all bits in expr. The calculation is performed with 64-bit (BIGINT) precision.    
160 YEARWEEK 14 YEARWEEK(date) YEARWEEK(date,start) Returns year and week for a date. The start argument works exactly like the start argument to WEEK(). The year in the result may be different from the year in the date argument for the first and the last week of the year. mysql> SELECT YEARWEEK('1987-01-01'); -> 198653  
161 NOT BETWEEN 26 expr NOT BETWEEN min AND max This is the same as NOT (expr BETWEEN min AND max).    
162 LOG10 4 LOG10(X) Returns the base-10 logarithm of X. mysql> SELECT LOG10(2); -> 0.301030 mysql> SELECT LOG10(100); -> 2.000000 mysql> SELECT LOG10(-100); -> NULL  
163 SQRT 4 SQRT(X) Returns the non-negative square root of X. mysql> SELECT SQRT(4); -> 2.000000 mysql> SELECT SQRT(20); -> 4.472136  
164 DECIMAL 1 DECIMAL[(M[,D])] [UNSIGNED] [ZEROFILL] For MySQL 5.0.3 and above: A packed ``exact'' fixed-point number. M is the total number of digits and D is the number of decimals. The decimal point and (for negative numbers) the '-' sign are not counted in M. If D is 0, values have no decimal point or fractional part. The maximum number of digits (M) for DECIMAL is 64. The maximum number of supported decimals (D) is 30. If UNSIGNED is specified, negative values are disallowed. If D is omitted, the default is 0. If M is omitted, the default is 10. All basic calculations (+, -, *, /) with DECIMAL columns are done with a precision of 64 decimal digits. Before MySQL 5.0.3: An unpacked fixed-point number. Behaves like a CHAR column; ``unpacked'' means the number is stored as a string, using one character for each digit of the value. M is the total number of digits and D is the number of decimals. The decimal point and (for negative numbers) the '-' sign are not counted in M, although space for them is reserved. If D is 0, values have no decimal point or fractional part. The maximum range of DECIMAL values is the same as for DOUBLE, but the actual range for a given DECIMAL column may be constrained by the choice of M and D. If UNSIGNED is specified, negative values are disallowed. If D is omitted, the default is 0. If M is omitted, the default is 10. Before MySQL 3.23: As just described, with the exception that the M value must be large enough to include the space needed for the sign and the decimal point characters. DEC[(M[,D])] [UNSIGNED] [ZEROFILL] NUMERIC[(M[,D])] [UNSIGNED] [ZEROFILL] FIXED[(M[,D])] [UNSIGNED] [ZEROFILL] These are synonyms for DECIMAL. The FIXED synonym was added in MySQL 4.1.0 for compatibility with other servers.    
165 GEOMETRYN 5 GeometryN(gc,n) Returns the n-th geometry in the GeometryCollection value gc. Geometry numbers begin at 1. mysql> SET @gc = 'GeometryCollection(Point(1 1),LineString(2 2, 3 3))'; mysql> SELECT AsText(GeometryN(GeomFromText(@gc),1)); +----------------------------------------+ | AsText(GeometryN(GeomFromText(@gc),1)) | +----------------------------------------+ | POINT(1 1) | +----------------------------------------+  
166 CREATE INDEX 28 In MySQL 3.22 or later, CREATE INDEX is mapped to an ALTER TABLE statement to create indexes. See also : [ALTER TABLE, , ALTER TABLE]. The CREATE INDEX statement doesn't do anything prior to MySQL 3.22. CREATE [UNIQUE|FULLTEXT|SPATIAL] INDEX index_name [USING index_type] ON tbl_name (index_col_name,...) index_col_name: col_name [(length)] [ASC | DESC]  
167 ALTER DATABASE 28 ALTER DATABASE allows you to change the overall characteristics of a database. These characteristics are stored in the *db.opt file in the database directory. To use ALTER DATABASE, you need the ALTER privilege on the database. ALTER {DATABASE | SCHEMA} [db_name] alter_specification [, alter_specification] ... alter_specification: [DEFAULT] CHARACTER SET charset_name | [DEFAULT] COLLATE collation_name  
168 << 27 Shifts a longlong (BIGINT) number to the left. << mysql> SELECT 1 << 2; -> 4  
169 MD5 17 MD5(str) Calculates an MD5 128-bit checksum for the string. The value is returned as a binary string of 32 hex digits, or NULL if the argument was NULL. The return value can, for example, be used as a hash key. mysql> SELECT MD5('testing'); -> 'ae2b1fca515949e5d54fb22b8ed95575'  
170 < 26 < Less than: mysql> SELECT 2 < 2; -> 0  
171 UNIX_TIMESTAMP 14 UNIX_TIMESTAMP() UNIX_TIMESTAMP(date) If called with no argument, returns a Unix timestamp (seconds since '1970-01-01 00:00:00' GMT) as an unsigned integer. If UNIX_TIMESTAMP() is called with a date argument, it returns the value of the argument as seconds since '1970-01-01 00:00:00' GMT. date may be a DATE string, a DATETIME string, a TIMESTAMP, or a number in the format YYMMDD or YYYYMMDD in local time. mysql> SELECT UNIX_TIMESTAMP(); -> 882226357 mysql> SELECT UNIX_TIMESTAMP('1997-10-04 22:23:00'); -> 875996580  
172 DAYOFMONTH 14 DAYOFMONTH(date) Returns the day of the month for date, in the range 1 to 31. mysql> SELECT DAYOFMONTH('1998-02-03'); -> 3  
173 ASCII 23 ASCII(str) Returns the numeric value of the leftmost character of the string str. Returns 0 if str is the empty string. Returns NULL if str is NULL. ASCII() works for characters with numeric values from 0 to 255. mysql> SELECT ASCII('2'); -> 50 mysql> SELECT ASCII(2); -> 50 mysql> SELECT ASCII('dx'); -> 100  
174 DIV 4 Integer division. Similar to FLOOR() but safe with BIGINT values. mysql> SELECT 5 DIV 2; -> 2  
175 RENAME USER 7 The RENAME USER statement renames existing MySQL accounts. To use it, you must have the global CREATE USER privilege or the UPDATE privilege for the mysql database. An error occurs if any old account does not exist or any new account exists. The old_user and new_user values are given the same way as for the GRANT statement. RENAME USER old_user TO new_user [, old_user TO new_user] ...  
176 SHOW SLAVE STATUS 7 SHOW SLAVE STATUS Provides status information on essential parameters of the slave threads. If you issue this statement using the mysql client, you can use a \G statement terminator rather than semicolon to get a more readable vertical layout: mysql> SHOW SLAVE STATUS\G *************************** 1. row *************************** Slave_IO_State: Waiting for master to send event Master_Host: localhost Master_User: root Master_Port: 3306 Connect_Retry: 3 Master_Log_File: gbichot-bin.005 Read_Master_Log_Pos: 79 Relay_Log_File: gbichot-relay-bin.005 Relay_Log_Pos: 548 Relay_Master_Log_File: gbichot-bin.005 Slave_IO_Running: Yes Slave_SQL_Running: Yes Replicate_Do_DB: Replicate_Ignore_DB: Last_Errno: 0 Last_Error: Skip_Counter: 0 Exec_Master_Log_Pos: 79 Relay_Log_Space: 552 Until_Condition: None Until_Log_File: Until_Log_Pos: 0 Master_SSL_Allowed: No Master_SSL_CA_File: Master_SSL_CA_Path: Master_SSL_Cert: Master_SSL_Cipher: Master_SSL_Key: Seconds_Behind_Master: 8    
177 GEOMETRY 24 MySQL provides a standard way of creating spatial columns for geometry types, for example, with CREATE TABLE or ALTER TABLE. Currently, spatial columns are supported only for MyISAM tables. mysql> CREATE TABLE geom (g GEOMETRY); Query OK, 0 rows affected (0.02 sec)  
178 NUMPOINTS 18 NumPoints(ls) Returns the number of points in the LineString value ls. mysql> SET @ls = 'LineString(1 1,2 2,3 3)'; mysql> SELECT NumPoints(GeomFromText(@ls)); +------------------------------+ | NumPoints(GeomFromText(@ls)) | +------------------------------+ | 3 | +------------------------------+  
179 & 27 & Bitwise AND: mysql> SELECT 29 & 15; -> 13  
180 LOCALTIMESTAMP 14 LOCALTIMESTAMP LOCALTIMESTAMP() LOCALTIMESTAMP and LOCALTIMESTAMP() are synonyms for NOW().    
181 ADDDATE 14 ADDDATE(date,INTERVAL expr type) ADDDATE(expr,days) When invoked with the INTERVAL form of the second argument, ADDDATE() is a synonym for DATE_ADD(). The related function SUBDATE() is a synonym for DATE_SUB(). For information on the INTERVAL argument, see the discussion for DATE_ADD(). mysql> SELECT DATE_ADD('1998-01-02', INTERVAL 31 DAY); -> '1998-02-02' mysql> SELECT ADDDATE('1998-01-02', INTERVAL 31 DAY); -> '1998-02-02' As of MySQL 4.1.1, the second syntax is allowed, where expr is a date or datetime expression and days is the number of days to be added to expr. mysql> SELECT ADDDATE('1998-01-02', 31); -> '1998-02-02'    
182 SMALLINT 1 SMALLINT[(M)] [UNSIGNED] [ZEROFILL] A small integer. The signed range is -32768 to 32767. The unsigned range is 0 to 65535.    
183 ORD 23 ORD(str) If the leftmost character of the string str is a multi-byte character, returns the code for that character, calculated from the numeric values of its constituent bytes using this formula: (1st byte code) + (2nd byte code * 256) + (3rd byte code * 256^2) ... If the leftmost character is not a multi-byte character, ORD() returns the same value as the ASCII() function. mysql> SELECT ORD('2'); -> 50  
184 ENVELOPE 19 Envelope(g) Returns the Minimum Bounding Rectangle (MBR) for the geometry value g. The result is returned as a Polygon value. mysql> SELECT AsText(Envelope(GeomFromText('LineString(1 1,2 2)'))); +-------------------------------------------------------+ | AsText(Envelope(GeomFromText('LineString(1 1,2 2)'))) | +-------------------------------------------------------+ | POLYGON((1 1,2 1,2 2,1 2,1 1)) | +-------------------------------------------------------+ The polygon is defined by the corner points of the bounding box: POLYGON((MINX MINY, MAXX MINY, MAXX MAXY, MINX MAXY, MINX MINY))    
185 IS_FREE_LOCK 21 IS_FREE_LOCK(str) Checks whether the lock named str is free to use (that is, not locked). Returns 1 if the lock is free (no one is using the lock), 0 if the lock is in use, and NULL on errors (such as incorrect arguments).    
186 SHOW BINLOG 6 SHOW BINLOG EVENTS [IN 'log_name'] [FROM pos] [LIMIT [offset,] row_count] Shows the events in the binary log. If you do not specify 'log_name', the first binary log is displayed.    
187 TOUCHES 11 Touches(g1,g2) Returns 1 or 0 to indicate whether or not g1 spatially touches g2. Two geometries /spatially touch/ if the interiors of the geometries do not intersect, but the boundary of one of the geometries intersects either the boundary or the interior of the other.    
188 TIMESTAMPADD FUNCTION 14   mysql> SELECT TIMESTAMPADD(MINUTE,1,'2003-01-02'); -> '2003-01-02 00:01:00' mysql> SELECT TIMESTAMPADD(WEEK,1,'2003-01-02'); -> '2003-01-09'  
189 INET_ATON 21 INET_ATON(expr) Given the dotted-quad representation of a network address as a string, returns an integer that represents the numeric value of the address. Addresses may be 4- or 8-byte addresses. mysql> SELECT INET_ATON('209.207.224.40'); -> 3520061480  
190 AUTO_INCREMENT 1 The AUTO_INCREMENT attribute can be used to generate a unique identity for new rows: CREATE TABLE animals ( id MEDIUMINT NOT NULL AUTO_INCREMENT, name CHAR(30) NOT NULL, PRIMARY KEY (id) ); INSERT INTO animals (name) VALUES ('dog'),('cat'),('penguin'), ('lax'),('whale'),('ostrich'); SELECT * FROM animals;  
191 UNCOMPRESS 23 UNCOMPRESS(string_to_uncompress) Uncompresses a string compressed by the COMPRESS() function. If the argument is not a compressed value, the result is NULL. This function requires MySQL to have been compiled with a compression library such as zlib. Otherwise, the return value is always NULL. mysql> SELECT UNCOMPRESS(COMPRESS('any string')); -> 'any string' mysql> SELECT UNCOMPRESS('any string'); -> NULL  
192 ISSIMPLE 19 IsSimple(g) Currently, this function is a placeholder and should not be used. If implemented, its behavior will be as described in the next paragraph. Returns 1 if the geometry value g has no anomalous geometric points, such as self-intersection or self-tangency. IsSimple() returns 0 if the argument is not simple, and -1 if it is NULL. The description of each instantiable geometric class given earlier in the chapter includes the specific conditions that cause an instance of that class to be classified as not simple.    
193 - BINARY 4 - Subtraction: mysql> SELECT 3-5; -> -2  
194 GEOMCOLLFROMTEXT 3 GeomCollFromText(wkt[,srid]) GeometryCollectionFromText(wkt[,srid]) Constructs a GEOMETRYCOLLECTION value using its WKT representation and SRID.    
195 WKT DEFINITION 3 The Well-Known Text (WKT) representation of Geometry is designed to exchange geometry data in ASCII form.    
196 CURRENT_TIME 14 CURRENT_TIME CURRENT_TIME() CURRENT_TIME and CURRENT_TIME() are synonyms for CURTIME().    
197 LAST_INSERT_ID 25 LAST_INSERT_ID() LAST_INSERT_ID(expr) Returns the last automatically generated value that was inserted into an AUTO_INCREMENT column. mysql> SELECT LAST_INSERT_ID(); -> 195  
198 LAST_DAY 14 LAST_DAY(date) Takes a date or datetime value and returns the corresponding value for the last day of the month. Returns NULL if the argument is invalid. mysql> SELECT LAST_DAY('2003-02-05'); -> '2003-02-28' mysql> SELECT LAST_DAY('2004-02-05'); -> '2004-02-29' mysql> SELECT LAST_DAY('2004-01-01 01:01:01'); -> '2004-01-31' mysql> SELECT LAST_DAY('2003-03-32'); -> NULL  
199 MEDIUMINT 1 MEDIUMINT[(M)] [UNSIGNED] [ZEROFILL] A medium-size integer. The signed range is -8388608 to 8388607. The unsigned range is 0 to 16777215.    
200 FLOOR 4 FLOOR(X) Returns the largest integer value not greater than X. mysql> SELECT FLOOR(1.23); -> 1 mysql> SELECT FLOOR(-1.23); -> -2  
201 RTRIM 23 RTRIM(str) Returns the string str with trailing space characters removed. mysql> SELECT RTRIM('barbar '); -> 'barbar'  
202 DEGREES 4 DEGREES(X) Returns the argument X, converted from radians to degrees. mysql> SELECT DEGREES(PI()); -> 180.000000  
203 EXPLAIN 6 The EXPLAIN statement can be used either as a synonym for DESCRIBE or as a way to obtain information about how MySQL executes a SELECT statement: --- The EXPLAIN tbl_name syntax is synonymous with DESCRIBE tbl_name or SHOW COLUMNS FROM tbl_name. --- When you precede a SELECT statement with the keyword EXPLAIN, MySQL explains how it would process the SELECT, providing information about how tables are joined and in which order. EXPLAIN tbl_name  
204 VARCHAR 1 [NATIONAL] VARCHAR(M) [BINARY] A variable-length string. M represents the maximum column length. The range of M is 1 to 255 before MySQL 4.0.2, 0 to 255 as of MySQL 4.0.2, and 0 to 65,535 as of MySQL 5.0.3. (The maximum actual length of a VARCHAR in MySQL 5.0 is determined by the maximum row size and the character set you use. The maximum effective length is 65,532 bytes.) Note: Before 5.0.3, trailing spaces were removed when VARCHAR values were stored, which differs from the standard SQL specification. From MySQL 4.1.0 to 5.0.2, a VARCHAR column with a length specification greater than 255 is converted to the smallest TEXT type that can hold values of the given length. For example, VARCHAR(500) is converted to TEXT, and VARCHAR(200000) is converted to MEDIUMTEXT. This is a compatibility feature. However, this conversion affects trailing-space removal. VARCHAR is shorthand for CHARACTER VARYING. As of MySQL 4.1.2, the BINARY attribute is shorthand for specifying the binary collation of the column character set. Sorting and comparison is based on numeric character values. Before 4.1.2, BINARY attribute causes the column to be treated as a binary string. Sorting and comparison is based on numeric byte values. Starting from MySQL 5.0.3, VARCHAR is stored with a one-byte or two-byte length prefix + data. The length prefix is two bytes if the VARCHAR column is declared with a length greater than 255.    
205 UNHEX 23 UNHEX(str) Does the opposite of HEX(str). That is, it interprets each pair of hexadecimal digits in the argument as a number and converts it to the character represented by the number. The resulting characters are returned as a binary string. mysql> SELECT UNHEX('4D7953514C'); -> 'MySQL' mysql> SELECT 0x4D7953514C; -> 'MySQL' mysql> SELECT UNHEX(HEX('string')); -> 'string' mysql> SELECT HEX(UNHEX('1267')); -> '1267'  
206 - UNARY 4 - Unary minus. Changes the sign of the argument. mysql> SELECT - 2; -> -2  
207 COS 4 COS(X) Returns the cosine of X, where X is given in radians. mysql> SELECT COS(PI()); -> -1.000000  
208 DATE FUNCTION 14 DATE(expr) Extracts the date part of the date or datetime expression expr. mysql> SELECT DATE('2003-12-31 01:02:03'); -> '2003-12-31'  
209 RESET MASTER 6 RESET MASTER Deletes all binary logs listed in the index file, resets the binary log index file to be empty, and creates a new binary log file. This statement was named FLUSH MASTER before MySQL 3.23.26.    
210 TAN 4 TAN(X) Returns the tangent of X, where X is given in radians. mysql> SELECT TAN(PI()+1); -> 1.557408  
211 PI 4 PI() Returns the value of PI. The default number of decimals displayed is five, but MySQL internally uses the full double-precision value for PI. mysql> SELECT PI(); -> 3.141593 mysql> SELECT PI()+0.000000000000000000; -> 3.141592653589793116  
212 WEEKOFYEAR 14 WEEKOFYEAR(date) Returns the calendar week of the date as a number in the range from 1 to 53. It is a compatibility function that is equivalent to WEEK(date,3). mysql> SELECT WEEKOFYEAR('1998-02-20'); -> 8  
213 / 4 / Division: mysql> SELECT 3/5; -> 0.60  
214 STDDEV_SAMP 12 STDDEV_SAMP(expr) Returns the sample standard deviation of expr (the square root of VAR_SAMP(). This function was added in MySQL 5.0.3.    
215 MLINEFROMWKB 13 MLineFromWKB(wkb[,srid]) MultiLineStringFromWKB(wkb[,srid]) Constructs a MULTILINESTRING value using its WKB representation and SRID.    
216 UNCOMPRESSED_LENGTH 23 UNCOMPRESSED_LENGTH(compressed_string) Returns the length of a compressed string before compression. mysql> SELECT UNCOMPRESSED_LENGTH(COMPRESS(REPEAT('a',30))); -> 30  
217 LOG2 4 LOG2(X) Returns the base-2 logarithm of X. mysql> SELECT LOG2(65536); -> 16.000000 mysql> SELECT LOG2(-100); -> NULL  
218 SUBTIME 14 SUBTIME(expr,expr2) SUBTIME() subtracts expr2 from expr and returns the result. expr is a time or datetime expression, and expr2 is a time expression. mysql> SELECT SUBTIME('1997-12-31 23:59:59.999999', -> '1 1:1:1.000002'); -> '1997-12-30 22:58:58.999997' mysql> SELECT SUBTIME('01:00:00.999999', '02:00:00.999998'); -> '-00:59:59.999999'  
219 DROP TABLE 28 DROP TABLE removes one or more tables. You must have the DROP privilege for each table. All table data and the table definition are /removed/, so /be careful/ with this statement! In MySQL 3.22 or later, you can use the keywords IF EXISTS to prevent an error from occurring for tables that don't exist. As of MySQL 4.1, a NOTE is generated for each non-existent table when using IF EXISTS. See also : [SHOW WARNINGS, , SHOW WARNINGS]. RESTRICT and CASCADE are allowed to make porting easier. For the moment, they do nothing. Note: DROP TABLE automatically commits the current active transaction, unless you are using MySQL 4.1 or higher and the TEMPORARY keyword. DROP [TEMPORARY] TABLE [IF EXISTS] tbl_name [, tbl_name] ... [RESTRICT | CASCADE]  
220 DUAL 22 SELECT ... FROM DUAL is an alias for SELECT .... (To be compatible with some other databases).    
221 INSTR 23 INSTR(str,substr) Returns the position of the first occurrence of substring substr in string str. This is the same as the two-argument form of LOCATE(), except that the arguments are swapped. mysql> SELECT INSTR('foobarbar', 'bar'); -> 4 mysql> SELECT INSTR('xbar', 'foobar'); -> 0  
222 NOW 14 NOW() Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS format, depending on whether the function is used in a string or numeric context. mysql> SELECT NOW(); -> '1997-12-15 23:50:26' mysql> SELECT NOW() + 0; -> 19971215235026  
223 >= 26 >= Greater than or equal: mysql> SELECT 2 >= 2; -> 1  
224 EXP 4 EXP(X) Returns the value of e (the base of natural logarithms) raised to the power of X. mysql> SELECT EXP(2); -> 7.389056 mysql> SELECT EXP(-2); -> 0.135335  
225 SHA 17 SHA1(str) SHA(str) Calculates an SHA1 160-bit checksum for the string, as described in RFC 3174 (Secure Hash Algorithm). The value is returned as a string of 40 hex digits, or NULL if the argument was NULL. One of the possible uses for this function is as a hash key. You can also use it as a cryptographically safe function for storing passwords. mysql> SELECT SHA1('abc'); -> 'a9993e364706816aba3e25717850c26c9cd0d89d'  
226 LONGBLOB 1 LONGBLOB A BLOB column with a maximum length of 4,294,967,295 or 4GB (2^32 - 1) bytes. Up to MySQL 3.23, the client/server protocol and MyISAM tables had a limit of 16MB per communication packet / table row. From MySQL 4.0, the maximum allowed length of LONGBLOB columns depends on the configured maximum packet size in the client/server protocol and available memory.    
227 POINTN 18 PointN(ls,n) Returns the n-th point in the Linestring value ls. Point numbers begin at 1. mysql> SET @ls = 'LineString(1 1,2 2,3 3)'; mysql> SELECT AsText(PointN(GeomFromText(@ls),2)); +-------------------------------------+ | AsText(PointN(GeomFromText(@ls),2)) | +-------------------------------------+ | POINT(2 2) | +-------------------------------------+  
228 SUM 12 SUM([DISTINCT] expr) Returns the sum of expr. If the return set has no rows, SUM() returns NULL. The DISTINCT keyword can be used as of MySQL 5.0.0 to sum only the distinct values of expr.    
229 OCT 23 OCT(N) Returns a string representation of the octal value of N, where N is a longlong (BIGINT)number. This is equivalent to CONV(N,10,8). Returns NULL if N is NULL. mysql> SELECT OCT(12); -> '14'  
230 SYSDATE 14 SYSDATE() SYSDATE() is a synonym for NOW().    
231 ASBINARY 13 AsBinary(g) Converts a value in internal geometry format to its WKB representation and returns the binary result. SELECT AsBinary(g) FROM geom;  
232 MAKEDATE 14 MAKEDATE(year,dayofyear) Returns a date, given year and day-of-year values. dayofyear must be greater than 0 or the result is NULL. mysql> SELECT MAKEDATE(2001,31), MAKEDATE(2001,32); -> '2001-01-31', '2001-02-01' mysql> SELECT MAKEDATE(2001,365), MAKEDATE(2004,365); -> '2001-12-31', '2004-12-30' mysql> SELECT MAKEDATE(2001,0); -> NULL  
233 BINARY OPERATOR 23 BINARY The BINARY operator casts the string following it to a binary string. This is an easy way to force a column comparison to be done byte by byte rather than character by character. This causes the comparison to be case sensitive even if the column isn't defined as BINARY or BLOB. BINARY also causes trailing spaces to be significant. mysql> SELECT 'a' = 'A'; -> 1 mysql> SELECT BINARY 'a' = 'A'; -> 0 mysql> SELECT 'a' = 'a '; -> 1 mysql> SELECT BINARY 'a' = 'a '; -> 0  
234 MBROVERLAPS 8 MBROverlaps(g1,g2) Returns 1 or 0 to indicate whether or not the Minimum Bounding Rectangles of the two geometries g1 and g2 overlap.    
235 SOUNDEX 23 SOUNDEX(str) Returns a soundex string from str. Two strings that sound almost the same should have identical soundex strings. A standard soundex string is four characters long, but the SOUNDEX() function returns an arbitrarily long string. You can use SUBSTRING() on the result to get a standard soundex string. All non-alphabetic characters are ignored in the given string. All international alphabetic characters outside the A-Z range are treated as vowels. mysql> SELECT SOUNDEX('Hello'); -> 'H400' mysql> SELECT SOUNDEX('Quadratically'); -> 'Q36324'  
236 SHOW MASTER LOGS 6 SHOW MASTER LOGS SHOW BINARY LOGS Lists the binary log files on the server. This statement is used as part of the procedure described in [PURGE MASTER LOGS, , PURGE MASTER LOGS] for determining which logs can be purged. mysql> SHOW BINARY LOGS; +---------------+-----------+ | Log_name | File_size | +---------------+-----------+ | binlog.000015 | 724935 | | binlog.000016 | 733481 | +---------------+-----------+    
237 MBRTOUCHES 8 MBRTouches(g1,g2) Returns 1 or 0 to indicate whether or not the Minimum Bounding Rectangles of the two geometries g1 and g2 touch.    
238 INSERT SELECT 6 INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE] [INTO] tbl_name [(col_name,...)] SELECT ... [ ON DUPLICATE KEY UPDATE col_name=expr, ... ] With INSERT ... SELECT, you can quickly insert many rows into a table from one or many tables. INSERT INTO tbl_temp2 (fld_id) SELECT tbl_temp1.fld_order_id FROM tbl_temp1 WHERE tbl_temp1.fld_order_id > 100;  
239 VARBINARY 1 VARBINARY(M) The VARBINARY type is similar to the VARCHAR type, but stores binary byte strings rather than non-binary character strings. This type was added in MySQL 4.1.2.    
240 LOAD INDEX 6 The LOAD INDEX INTO CACHE statement preloads a table index into the key cache to which it has been assigned by an explicit CACHE INDEX statement, or into the default key cache otherwise. LOAD INDEX INTO CACHE is used only for MyISAM tables. The IGNORE LEAVES modifier causes only blocks for the non-leaf nodes of the index to be preloaded. LOAD INDEX INTO CACHE tbl_index_list [, tbl_index_list] ... tbl_index_list: tbl_name [[INDEX|KEY] (index_name[, index_name] ...)] [IGNORE LEAVES]  
241 UNION 6 UNION is used to combine the result from many SELECT statements into one result set. UNION is available from MySQL 4.0.0 on. Selected columns listed in corresponding positions of each SELECT statement should have the same type. (For example, the first column selected by the first statement should have the same type as the first column selected by the other statements.) The column names used in the first SELECT statement are used as the column names for the results returned. SELECT ... UNION [ALL | DISTINCT] SELECT ... [UNION [ALL | DISTINCT] SELECT ...]  
242 TO_DAYS 14 TO_DAYS(date) Given a date date, returns a daynumber (the number of days since year 0). mysql> SELECT TO_DAYS(950501); -> 728779 mysql> SELECT TO_DAYS('1997-10-07'); -> 729669  
243 NOT REGEXP 23 expr NOT REGEXP pat expr NOT RLIKE pat This is the same as NOT (expr REGEXP pat).    
244 NOT IN 26 expr NOT IN (value,...) This is the same as NOT (expr IN (value,...)).    
245 ! 20 NOT ! Logical NOT. Evaluates to 1 if the operand is 0, to 0 if the operand is non-zero, and NOT NULL returns NULL. mysql> SELECT NOT 10; -> 0 mysql> SELECT NOT 0; -> 1 mysql> SELECT NOT NULL; -> NULL mysql> SELECT ! (1+1); -> 0 mysql> SELECT ! 1+1; -> 1  
246 TEXT TYPE 1 TEXT[(M)] A TEXT column with a maximum length of 65,535 (2^16 - 1) characters. Beginning with MySQL 4.1, an optional length M can be given. MySQL will create the column as the smallest TEXT type largest enough to hold values M characters long.    
247 DOUBLE 1 DOUBLE[(M,B)] [UNSIGNED] [ZEROFILL] A normal-size (double-precision) floating-point number. Allowable values are -1.7976931348623157E+308 to -2.2250738585072014E-308, 0, and 2.2250738585072014E-308 to 1.7976931348623157E+308. If UNSIGNED is specified, negative values are disallowed. M is the display width and B is the number of bits of precision. DOUBLE without arguments or FLOAT(p) (where p is in the range from 25 to 53) stands for a double-precision floating-point number. A single-precision floating-point number is accurate to approximately 7 decimal places; a double-precision floating-point number is accurate to approximately 15 decimal places. DOUBLE PRECISION[(M,D)] [UNSIGNED] [ZEROFILL] REAL[(M,D)] [UNSIGNED] [ZEROFILL] These are synonyms for DOUBLE. Exception: If the server SQL mode includes the REAL_AS_FLOAT option, REAL is a synonym for FLOAT rather than DOUBLE.    
248 TIME 1 TIME A time. The range is '-838:59:59' to '838:59:59'. MySQL displays TIME values in 'HH:MM:SS' format, but allows you to assign values to TIME columns using either strings or numbers.    
249 && 20 AND && Logical AND. Evaluates to 1 if all operands are non-zero and not NULL, to 0 if one or more operands are 0, otherwise NULL is returned. mysql> SELECT 1 && 1; -> 1 mysql> SELECT 1 && 0; -> 0 mysql> SELECT 1 && NULL; -> NULL mysql> SELECT 0 && NULL; -> 0 mysql> SELECT NULL && 0; -> 0  
250 X 16 X(p) Returns the X-coordinate value for the point p as a double-precision number. mysql> SELECT X(GeomFromText('Point(56.7 53.34)')); +--------------------------------------+ | X(GeomFromText('Point(56.7 53.34)')) | +--------------------------------------+ | 56.7 | +--------------------------------------+  
251 FOUND_ROWS 25 A SELECT statement may include a LIMIT clause to restrict the number of rows the server returns to the client. In some cases, it is desirable to know how many rows the statement would have returned without the LIMIT, but without running the statement again. To get this row count, include a SQL_CALC_FOUND_ROWS option in the SELECT statement, then invoke FOUND_ROWS() afterward: mysql> SELECT SQL_CALC_FOUND_ROWS * FROM tbl_name -> WHERE id > 100 LIMIT 10; mysql> SELECT FOUND_ROWS();  
252 SYSTEM_USER 25 SYSTEM_USER() SYSTEM_USER() is a synonym for USER().    
253 CROSSES 11 Crosses(g1,g2) Returns 1 if g1 spatially crosses g2. Returns NULL if g1 is a Polygon or a MultiPolygon, or if g2 is a Point or a MultiPoint. Otherwise, returns 0. The term /spatially crosses/ denotes a spatial relation between two given geometries that has the following properties: --- The two geometries intersect --- Their intersection results in a geometry that has a dimension that is one less than the maximum dimension of the two given geometries --- Their intersection is not equal to either of the two given geometries    
254 TRUNCATE TABLE 6 TRUNCATE TABLE empties a table completely. Logically, this is equivalent to a DELETE statement that deletes all rows, but there are practical differences under some circumstances. For InnoDB before version 5.0.3, TRUNCATE TABLE is mapped to DELETE, so there is no difference. Starting with MySQL/InnoDB-5.0.3, fast TRUNCATE TABLE is available. The operation is still mapped to DELETE if there are foreign key constraints that reference the table. For other storage engines, TRUNCATE TABLE differs from DELETE FROM in the following ways from MySQL 4.0 and up: --- Truncate operations drop and re-create the table, which is much faster than deleting rows one by one. --- Truncate operations are not transaction-safe; you get an error if you have an active transaction or an active table lock. --- The number of deleted rows is not returned. --- As long as the table definition file *tbl_name.frm is valid, the table can be re-created as an empty table with TRUNCATE TABLE, even if the data or index files have become corrupted. --- The table handler does not remember the last used AUTO_INCREMENT value, but starts counting from the beginning. This is true even for MyISAM and InnoDB, which normally does not reuse sequence values. In MySQL 3.23, TRUNCATE TABLE is mapped to COMMIT; DELETE FROM tbl_name, so it behaves like DELETE. See also : [DELETE, , DELETE]. TRUNCATE TABLE is an Oracle SQL extension. This statement was added in MySQL 3.23.28, although from 3.23.28 to 3.23.32, the keyword TABLE must be omitted. TRUNCATE TABLE tbl_name  
255 CURRENT_DATE 14 CURRENT_DATE CURRENT_DATE() CURRENT_DATE and CURRENT_DATE() are synonyms for CURDATE().    
256 BIT_XOR 12 BIT_XOR(expr) Returns the bitwise XOR of all bits in expr. The calculation is performed with 64-bit (BIGINT) precision.    
257 AREA 0 Area(poly) Returns as a double-precision number the area of the Polygon value poly, as measured in its spatial reference system. mysql> SET @poly = 'Polygon((0 0,0 3,3 0,0 0),(1 1,1 2,2 1,1 1))'; mysql> SELECT Area(GeomFromText(@poly)); +---------------------------+ | Area(GeomFromText(@poly)) | +---------------------------+ | 4 | +---------------------------+  
258 START SLAVE 7 START SLAVE [thread_type [, thread_type] ... ] START SLAVE [SQL_THREAD] UNTIL MASTER_LOG_FILE = 'log_name', MASTER_LOG_POS = log_pos START SLAVE [SQL_THREAD] UNTIL RELAY_LOG_FILE = 'log_name', RELAY_LOG_POS = log_pos thread_type: IO_THREAD | SQL_THREAD START SLAVE with no options starts both of the slave threads. The I/O thread reads queries from the master server and stores them in the relay log. The SQL thread reads the relay log and executes the queries. START SLAVE requires the SUPER privilege. If START SLAVE succeeds in starting the slave threads, it returns without any error. However, even in that case, it might be that the slave threads start and then later stop (for example, because they don't manage to connect to the master or read its binary logs, or some other problem). START SLAVE does not warn you about this. You must check your slave's error log for error messages generated by the slave threads, or check that they are running fine with SHOW SLAVE STATUS.    
259 FLUSH 6 You should use the FLUSH statement if you want to clear some of the internal caches MySQL uses. To execute FLUSH, you must have the RELOAD privilege. FLUSH [LOCAL | NO_WRITE_TO_BINLOG] flush_option [, flush_option] ...  
260 DESCRIBE 7 {DESCRIBE | DESC} tbl_name [col_name | wild] DESCRIBE provides information about the columns in a table. It is a shortcut for SHOW COLUMNS FROM. As of MySQL 5.0.1, these statements also display information for views.    
261 STDDEV_POP 12 STDDEV_POP(expr) Returns the population standard deviation of expr (the square root of VAR_POP()). This function was added in MySQL 5.0.3. Before 5.0.3, you can use STD() or STDDEV(), which are equivalent but not standard SQL.    
262 SUBSTRING 23 SUBSTRING(str,pos) SUBSTRING(str FROM pos) SUBSTRING(str,pos,len) SUBSTRING(str FROM pos FOR len) The forms without a len argument return a substring from string str starting at position pos. The forms with a len argument return a substring len characters long from string str, starting at position pos. The forms that use FROM are standard SQL syntax. mysql> SELECT SUBSTRING('Quadratically',5); -> 'ratically' mysql> SELECT SUBSTRING('foobarbar' FROM 4); -> 'barbar' mysql> SELECT SUBSTRING('Quadratically',5,6); -> 'ratica'  
263 ISEMPTY 19 IsEmpty(g) Returns 1 if the geometry value g is the empty geometry, 0 if it is not empty, and -1 if the argument is NULL. If the geometry is empty, it represents the empty point set.    
264 LTRIM 23 LTRIM(str) Returns the string str with leading space characters removed. mysql> SELECT LTRIM(' barbar'); -> 'barbar'  
265 REPAIR 7 REPAIR TABLE repairs a possibly corrupted table. By default, it has the same effect as myisamchk --recover tbl_name. REPAIR TABLE works only on MyISAM tables. REPAIR [LOCAL | NO_WRITE_TO_BINLOG] TABLE tbl_name [, tbl_name] ... [QUICK] [EXTENDED] [USE_FRM]  
266 INTERSECTS 11 Intersects(g1,g2) Returns 1 or 0 to indicate whether or not g1 spatially intersects g2.    
267 MBRDISJOINT 8 MBRDisjoint(g1,g2) Returns 1 or 0 to indicate whether or not the Minimum Bounding Rectangles of the two geometries g1 and g2 are disjoint (do not intersect).    
268 SUBSTRING_INDEX 23 SUBSTRING_INDEX(str,delim,count) Returns the substring from string str before count occurrences of the delimiter delim. If count is positive, everything to the left of the final delimiter (counting from the left) is returned. If count is negative, everything to the right of the final delimiter (counting from the right) is returned. mysql> SELECT SUBSTRING_INDEX('www.mysql.com', '.', 2); -> 'www.mysql' mysql> SELECT SUBSTRING_INDEX('www.mysql.com', '.', -2); -> 'mysql.com'  
269 ENCODE 17 ENCODE(str,pass_str) Encrypt str using pass_str as the password. To decrypt the result, use DECODE(). The result is a binary string of the same length as str. If you want to save it in a column, use a BLOB column type.    
270 TRUNCATE 4 TRUNCATE(X,D) Returns the number X, truncated to D decimals. If D is 0, the result has no decimal point or fractional part. D can be negative to truncate (make zero) D digits left of the decimal point of the value X. mysql> SELECT TRUNCATE(1.223,1); -> 1.2 mysql> SELECT TRUNCATE(1.999,1); -> 1.9 mysql> SELECT TRUNCATE(1.999,0); -> 1 mysql> SELECT TRUNCATE(-1.999,1); -> -1.9 mysql> SELECT TRUNCATE(122,-2); -> 100  
271 TIMESTAMPADD 14 TIMESTAMPADD(interval,int_expr,datetime_expr) Adds the integer expression int_expr to the date or datetime expression datetime_expr. The unit for int_expr is given by the interval argument, which should be one of the following values: FRAC_SECOND, SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, or YEAR. The interval value may be specified using one of keywords as shown, or with a prefix of SQL_TSI_. For example, DAY or SQL_TSI_DAY both are legal.    
272 SHOW 6 SHOW has many forms that provide information about databases, tables, columns, or status information about the server. This section describes those following: SHOW [FULL] COLUMNS FROM tbl_name [FROM db_name] [LIKE 'pattern'] SHOW CREATE DATABASE db_name SHOW CREATE TABLE tbl_name SHOW DATABASES [LIKE 'pattern'] SHOW ENGINE engine_name {LOGS | STATUS } SHOW [STORAGE] ENGINES SHOW ERRORS [LIMIT [offset,] row_count] SHOW GRANTS FOR user SHOW INDEX FROM tbl_name [FROM db_name] SHOW INNODB STATUS SHOW [BDB] LOGS SHOW PRIVILEGES SHOW [FULL] PROCESSLIST SHOW [GLOBAL | SESSION] STATUS [LIKE 'pattern'] SHOW TABLE STATUS [FROM db_name] [LIKE 'pattern'] SHOW [OPEN] TABLES [FROM db_name] [LIKE 'pattern'] SHOW [GLOBAL | SESSION] VARIABLES [LIKE 'pattern'] SHOW WARNINGS [LIMIT [offset,] row_count] The SHOW statement also has forms that provide information about replication master and slave servers and are described in [Replication SQL]: SHOW BINLOG EVENTS SHOW MASTER LOGS SHOW MASTER STATUS SHOW SLAVE HOSTS SHOW SLAVE STATUS If the syntax for a given SHOW statement includes a LIKE 'pattern' part, 'pattern' is a string that can contain the SQL '%' and '_' wildcard characters. The pattern is useful for restricting statement output to matching values.    
273 GREATEST 26 GREATEST(value1,value2,...) With two or more arguments, returns the largest (maximum-valued) argument. The arguments are compared using the same rules as for LEAST(). mysql> SELECT GREATEST(2,0); -> 2 mysql> SELECT GREATEST(34.0,3.0,5.0,767.0); -> 767.0 mysql> SELECT GREATEST('B','A','C'); -> 'C'  
274 OCTETLENGTH 23 OCTET_LENGTH(str) OCTET_LENGTH() is a synonym for LENGTH().    
275 SECOND 14 SECOND(time) Returns the second for time, in the range 0 to 59. mysql> SELECT SECOND('10:05:03'); -> 3  
276 BIT_AND 12 BIT_AND(expr) Returns the bitwise AND of all bits in expr. The calculation is performed with 64-bit (BIGINT) precision. mysql> SELECT order.custid, customer.name, MAX(payments) -> FROM order,customer -> WHERE order.custid = customer.custid -> GROUP BY order.custid;  
277 ATAN2 4 ATAN(Y,X) ATAN2(Y,X) Returns the arc tangent of the two variables X and Y. It is similar to calculating the arc tangent of Y / X, except that the signs of both arguments are used to determine the quadrant of the result. mysql> SELECT ATAN(-2,2); -> -0.785398 mysql> SELECT ATAN2(PI(),0); -> 1.570796  
278 MBRCONTAINS 8 MBRContains(g1,g2) Returns 1 or 0 to indicate whether or not the Minimum Bounding Rectangle of g1 contains the Minimum Bounding Rectangle of g2. mysql> SET @g1 = GeomFromText('Polygon((0 0,0 3,3 3,3 0,0 0))'); mysql> SET @g2 = GeomFromText('Point(1 1)'); mysql> SELECT MBRContains(@g1,@g2), MBRContains(@g2,@g1); ----------------------+----------------------+ | MBRContains(@g1,@g2) | MBRContains(@g2,@g1) | +----------------------+----------------------+ | 1 | 0 | +----------------------+----------------------+  
279 HOUR 14 HOUR(time) Returns the hour for time. The range of the return value is 0 to 23 for time-of-day values. mysql> SELECT HOUR('10:05:03'); -> 10  
280 TYPE SET 1 SET('value1','value2',...) A set. A string object that can have zero or more values, each of which must be chosen from the list of values 'value1', 'value2', ... A SET column can have a maximum of 64 members. SET values are represented internally as integers.    
281 SELECT 6 SELECT is used to retrieve rows selected from one or more tables. Support for UNION statements and subqueries is available as of MySQL 4.0 and 4.1, respectively. See [UNION, , UNION] and [Subqueries]. --- Each select_expr indicates a column you want to retrieve. --- table_references indicates the table or tables from which to retrieve rows. Its syntax is described in [JOIN, , JOIN]. --- where_definition consists of the keyword WHERE followed by an expression that indicates the condition or conditions that rows must satisfy to be selected. SELECT can also be used to retrieve rows computed without reference to any table. SELECT [ALL | DISTINCT | DISTINCTROW ] [HIGH_PRIORITY] [STRAIGHT_JOIN] [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT] [SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS] select_expr, ... [INTO OUTFILE 'file_name' export_options | INTO DUMPFILE 'file_name'] [FROM table_references [WHERE where_definition] [GROUP BY {col_name | expr | position} [ASC | DESC], ... [WITH ROLLUP]] [HAVING where_definition] [ORDER BY {col_name | expr | position} [ASC | DESC] , ...] [LIMIT {[offset,] row_count | row_count OFFSET offset}] [PROCEDURE procedure_name(argument_list)] [FOR UPDATE | LOCK IN SHARE MODE]]  
282 COT 4 COT(X) Returns the cotangent of X. mysql> SELECT COT(12); -> -1.57267341 mysql> SELECT COT(0); -> NULL  
283 BACKUP TABLE 7 Note: This statement is deprecated. We are working on a better replacement for it that will provide online backup capabilities. In the meantime, the mysqlhotcopy script can be used instead. BACKUP TABLE copies to the backup directory the minimum number of table files needed to restore the table, after flushing any buffered changes to disk. The statement works only for MyISAM tables. It copies the *.frm definition and *.MYD data files. The *.MYI index file can be rebuilt from those two files. The directory should be specified as a full pathname. BACKUP TABLE tbl_name [, tbl_name] ... TO '/path/to/backup/directory'  
284 LOAD_FILE 23 LOAD_FILE(file_name) Reads the file and returns the file contents as a string. The file must be located on the server, you must specify the full pathname to the file, and you must have the FILE privilege. The file must be readable by all and be smaller than max_allowed_packet bytes. If the file doesn't exist or cannot be read because one of the preceding conditions is not satisfied, the function returns NULL. mysql> UPDATE tbl_name SET blob_column=LOAD_FILE('/tmp/picture') WHERE id=1;  
285 POINTFROMTEXT 3 PointFromText(wkt[,srid]) Constructs a POINT value using its WKT representation and SRID.    
286 LOAD TABLE FROM MASTER 6 LOAD TABLE tbl_name FROM MASTER Transfers a copy of the table from master to the slave. This statement is implemented mainly for debugging of LOAD DATA FROM MASTER. It requires that the account used for connecting to the master server has the RELOAD and SUPER privileges on the master and the SELECT privilege on the master table to load. On the slave side, the user that issues LOAD TABLE FROM MASTER should have privileges to drop and create the table. The conditions for LOAD DATA FROM MASTER apply here, too. For example, LOAD TABLE FROM MASTER works only for MyISAM tables. The timeout notes for LOAD DATA FROM MASTER apply as well.    
287 GROUP_CONCAT 12 GROUP_CONCAT(expr) This function returns a string result with the concatenated non-NULL values from a group. It returns NULL if there are no non-NULL values. The full syntax is as follows: GROUP_CONCAT([DISTINCT] expr [,expr ...] [ORDER BY {unsigned_integer | col_name | expr} [ASC | DESC] [,col_name ...]] [SEPARATOR str_val]) mysql> SELECT student_name, -> GROUP_CONCAT(test_score) -> FROM student -> GROUP BY student_name;  
288 DATE_FORMAT 14 DATE_FORMAT(date,format) Formats the date value according to the format string. The following specifiers may be used in the format string: Specifier Description %a Abbreviated weekday name (Sun..Sat) %b Abbreviated month name (Jan..Dec) %c Month, numeric (0..12) %D Day of the month with English suffix (0th, 1st, 2nd, 3rd, ...) %d Day of the month, numeric (00..31) %e Day of the month, numeric (0..31) %f Microseconds (000000..999999) %H Hour (00..23) %h Hour (01..12) %I Hour (01..12) %i Minutes, numeric (00..59) %j Day of year (001..366) %k Hour (0..23) %l Hour (1..12) %M Month name (January..December) %m Month, numeric (00..12) %p AM or PM %r Time, 12-hour (hh:mm:ss followed by AM or PM) %S Seconds (00..59) %s Seconds (00..59) %T Time, 24-hour (hh:mm:ss) %U Week (00..53), where Sunday is the first day of the week %u Week (00..53), where Monday is the first day of the week %V Week (01..53), where Sunday is the first day of the week; used with %X %v Week (01..53), where Monday is the first day of the week; used with %x %W Weekday name (Sunday..Saturday) %w Day of the week (0=Sunday..6=Saturday) %X Year for the week where Sunday is the first day of the week, numeric, four digits; used with %V %x Year for the week, where Monday is the first day of the week, numeric, four digits; used with %v %Y Year, numeric, four digits %y Year, numeric, two digits %% A literal '%'. All other characters are copied to the result without interpretation. The %v, %V, %x, and %X format specifiers are available as of MySQL 3.23.8. %f is available as of MySQL 4.1.1. As of MySQL 3.23, the '%' character is required before format specifier characters. In earlier versions of MySQL, '%' was optional. The reason the ranges for the month and day specifiers begin with zero is that MySQL allows incomplete dates such as '2004-00-00' to be stored as of MySQL 3.23. mysql> SELECT DATE_FORMAT('1997-10-04 22:23:00', '%W %M %Y'); -> 'Saturday October 1997' mysql> SELECT DATE_FORMAT('1997-10-04 22:23:00', '%H:%i:%s'); -> '22:23:00' mysql> SELECT DATE_FORMAT('1997-10-04 22:23:00', '%D %y %a %d %m %b %j'); -> '4th 97 Sat 04 10 Oct 277' mysql> SELECT DATE_FORMAT('1997-10-04 22:23:00', '%H %k %I %r %T %S %w'); -> '22 22 10 10:23:00 PM 22:23:00 00 6' mysql> SELECT DATE_FORMAT('1999-01-01', '%X %V'); -> '1998 52'  
289 BENCHMARK 25 BENCHMARK(count,expr) The BENCHMARK() function executes the expression expr repeatedly count times. It may be used to time how fast MySQL processes the expression. The result value is always 0. The intended use is from within the mysql client, which reports query execution times: mysql> SELECT BENCHMARK(1000000,ENCODE('hello','goodbye')); +----------------------------------------------+ | BENCHMARK(1000000,ENCODE('hello','goodbye')) | +----------------------------------------------+ | 0 | +----------------------------------------------+ 1 row in set (4.74 sec)  
290 YEAR 14 YEAR(date) Returns the year for date, in the range 1000 to 9999. mysql> SELECT YEAR('98-02-03'); -> 1998  
291 SHOW ENGINE 6 SHOW ENGINE displays log or status information about storage engines. The following statements currently are supported: SHOW ENGINE BDB LOGS SHOW ENGINE INNODB STATUS SHOW ENGINE BDB LOGS displays status information about existing BDB log files. It returns the following fields: File The full path to the log file. Type The log file type (BDB for Berkeley DB log files). Status The status of the log file (FREE if the file can be removed, or IN USE if the file is needed by the transaction subsystem) SHOW ENGINE INNODB STATUS displays extensive information about the state of the InnoDB storage engine. Older (and now deprecated) synonyms for these statements are SHOW [BDB] LOGS and SHOW INNODB STATUS. SHOW ENGINE can be used as of MySQL 4.1.2. SHOW ENGINE engine_name {LOGS | STATUS }  
292 RELEASE_LOCK 21 RELEASE_LOCK(str) Releases the lock named by the string str that was obtained with GET_LOCK(). Returns 1 if the lock was released, 0 if the lock wasn't locked by this thread (in which case the lock is not released), and NULL if the named lock didn't exist. The lock does not exist if it was never obtained by a call to GET_LOCK() or if it has previously been released. The DO statement is convenient to use with RELEASE_LOCK(). See also : [DO, , DO].    
293 IS NULL 26 IS NULL IS NOT NULL Tests whether a value is or is not NULL. mysql> SELECT 1 IS NULL, 0 IS NULL, NULL IS NULL; -> 0, 0, 1 mysql> SELECT 1 IS NOT NULL, 0 IS NOT NULL, NULL IS NOT NULL; -> 1, 1, 0  
294 CONVERT_TZ 14 CONVERT_TZ(dt,from_tz,to_tz) CONVERT_TZ() converts a datetime value dt from time zone given by from_tz to the time zone given by to_tz and returns the resulting value. Time zones may be specified as described in [Time zone support]. This function returns NULL if the arguments are invalid. mysql> SELECT CONVERT_TZ('2004-01-01 12:00:00','GMT','MET'); -> '2004-01-01 13:00:00' mysql> SELECT CONVERT_TZ('2004-01-01 12:00:00','+00:00','-07:00'); -> '2004-01-01 05:00:00'  
295 TIME_TO_SEC 14 TIME_TO_SEC(time) Returns the time argument, converted to seconds. mysql> SELECT TIME_TO_SEC('22:23:00'); -> 80580 mysql> SELECT TIME_TO_SEC('00:39:38'); -> 2378  
296 WEEKDAY 14 WEEKDAY(date) Returns the weekday index for date (0 = Monday, 1 = Tuesday, ... 6 = Sunday). mysql> SELECT WEEKDAY('1998-02-03 22:23:00'); -> 1 mysql> SELECT WEEKDAY('1997-11-05'); -> 2  
297 EXPORT_SET 23 EXPORT_SET(bits,on,off[,separator[,number_of_bits]]) Returns a string in which for every bit set in the value bits, you get an on string and for every reset bit you get an off string. Bits in bits are examined from right to left (from low-order to high-order bits). Strings are added to the result from left to right, separated by the separator string (default ','). The number of bits examined is given by number_of_bits (default 64). mysql> SELECT EXPORT_SET(5,'Y','N',',',4); -> 'Y,N,Y,N' mysql> SELECT EXPORT_SET(6,'1','0',',',10); -> '0,1,1,0,0,0,0,0,0,0'  
298 TIME FUNCTION 14 TIME(expr) Extracts the time part of the time or datetime expression expr. mysql> SELECT TIME('2003-12-31 01:02:03'); -> '01:02:03' mysql> SELECT TIME('2003-12-31 01:02:03.000123'); -> '01:02:03.000123'  
299 CAST 23 The CAST() and CONVERT() functions can be used to take a value of one type and produce a value of another type. The type can be one of the following values: --- BINARY --- CHAR --- DATE --- DATETIME --- SIGNED [INTEGER] --- TIME --- UNSIGNED [INTEGER] BINARY produces a binary string. See the entry for the BINARY operator in this section for a description of how this affects comparisons. CAST() and CONVERT() are available as of MySQL 4.0.2. The CHAR conversion type is available as of 4.0.6. The USING form of CONVERT() is available as of 4.1.0. CAST() and CONVERT(... USING ...) are standard SQL syntax. The non-USING form of CONVERT() is ODBC syntax. CONVERT() with USING is used to convert data between different character sets. In MySQL, transcoding names are the same as the corresponding character set names. For example, this statement converts the string 'abc' in the server's default character set to the corresponding string in the utf8 character set: SELECT CONVERT('abc' USING utf8); The cast functions are useful when you want to create a column with a specific type in a CREATE ... SELECT statement: SELECT enum_col FROM tbl_name ORDER BY CAST(enum_col AS CHAR);  
300 SOUNDS LIKE 23 expr1 SOUNDS LIKE expr2 This is the same as SOUNDEX(expr1) = SOUNDEX(expr2). It is available only in MySQL 4.1 or later.    
301 PERIOD_DIFF 14 PERIOD_DIFF(P1,P2) Returns the number of months between periods P1 and P2. P1 and P2 should be in the format YYMM or YYYYMM. Note that the period arguments P1 and P2 are /not/ date values. mysql> SELECT PERIOD_DIFF(9802,199703); -> 11  
302 LIKE 23 expr LIKE pat [ESCAPE 'escape-char'] Pattern matching using SQL simple regular expression comparison. Returns 1 (TRUE) or 0 (FALSE). If either expr or pat is NULL, the result is NULL. The pattern need not be a literal string. For example, it can be specified as a string expression or table column. With LIKE you can use the following two wildcard characters in the pattern: Character Description % Matches any number of characters, even zero characters _ Matches exactly one character mysql> SELECT 'David!' LIKE 'David_'; -> 1 mysql> SELECT 'David!' LIKE '%D%v%'; -> 1  
303 MULTIPOINT 2 MultiPoint(pt1,pt2,...) Constructs a WKB MultiPoint value using WKB Point arguments. If any argument is not a WKB Point, the return value is NULL.    
304 >> 27 >> Shifts a longlong (BIGINT) number to the right. mysql> SELECT 4 >> 2; -> 1  
305 TRUE FALSE 22 TRUE and FALSE added as alias for 1 and 0, respectively.    
306 AVG 12 AVG([DISTINCT] expr) Returns the average value of expr. The DISTINCT option can be used as of MySQL 5.0.3 to return the averge of the distinct values of expr. mysql> SELECT student_name, AVG(test_score) -> FROM student -> GROUP BY student_name;  
307 MBRWITHIN 8 MBRWithin(g1,g2) Returns 1 or 0 to indicate whether or not the Minimum Bounding Rectangle of g1 is within the Minimum Bounding Rectangle of g2. mysql> SET @g1 = GeomFromText('Polygon((0 0,0 3,3 3,3 0,0 0))'); mysql> SET @g2 = GeomFromText('Polygon((0 0,0 5,5 5,5 0,0 0))'); mysql> SELECT MBRWithin(@g1,@g2), MBRWithin(@g2,@g1); +--------------------+--------------------+ | MBRWithin(@g1,@g2) | MBRWithin(@g2,@g1) | +--------------------+--------------------+ | 1 | 0 | +--------------------+--------------------+  
308 IN 26 expr IN (value,...) Returns 1 if expr is any of the values in the IN list, else returns 0. If all values are constants, they are evaluated according to the type of expr and sorted. The search for the item then is done using a binary search. This means IN is very quick if the IN value list consists entirely of constants. If expr is a case-sensitive string expression, the string comparison is performed in case-sensitive fashion. mysql> SELECT 2 IN (0,3,5,'wefwf'); -> 0 mysql> SELECT 'wefwf' IN (0,3,5,'wefwf'); -> 1  
309 QUOTE 23 QUOTE(str) Quotes a string to produce a result that can be used as a properly escaped data value in an SQL statement. The string is returned surrounded by single quotes and with each instance of single quote ('''), backslash ('\'), ASCII NUL, and Control-Z preceded by a backslash. If the argument is NULL, the return value is the word ``NULL'' without surrounding single quotes. The QUOTE() function was added in MySQL 4.0.3. mysql> SELECT QUOTE('Don\'t!'); -> 'Don\'t!' mysql> SELECT QUOTE(NULL); -> NULL  
310 SESSION_USER 25 SESSION_USER() SESSION_USER() is a synonym for USER().    
311 QUARTER 14 QUARTER(date) Returns the quarter of the year for date, in the range 1 to 4. mysql> SELECT QUARTER('98-04-01'); -> 2  
312 POSITION 23 POSITION(substr IN str) POSITION(substr IN str) is a synonym for LOCATE(substr,str). mysql> SELECT LOCATE('bar', 'foobarbar'); -> 4 mysql> SELECT LOCATE('xbar', 'foobar'); -> 0 mysql> SELECT LOCATE('bar', 'foobarbar',5); -> 7  
313 IS_USED_LOCK 21 IS_USED_LOCK(str) Checks whether the lock named str is in use (that is, locked). If so, it returns the connection identifier of the client that holds the lock. Otherwise, it returns NULL.    
314 POLYFROMTEXT 3 PolyFromText(wkt[,srid]) PolygonFromText(wkt[,srid]) Constructs a POLYGON value using its WKT representation and SRID.    
315 DES_ENCRYPT 17 DES_ENCRYPT(str[,(key_num|key_str)]) Encrypts the string with the given key using the Triple-DES algorithm. On error, this function returns NULL. Note that this function works only if MySQL has been configured with SSL support. See also : [Secure connections]. The encryption key to use is chosen based on the second argument to DES_ENCRYPT(), if one was given: Argument Description No argument The first key from the DES key file is used. key_num The given key number (0-9) from the DES key file is used. key_str The given key string is used to encrypt str. The key file can be specified with the --des-key-file server option. The return string is a binary string where the first character is CHAR(128 | key_num). The 128 is added to make it easier to recognize an encrypted key. If you use a string key, key_num is 127. The string length for the result is new_len = orig_len + (8-(orig_len % 8))+1. key_num des_key_str  
316 LENGTH 23 LENGTH(str) Returns the length of the string str, measured in bytes. A multi-byte character counts as multiple bytes. This means that for a string containing five two-byte characters, LENGTH() returns 10, whereas CHAR_LENGTH() returns 5. mysql> SELECT LENGTH('text'); -> 4  
317 DISTANCE 11 Distance(g1,g2) Returns as a double-precision number the shortest distance between any two points in the two geometries.    
318 STR_TO_DATE 14 STR_TO_DATE(str,format) This is the reverse function of the DATE_FORMAT() function. It takes a string str and a format string format. STR_TO_DATE() returns a DATETIME value if the format string contains both date and time parts, or a DATE or TIME value if the string contains only date or time parts. The date, time, or datetime values contained in str should be given in the format indicated by format. For the specifiers that can be used in format, see the table in the DATE_FORMAT() function description. All other characters are just taken verbatim, thus not being interpreted. If str contains an illegal date, time, or datetime value, STR_TO_DATE() returns NULL. Starting from MySQL 5.0.3, an illegal value also produces a warning. @c next example commented out until format string becomes optional @c mysql> SELECT STR_TO_DATE('2003-10-03'); @c -> 2003-10-03 00:00:00 mysql> SELECT STR_TO_DATE('03.10.2003 09.20', -> '%d.%m.%Y %H.%i'); -> '2003-10-03 09:20:00' mysql> SELECT STR_TO_DATE('10arp', '%carp'); -> '0000-10-00 00:00:00' mysql> SELECT STR_TO_DATE('2003-15-10 00:00:00', -> '%Y-%m-%d %H:%i:%s'); -> NULL  
319 Y 16 Y(p) Returns the Y-coordinate value for the point p as a double-precision number. mysql> SELECT Y(GeomFromText('Point(56.7 53.34)')); +--------------------------------------+ | Y(GeomFromText('Point(56.7 53.34)')) | +--------------------------------------+ | 53.34 | +--------------------------------------+  
320 NUMINTERIORRINGS 0 NumInteriorRings(poly) Returns the number of interior rings in the Polygon value poly. mysql> SET @poly = -> 'Polygon((0 0,0 3,3 3,3 0,0 0),(1 1,1 2,2 2,2 1,1 1))'; mysql> SELECT NumInteriorRings(GeomFromText(@poly)); +---------------------------------------+ | NumInteriorRings(GeomFromText(@poly)) | +---------------------------------------+ | 1 | +---------------------------------------+  
321 INTERIORRINGN 0 InteriorRingN(poly,n) Returns the n-th interior ring for the Polygon value poly as a LineString. Ring numbers begin at 1. mysql> SET @poly = -> 'Polygon((0 0,0 3,3 3,3 0,0 0),(1 1,1 2,2 2,2 1,1 1))'; mysql> SELECT AsText(InteriorRingN(GeomFromText(@poly),1)); +----------------------------------------------+ | AsText(InteriorRingN(GeomFromText(@poly),1)) | +----------------------------------------------+ | LINESTRING(1 1,1 2,2 2,2 1,1 1) | +----------------------------------------------+  
322 UTC_TIME 14 UTC_TIME UTC_TIME() Returns the current UTC time as a value in 'HH:MM:SS' or HHMMSS format, depending on whether the function is used in a string or numeric context. mysql> SELECT UTC_TIME(), UTC_TIME() + 0; -> '18:07:53', 180753  
323 STDDEV 12 STD(expr) STDDEV(expr) Returns the population standard deviation of expr. This is an extension to standard SQL. The STDDEV() form of this function is provided for Oracle compatibility. As of MySQL 5.0.3, the standard SQL function STDDEV_POP() can be used instead.    
324 PERIOD_ADD 14 PERIOD_ADD(P,N) Adds N months to period P (in the format YYMM or YYYYMM). Returns a value in the format YYYYMM. Note that the period argument P is /not/ a date value. mysql> SELECT PERIOD_ADD(9801,2); -> 199803  
325 | 27 | Bitwise OR: mysql> SELECT 29 | 15; -> 31  
326 GEOMFROMTEXT 3 GeomFromText(wkt[,srid]) GeometryFromText(wkt[,srid]) Constructs a geometry value of any type using its WKT representation and SRID.    
327 RIGHT 23 RIGHT(str,len) Returns the rightmost len characters from the string str. mysql> SELECT RIGHT('foobarbar', 4); -> 'rbar'  
328 DATEDIFF 14 DATEDIFF(expr,expr2) DATEDIFF() returns the number of days between the start date expr and the end date expr2. expr and expr2 are date or date-and-time expressions. Only the date parts of the values are used in the calculation. mysql> SELECT DATEDIFF('1997-12-31 23:59:59','1997-12-30'); -> 1 mysql> SELECT DATEDIFF('1997-11-30 23:59:59','1997-12-31'); -> -31  
329 BIN 23 BIN(N) Returns a string representation of the binary value of N, where N is a longlong (BIGINT) number. This is equivalent to CONV(N,10,2). Returns NULL if N is NULL. mysql> SELECT BIN(12); -> '1100'  
330 MULTILINESTRING 2 MultiLineString(ls1,ls2,...) Constructs a WKB MultiLineString value using WKB LineString arguments. If any argument is not a WKB LineString, the return value is NULL.    
331 LOAD DATA 6 The LOAD DATA INFILE statement reads rows from a text file into a table at a very high speed. For more information about the efficiency of INSERT versus LOAD DATA INFILE and speeding up LOAD DATA INFILE, [Insert speed]. As of MySQL 4.1, the character set indicated by the character_set_database system variable is used to interpret the information in the file. SET NAMES and the setting of character_set_client do not affect input interpretation. You can also load data files by using the mysqlimport utility; it operates by sending a LOAD DATA INFILE statement to the server. The --local option causes mysqlimport to read data files from the client host. You can specify the --compress option to get better performance over slow networks if the client and server support the compressed protocol. See also : [mysqlimport, , mysqlimport]. If you specify the LOW_PRIORITY keyword, execution of the LOAD DATA statement is delayed until no other clients are reading from the table. If you specify the CONCURRENT keyword with a MyISAM table that satisfies the condition for concurrent inserts (that is, it contains no free blocks in the middle), then other threads can retrieve data from the table while LOAD DATA is executing. Using this option affects the performance of LOAD DATA a bit, even if no other thread is using the table at the same time. If the LOCAL keyword is specified, it is interpreted with respect to the client end of the connection: --- If LOCAL is specified, the file is read by the client program on the client host and sent to the server. The file can be given as a full pathname to specify its exact location. If given as a relative pathname, the name is interpreted relative to the directory in which the client program was started. --- If LOCAL is not specified, the file must be located on the server host and is read directly by the server. LOCAL is available in MySQL 3.22.6 or later. When locating files on the server host, the server uses the following rules: --- If an absolute pathname is given, the server uses the pathname as is. --- If a relative pathname with one or more leading components is given, the server searches for the file relative to the server's data directory. --- If a filename with no leading components is given, the server looks for the file in the database directory of the default database. Note that these rules mean that a file named as *./myfile.txt is read from the server's data directory, whereas the same file named as *myfile.txt is read from the database directory of the default database. For example, the following LOAD DATA statement reads the file *data.txt from the database directory for db1 because db1 is the current database, even though the statement explicitly loads the file into a table in the db2 database: mysql> USE db1; mysql> LOAD DATA INFILE 'data.txt' INTO TABLE db2.my_table; Note that Windows pathnames are specified using forward slashes rather than backslashes. If you do use backslashes, you must double them. For security reasons, when reading text files located on the server, the files must either reside in the database directory or be readable by all. Also, to use LOAD DATA INFILE on server files, you must have the FILE privilege. LOAD DATA [LOW_PRIORITY | CONCURRENT] [LOCAL] INFILE 'file_name.txt' [REPLACE | IGNORE] INTO TABLE tbl_name [FIELDS [TERMINATED BY '\t'] [[OPTIONALLY] ENCLOSED BY ''] [ESCAPED BY '\\' ] ] [LINES [STARTING BY ''] [TERMINATED BY '\n'] ] [IGNORE number LINES] [(col_name,...)]  
332 BLOB TYPE 1 BLOB[(M)] A BLOB column with a maximum length of 65,535 (2^16 - 1) bytes. Beginning with MySQL 4.1, an optional length M can be given. MySQL will create the column as the smallest BLOB type largest enough to hold values M bytes long.    
333 LOCALTIME 14 LOCALTIME LOCALTIME() LOCALTIME and LOCALTIME() are synonyms for NOW().    
334 MPOINTFROMTEXT 3 MPointFromText(wkt[,srid]) MultiPointFromText(wkt[,srid]) Constructs a MULTIPOINT value using its WKT representation and SRID.    
335 BLOB 1 A BLOB is a binary large object that can hold a variable amount of data. The four BLOB types, TINYBLOB, BLOB, MEDIUMBLOB, and LONGBLOB, differ only in the maximum length of the values they can hold.    
336 PASSWORD 17   mysql> SELECT PASSWORD('badpwd'); -> '7f84554057dd964b'  
337 CHAR 1 [NATIONAL] CHAR(M) [BINARY | ASCII | UNICODE] A fixed-length string that is always right-padded with spaces to the specified length when stored. M represents the column length. The range of M is 0 to 255 characters (1 to 255 prior to MySQL 3.23). Note: Trailing spaces are removed when CHAR values are retrieved. From MySQL 4.1.0 to 5.0.2, a CHAR column with a length specification greater than 255 is converted to the smallest TEXT type that can hold values of the given length. For example, CHAR(500) is converted to TEXT, and CHAR(200000) is converted to MEDIUMTEXT. This is a compatibility feature. However, this conversion causes the column to become a variable-length column, and also affects trailing-space removal. CHAR is shorthand for CHARACTER. NATIONAL CHAR (or its equivalent short form, NCHAR) is the standard SQL way to define that a CHAR column should use the default character set. This is the default in MySQL. As of MySQL 4.1.2, the BINARY attribute is shorthand for specifying the binary collation of the column character set. Sorting and comparison is based on numeric character values. Before 4.1.2, BINARY attribute causes the column to be treated as a binary string. Sorting and comparison is based on numeric byte values. From MySQL 4.1.0 on, column type CHAR BYTE is an alias for CHAR BINARY. This is a compatibility feature. From MySQL 4.1.0 on, the ASCII attribute can be specified for CHAR. It assigns the latin1 character set. From MySQL 4.1.1 on, the UNICODE attribute can be specified for CHAR. It assigns the ucs2 character set. MySQL allows you to create a column of type CHAR(0). This is mainly useful when you have to be compliant with some old applications that depend on the existence of a column but that do not actually use the value. This is also quite nice when you need a column that can take only two values: A CHAR(0) column that is not defined as NOT NULL occupies only one bit and can take only the values NULL and '' (the empty string). CHAR This is a synonym for CHAR(1).    
338 UTC_DATE 14 UTC_DATE UTC_DATE() Returns the current UTC date as a value in 'YYYY-MM-DD' or YYYYMMDD format, depending on whether the function is used in a string or numeric context. mysql> SELECT UTC_DATE(), UTC_DATE() + 0; -> '2003-08-14', 20030814  
339 DIMENSION 19 Dimension(g) Returns the inherent dimension of the geometry value g. The result can be -1, 0, 1, or 2. (The meaning of these values is given in [GIS class geometry].) mysql> SELECT Dimension(GeomFromText('LineString(1 1,2 2)')); +------------------------------------------------+ | Dimension(GeomFromText('LineString(1 1,2 2)')) | +------------------------------------------------+ | 1 | +------------------------------------------------+  
340 COUNT DISTINCT 12 COUNT(DISTINCT expr,[expr...]) Returns a count of the number of different non-NULL values. mysql> SELECT COUNT(DISTINCT results) FROM student;  
341 BIT 1 BIT[(M)] A bit-field type. M indicates the number of bits per value, from 1 to 64. The default is 1 if M is omitted. This data type was added in MySQL 5.0.3 for MyISAM, and extended in 5.0.5 to MEMORY, InnoDB, and BDB. Before 5.0.3, BIT is a synonym for TINYINT(1).    
342 EQUALS 11 Equals(g1,g2) Returns 1 or 0 to indicate whether or not g1 is spatially equal to g2.    
343 SHOW CREATE VIEW 24 This statement shows a CREATE VIEW statement that creates the given view. SHOW CREATE VIEW view_name  
344 INTERVAL 26 INTERVAL(N,N1,N2,N3,...) Returns 0 if N < N1, 1 if N < N2 and so on or -1 if N is NULL. All arguments are treated as integers. It is required that N1 < N2 < N3 < ... < Nn for this function to work correctly. This is because a binary search is used (very fast). mysql> SELECT INTERVAL(23, 1, 15, 17, 30, 44, 200); -> 3 mysql> SELECT INTERVAL(10, 1, 10, 100, 1000); -> 2 mysql> SELECT INTERVAL(22, 23, 30, 44, 200); -> 0  
345 FROM_DAYS 14 FROM_DAYS(N) Given a daynumber N, returns a DATE value. mysql> SELECT FROM_DAYS(729669); -> '1997-10-07'  
346 BIT_COUNT 27 BIT_COUNT(N) Returns the number of bits that are set in the argument N. mysql> SELECT BIT_COUNT(29); -> 4  
347 UTC_TIMESTAMP 14 UTC_TIMESTAMP UTC_TIMESTAMP() Returns the current UTC date and time as a value in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS format, depending on whether the function is used in a string or numeric context. mysql> SELECT UTC_TIMESTAMP(), UTC_TIMESTAMP() + 0; -> '2003-08-14 18:08:04', 20030814180804  
348 + 4 + Addition: mysql> SELECT 3+5; -> 8  
349 INET_NTOA 21 INET_NTOA(expr) Given a numeric network address (4 or 8 byte), returns the dotted-quad representation of the address as a string. mysql> SELECT INET_NTOA(3520061480); -> '209.207.224.40'  
350 ACOS 4 ACOS(X) Returns the arc cosine of X, that is, the value whose cosine is X. Returns NULL if X is not in the range -1 to 1. mysql> SELECT ACOS(1); -> 0.000000 mysql> SELECT ACOS(1.0001); -> NULL mysql> SELECT ACOS(0); -> 1.570796  
351 ISOLATION 10 SET [GLOBAL | SESSION] TRANSACTION ISOLATION LEVEL { READ UNCOMMITTED | READ COMMITTED | REPEATABLE READ | SERIALIZABLE } This statement sets the transaction isolation level for the next transaction, globally, or for the current session. The default behavior of SET TRANSACTION is to set the isolation level for the next (not yet started) transaction. If you use the GLOBAL keyword, the statement sets the default transaction level globally for all new connections created from that point on. Existing connections are unaffected. You need the SUPER privilege to do this. Using the SESSION keyword sets the default transaction level for all future transactions performed on the current connection. For descriptions of each InnoDB transaction isolation level, see [InnoDB transaction isolation, InnoDB transaction isolation]. InnoDB supports each of these levels from MySQL 4.0.5 on. The default level is REPEATABLE READ. You can set the initial default global isolation level for mysqld with the --transaction-isolation option. See also : [Server options].    
352 CEILING 4 CEILING(X) CEIL(X) Returns the smallest integer value not less than X. mysql> SELECT CEILING(1.23); -> 2 mysql> SELECT CEIL(-1.23); -> -1  
353 SIN 4 SIN(X) Returns the sine of X, where X is given in radians. mysql> SELECT SIN(PI()); -> 0.000000  
354 DAYOFWEEK 14 DAYOFWEEK(date) Returns the weekday index for date (1 = Sunday, 2 = Monday, ..., 7 = Saturday). These index values correspond to the ODBC standard. mysql> SELECT DAYOFWEEK('1998-02-03'); -> 3  
355 LINEFROMWKB 13 LineFromWKB(wkb[,srid]) LineStringFromWKB(wkb[,srid]) Constructs a LINESTRING value using its WKB representation and SRID.    
356 GEOMETRYTYPE 19 GeometryType(g) Returns as a string the name of the geometry type of which the geometry instance g is a member. The name corresponds to one of the instantiable Geometry subclasses. mysql> SELECT GeometryType(GeomFromText('POINT(1 1)')); +------------------------------------------+ | GeometryType(GeomFromText('POINT(1 1)')) | +------------------------------------------+ | POINT | +------------------------------------------+  
357 GRANT TYPES 7 For the GRANT and REVOKE statements, priv_type can be specified as any of the following: Privilege Meaning ALL [PRIVILEGES] Sets all simple privileges except GRANT OPTION ALTER Allows use of ALTER TABLE ALTER ROUTINE Alter or drop stored routines CREATE Allows use of CREATE TABLE CREATE ROUTINE Create stored routines CREATE TEMPORARY TABLES Allows use of CREATE TEMPORARY TABLE CREATE USER Allows use of CREATE USER, DROP USER, RENAME USER, and REVOKE ALL PRIVILEGES. CREATE VIEW Allows use of CREATE VIEW DELETE Allows use of DELETE DROP Allows use of DROP TABLE EXECUTE Allows the user to run stored routines FILE Allows use of SELECT ... INTO OUTFILE and LOAD DATA INFILE INDEX Allows use of CREATE INDEX and DROP INDEX INSERT Allows use of INSERT LOCK TABLES Allows use of LOCK TABLES on tables for which you have the SELECT privilege PROCESS Allows use of SHOW FULL PROCESSLIST REFERENCES Not implemented RELOAD Allows use of FLUSH REPLICATION CLIENT Allows the user to ask where slave or master servers are REPLICATION SLAVE Needed for replication slaves (to read binary log events from the master) SELECT Allows use of SELECT SHOW DATABASES SHOW DATABASES shows all databases SHOW VIEW Allows use of SHOW CREATE VIEW SHUTDOWN Allows use of mysqladmin shutdown SUPER Allows use of CHANGE MASTER, KILL, PURGE MASTER LOGS, and SET GLOBAL statements, the mysqladmin debug command; allows you to connect (once) even if max_connections is reached UPDATE Allows use of UPDATE USAGE Synonym for ``no privileges'' GRANT OPTION Allows privileges to be granted    
358 CREATE VIEW 24 This statement creates a new view, or replaces an existing one if the OR REPLACE clause is given. The select_statement is a SELECT statement that provides the definition of the view. The statement can select from base tables or other views. This statement requires the CREATE VIEW privilege for the view, and some privilege for each column selected by the SELECT statement. For columns used elsewhere in the SELECT statement you must have the SELECT privilege. If the OR REPLACE clause is present, you must also have the DELETE privilege for the view. A view belongs to a database. By default, a new view is created in the current database. To create the view explicitly in a given database, specify the name as db_name.view_name when you create it. mysql> CREATE VIEW test.v AS SELECT * FROM t; Tables and views share the same namespace within a database, so a database cannot contain a table and a view that have the same name. Views must have unique column names with no duplicates, just like base tables. By default, the names of the columns retrieved by the SELECT statement are used for the view column names. To define explicit names for the view columns, the optional column_list clause can be given as a list of comma-separated identifiers. The number of names in column_list must be the same as the number of columns retrieved by the SELECT statement. Columns retrieved by the SELECT statement can be simple references to table columns. They can also be expressions that use functions, constant values, operators, and so forth. Unqualified table or view names in the SELECT statement are interpreted with respect to the default database. A view can refer to tables or views in other databases by qualifying the table or view name with the proper database name. A view can be created from many kinds of SELECT statements. It can refer to base tables or other views. It can use joins, UNION, and subqueries. The SELECT need not even refer to any tables. The following example defines a view that selects two columns from another table, as well as an expression calculated from those columns: mysql> CREATE TABLE t (qty INT, price INT); mysql> INSERT INTO t VALUES(3, 50); mysql> CREATE VIEW v AS SELECT qty, price, qty*price AS value FROM t; mysql> SELECT * FROM v; +------+-------+-------+ | qty | price | value | +------+-------+-------+ | 3 | 50 | 150 | +------+-------+-------+ A view definition is subject to the following restrictions: --- The SELECT statement cannot contain a subquery in the FROM clause. --- The SELECT statement cannot refer to system or user variables. --- The SELECT statement cannot refer to prepared statement parameters. --- Within a stored routine, the definition cannot refer to routine parameters or local variables. --- Any table or view referred to in the definition must exist. However, after a view has been created, it is possible to drop a table or view that the definition refers to. To check a view definition for problems of this kind, use the CHECK TABLE statement. --- The definition cannot refer to a TEMPORARY table, and you cannot create a TEMPORARY view. --- The tables named in the view definition must already exist. --- You cannot associate a trigger with a view. ORDER BY is allowed in a view definition, but it is ignored if you select from a view using a statement that has its own ORDER BY. For other options or clauses in the definition, they are added to the options or clauses of the statement that references the view, but the effect is undefined. For example, if a view definition includes a LIMIT clause, and you select from the view using a statement that has its own LIMIT clause, it is undefined which limit applies. This same principle applies to options such as ALL, DISTINCT, or SQL_SMALL_RESULT that follow the SELECT keyword, and to clauses such as INTO, FOR UPDATE, LOCK IN SHARE MODE, and PROCEDURE. If you create a view and then change the query processing environment by changing system variables, that may affect the results you get from the view: mysql> CREATE VIEW v AS SELECT CHARSET(CHAR(65)), COLLATION(CHAR(65)); Query OK, 0 rows affected (0.00 sec) mysql> SET NAMES 'latin1'; Query OK, 0 rows affected (0.00 sec) mysql> SELECT * FROM v; +-------------------+---------------------+ | CHARSET(CHAR(65)) | COLLATION(CHAR(65)) | +-------------------+---------------------+ | latin1 | latin1_swedish_ci | +-------------------+---------------------+ 1 row in set (0.00 sec) mysql> SET NAMES 'utf8'; Query OK, 0 rows affected (0.00 sec) mysql> SELECT * FROM v; +-------------------+---------------------+ | CHARSET(CHAR(65)) | COLLATION(CHAR(65)) | +-------------------+---------------------+ | utf8 | utf8_general_ci | +-------------------+---------------------+ 1 row in set (0.00 sec) The optional ALGORITHM clause is a MySQL extension to standard SQL. ALGORITHM takes three values: MERGE, TEMPTABLE, or UNDEFINED. The default algorithm is UNDEFINED if no ALGORITHM clause is present. The algorithm affects how MySQL processes the view. For MERGE, the text of a statement that refers to the view and the view definition are merged such that parts of the view definition replace corresponding parts of the statement. For TEMPTABLE, the results from the view are retrieved into a temporary table, which then is used to execute the statement. For UNDEFINED, MySQL chooses which algorithm to use. It prefers MERGE over TEMPTABLE if possible, because MERGE is usually more efficient and because a view cannot be updatable if a temporary table is used. A reason to choose TEMPTABLE explicitly is that locks can be released on underlying tables after the temporary table has been created and before it is used to finish processing the statement. This might result in quicker lock release than the MERGE algorithm so that other clients that use the view are not blocked as long. A view algorithm can be UNDEFINED three ways: --- No ALGORITHM clause is present in the CREATE VIEW statement. --- The CREATE VIEW statement has an explicit ALGORITHM = UNDEFINED clause. --- ALGORITHM = MERGE is specified for a view that can be processed only with a temporary table. In this case, MySQL generates a warning and sets the algorithm to UNDEFINED. As mentioned earlier, MERGE is handled by merging corresponding parts of a view definition into the statement that refers to the view. The following examples briefly illustrate how the MERGE algorithm works. The examples assume that there is a view v_merge that has this definition: CREATE ALGORITHM = MERGE VIEW v_merge (vc1, vc2) AS SELECT c1, c2 FROM t WHERE c3 > 100; Example 1: Suppose that we issue this statement: SELECT * FROM v_merge; MySQL handles the statement as follows: --- v_merge becomes t --- * becomes vc1, vc2, which corresponds to c1, c2 --- The view WHERE clause is added The resulting statement to be executed becomes: SELECT c1, c2 FROM t WHERE c3 > 100; Example 2: Suppose that we issue this statement: SELECT * FROM v_merge WHERE vc1 < 100; This statement is handled similarly to the previous one, except that vc1 < 100 becomes c1 < 100 and the view WHERE clause is added to the statement WHERE clause using an AND connective (and parentheses are added to make sure the parts of the clause are executed with correct precedence). The resulting statement to be executed becomes: SELECT c1, c2 FROM t WHERE (c3 > 100) AND (c1 < 100); Effectively, the statement to be executed has a WHERE clause of this form: WHERE (select WHERE) AND (view WHERE) The MERGE algorithm requires a one-to relationship between the rows in the view and the rows in the underlying table. If this relationship does not hold, a temporary table must be used instead. Lack of a one-to-one relationship occurs if the view contains any of a number of constructs: --- Aggregate functions (SUM(), MIN(), MAX(), COUNT(), and so forth) --- DISTINCT --- GROUP BY --- HAVING --- UNION or UNION ALL --- Refers only to literal values (in this case, there is no underlying table) Some views are updatable. That is, you can use them in statements such as UPDATE, DELETE, or INSERT to update the contents of the underlying table. For a view to be updatable, there must be a one-to relationship between the rows in the view and the rows in the underlying table. There are also certain other constructs that make a view non-updatable. To be more specific, a view is not updatable if it contains any of the following: --- Aggregate functions (SUM(), MIN(), MAX(), COUNT(), and so forth) --- DISTINCT --- GROUP BY --- HAVING --- UNION or UNION ALL --- Subquery in the select list --- Join --- Non-updatable view in the FROM clause --- A subquery in the WHERE clause that refers to a table in the FROM clause --- Refers only to literal values (in this case, there is no underlying table to update) --- ALGORITHM = TEMPTABLE (use of a temporary table always makes a view non-updatable) With respect to insertability (being updatable with INSERT statements), an updatable view is insertable if it also satisfies these additional requirements for the view columns: --- There must be no duplicate view column names. --- The view must contain all columns in the base table that do not have a default value. --- The view columns must be simple column references and not derived columns. A derived column is one that is not a simple column reference but is derived from an expression. These are examples of derived columns: 3.14159 col1 + 3 UPPER(col2) col3 / col4 (subquery) A view that has a mix of simple column references and derived columns is not insertable, but it can be updatable if you update only those columns that are not derived. Consider this view: CREATE VIEW v AS SELECT col1, 1 AS col2 FROM t; This view is not insertable because col2 is derived from an expression. But it is updatable if the update does not try to update col2. This update is allowable: UPDATE v SET col1 = 0; This update is not allowable because it attempts to update a derived column: UPDATE v SET col2 = 0; It is sometimes possible for a multiple-table view to be updatable, assuming that it can be processed with the MERGE algorithm. For this to work, the view must use an inner join (not an outer join or a UNION). Also, only a single table in the view definition can be updated, so the SET clause must name only columns from one of the tables in the view. Views that use UNION ALL are disallowed even though they might be theoretically updatable, because the implementation uses temporary tables to process them. For a multiple-table updatable view, INSERT can work if it inserts into a single table. DELETE is not supported. The WITH CHECK OPTION clause can be given for an updatable view to prevent inserts or updates to rows except those for which the WHERE clause in the select_statement is true.    
359 TRIM 23 TRIM([{BOTH | LEADING | TRAILING} [remstr] FROM] str) TRIM(remstr FROM] str) Returns the string str with all remstr prefixes and/or suffixes removed. If none of the specifiers BOTH, LEADING, or TRAILING is given, BOTH is assumed. If remstr is optional and not specified, spaces are removed. mysql> SELECT TRIM(' bar '); -> 'bar' mysql> SELECT TRIM(LEADING 'x' FROM 'xxxbarxxx'); -> 'barxxx' mysql> SELECT TRIM(BOTH 'x' FROM 'xxxbarxxx'); -> 'bar' mysql> SELECT TRIM(TRAILING 'xyz' FROM 'barxxyz'); -> 'barx'  
360 IS 26 IS boolean_value IS NOT boolean_value Tests whether a value against a boolean value, where boolean_value can be TRUE, FALSE, or UNKNOWN. mysql> SELECT 1 IS TRUE, 0 IS FALSE, NULL IS UNKNOWN; -> 1, 1, 1 mysql> SELECT 1 IS NOT UNKNOWN, 0 IS NOT UNKNOWN, NULL IS NOT UNKNOWN; -> 1, 1, 0  
361 GET_FORMAT 14 GET_FORMAT(DATE|TIME|DATETIME, 'EUR'|'USA'|'JIS'|'ISO'|'INTERNAL') Returns a format string. This function is useful in combination with the DATE_FORMAT() and the STR_TO_DATE() functions. The three possible values for the first argument and the five possible values for the second argument result in 15 possible format strings (for the specifiers used, see the table in the DATE_FORMAT() function description). Function Call Result GET_FORMAT(DATE,'USA') '%m.%d.%Y' GET_FORMAT(DATE,'JIS') '%Y-%m-%d' GET_FORMAT(DATE,'ISO') '%Y-%m-%d' GET_FORMAT(DATE,'EUR') '%d.%m.%Y' GET_FORMAT(DATE,'INTERNAL') '%Y%m%d' GET_FORMAT(DATETIME,'USA') '%Y-%m-%d-%H.%i.%s' GET_FORMAT(DATETIME,'JIS') '%Y-%m-%d %H:%i:%s' GET_FORMAT(DATETIME,'ISO') '%Y-%m-%d %H:%i:%s' GET_FORMAT(DATETIME,'EUR') '%Y-%m-%d-%H.%i.%s' GET_FORMAT(DATETIME,'INTERNAL') '%Y%m%d%H%i%s' GET_FORMAT(TIME,'USA') '%h:%i:%s %p' GET_FORMAT(TIME,'JIS') '%H:%i:%s' GET_FORMAT(TIME,'ISO') '%H:%i:%s' GET_FORMAT(TIME,'EUR') '%H.%i.%S' GET_FORMAT(TIME,'INTERNAL') '%H%i%s' ISO format is ISO 9075, not ISO 8601. As of MySQL 4.1.4, TIMESTAMP can also be used; GET_FORMAT() returns the same values as for DATETIME. mysql> SELECT DATE_FORMAT('2003-10-03',GET_FORMAT(DATE,'EUR')); -> '03.10.2003' mysql> SELECT STR_TO_DATE('10.31.2003',GET_FORMAT(DATE,'USA')); -> 2003-10-31 @c Following is commented out because not yet implemented @c mysql> SET DATE_FORMAT=GET_FORMAT(DATE, 'USA'); SELECT '2003-10-31'; @c -> 10-31-2003  
362 TINYBLOB 1 TINYBLOB A BLOB column with a maximum length of 255 (2^8 - 1) bytes.    
363 SAVEPOINT 10 SAVEPOINT identifier ROLLBACK TO SAVEPOINT identifier Starting from MySQL 4.0.14 and 4.1.1, InnoDB supports the SQL statements SAVEPOINT and ROLLBACK TO SAVEPOINT.    
364 IF 9 IF(expr1,expr2,expr3) If expr1 is TRUE (expr1 <> 0 and expr1 <> NULL) then IF() returns expr2, else it returns expr3. IF() returns a numeric or string value, depending on the context in which it is used. mysql> SELECT IF(1>2,2,3); -> 3 mysql> SELECT IF(1<2,'yes','no'); -> 'yes' mysql> SELECT IF(STRCMP('test','test1'),'no','yes'); -> 'no'  
365 PURGE 6   PURGE MASTER LOGS TO 'mysql-bin.010'; PURGE MASTER LOGS BEFORE '2003-04-02 22:46:26';  
366 USER 25 USER() Returns the current MySQL username and hostname. mysql> SELECT USER(); -> 'davida@localhost'  
367 MPOINTFROMWKB 13 MPointFromWKB(wkb[,srid]) MultiPointFromWKB(wkb[,srid]) Constructs a MULTIPOINT value using its WKB representation and SRID.    
368 ALTER TABLE 28 ALTER TABLE allows you to change the structure of an existing table. For example, you can add or delete columns, create or destroy indexes, change the type of existing columns, or rename columns or the table itself. You can also change the comment for the table and type of the table. ALTER [IGNORE] TABLE tbl_name alter_specification [, alter_specification] ... alter_specification: ADD [COLUMN] column_definition [FIRST | AFTER col_name ] | ADD [COLUMN] (column_definition,...) | ADD INDEX [index_name] [index_type] (index_col_name,...) | ADD [CONSTRAINT [symbol]] PRIMARY KEY [index_type] (index_col_name,...) | ADD [CONSTRAINT [symbol]] UNIQUE [index_name] [index_type] (index_col_name,...) | ADD [FULLTEXT|SPATIAL] [index_name] (index_col_name,...) | ADD [CONSTRAINT [symbol]] FOREIGN KEY [index_name] (index_col_name,...) [reference_definition] | ALTER [COLUMN] col_name {SET DEFAULT literal | DROP DEFAULT} | CHANGE [COLUMN] old_col_name column_definition [FIRST|AFTER col_name] | MODIFY [COLUMN] column_definition [FIRST | AFTER col_name] | DROP [COLUMN] col_name | DROP PRIMARY KEY | DROP INDEX index_name | DROP FOREIGN KEY fk_symbol | DISABLE KEYS | ENABLE KEYS | RENAME [TO] new_tbl_name | ORDER BY col_name | CONVERT TO CHARACTER SET charset_name [COLLATE collation_name] | [DEFAULT] CHARACTER SET charset_name [COLLATE collation_name] | DISCARD TABLESPACE | IMPORT TABLESPACE | table_options  
369 CHAR BYTE 22 CHAR BYTE is an alias for CHAR BINARY.    
370 MERGE 7 @menu * MERGE table problems:: MERGE Table Problems @end menu The MERGE storage engine was introduced in MySQL 3.23.25. It is also known as the MRG_MyISAM engine. A MERGE table is a collection of identical MyISAM tables that can be used as one. ``Identical'' means that all tables have identical column and index information. You can't merge tables in which the columns are listed in a different order, don't have exactly the same columns, or have the indexes in different order. However, any or all of the tables can be compressed with myisampack. See also : [myisampack, , myisampack]. Differences in table options such as AVG_ROW_LENGTH, MAX_ROWS, or PACK_KEYS do not matter. mysql> CREATE TABLE t1 ( -> a INT NOT NULL AUTO_INCREMENT PRIMARY KEY, -> message CHAR(20)); mysql> CREATE TABLE t2 ( -> a INT NOT NULL AUTO_INCREMENT PRIMARY KEY, -> message CHAR(20)); mysql> INSERT INTO t1 (message) VALUES ('Testing'),('table'),('t1'); mysql> INSERT INTO t2 (message) VALUES ('Testing'),('table'),('t2'); mysql> CREATE TABLE total ( -> a INT NOT NULL AUTO_INCREMENT, -> message CHAR(20), INDEX(a)) -> TYPE=MERGE UNION=(t1,t2) INSERT_METHOD=LAST;  
371 CREATE TABLE 28 CREATE TABLE creates a table with the given name. You must have the CREATE privilege for the table. Rules for allowable table names are given in [Legal names]. By default, the table is created in the current database. An error occurs if the table exists, if there is no current database, or if the database does not exist. CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name [(create_definition,...)] [table_options] [select_statement]  
372 > 26 > Greater than: mysql> SELECT 2 > 2; -> 0  
373 MICROSECOND 14 MICROSECOND(expr) Returns the microseconds from the time or datetime expression expr as a number in the range from 0 to 999999. mysql> SELECT MICROSECOND('12:00:00.123456'); -> 123456 mysql> SELECT MICROSECOND('1997-12-31 23:59:59.000010'); -> 10  
374 ANALYZE 7 This statement analyzes and stores the key distribution for a table. During the analysis, the table is locked with a read lock. This works on MyISAM and BDB tables and (as of MySQL 4.0.13) InnoDB tables. For MyISAM tables, this statement is equivalent to using myisamchk -a. MySQL uses the stored key distribution to decide the order in which tables should be joined when you perform a join on something other than a constant. ANALYZE [LOCAL | NO_WRITE_TO_BINLOG] TABLE tbl_name [, tbl_name] ...  
375 CONSTRAINT 7 The syntax of a foreign key constraint definition in InnoDB looks like this: [CONSTRAINT symbol] FOREIGN KEY [id] (index_col_name, ...) REFERENCES tbl_name (index_col_name, ...) [ON DELETE {RESTRICT | CASCADE | SET NULL | NO ACTION}] [ON UPDATE {RESTRICT | CASCADE | SET NULL | NO ACTION}] CREATE TABLE product (category INT NOT NULL, id INT NOT NULL, price DECIMAL, PRIMARY KEY(category, id)) TYPE=INNODB; CREATE TABLE customer (id INT NOT NULL, PRIMARY KEY (id)) TYPE=INNODB; CREATE TABLE product_order (no INT NOT NULL AUTO_INCREMENT, product_category INT NOT NULL, product_id INT NOT NULL, customer_id INT NOT NULL, PRIMARY KEY(no), INDEX (product_category, product_id), FOREIGN KEY (product_category, product_id) REFERENCES product(category, id) ON UPDATE CASCADE ON DELETE RESTRICT, INDEX (customer_id), FOREIGN KEY (customer_id) REFERENCES customer(id)) TYPE=INNODB;  
376 FIELD 23 FIELD(str,str1,str2,str3,...) Returns the index of str in the str1, str2, str3, ... list. Returns 0 if str is not found. If all arguments to FIELD() are strings, all arguments are compared as strings. If all arguments are numbers, they are compared as numbers. Otherwise, the arguments are compared as double. If str is NULL, the return value is 0 because NULL fails equality comparison with any value. FIELD() is the complement of ELT(). mysql> SELECT FIELD('ej', 'Hej', 'ej', 'Heja', 'hej', 'foo'); -> 2 mysql> SELECT FIELD('fo', 'Hej', 'ej', 'Heja', 'hej', 'foo'); -> 0  
377 MAKETIME 14 MAKETIME(hour,minute,second) Returns a time value calculated from the hour, minute, and second arguments. mysql> SELECT MAKETIME(12,15,30); -> '12:15:30'  
378 CURDATE 14 CURDATE() Returns the current date as a value in 'YYYY-MM-DD' or YYYYMMDD format, depending on whether the function is used in a string or numeric context. mysql> SELECT CURDATE(); -> '1997-12-15' mysql> SELECT CURDATE() + 0; -> 19971215  
379 MIN MAX 12 MIN([DISTINCT] expr) MAX([DISTINCT] expr) Returns the minimum or maximum value of expr. MIN() and MAX() may take a string argument; in such cases they return the minimum or maximum string value. See also : [MySQL indexes]. The DISTINCT keyword can be used as of MySQL 5.0.0 to find the minimum or maximum of the distinct values of expr; this is supported, but produces the same result as omitting DISTINCT. mysql> SELECT student_name, MIN(test_score), MAX(test_score) -> FROM student -> GROUP BY student_name;  
380 SET PASSWORD 7   SET PASSWORD = PASSWORD('some password') SET PASSWORD FOR user = PASSWORD('some password')  
381 ENUM 1 ENUM('value1','value2',...) An enumeration. A string object that can have only one value, chosen from the list of values 'value1', 'value2', ..., NULL or the special '' error value. An ENUM column can have a maximum of 65,535 distinct values. ENUM values are represented internally as integers.    
382 DATABASE 25 DATABASE() Returns the default (current) database name. As of MySQL 4.1, the string has the utf8 character set. mysql> SELECT DATABASE(); -> 'test'  
383 POINTFROMWKB 13 PointFromWKB(wkb[,srid]) Constructs a POINT value using its WKB representation and SRID.    
384 POWER 4 POW(X,Y) POWER(X,Y) Returns the value of X raised to the power of Y. mysql> SELECT POW(2,2); -> 4.000000 mysql> SELECT POW(2,-2); -> 0.250000  
385 ATAN 4 ATAN(X) Returns the arc tangent of X, that is, the value whose tangent is X. mysql> SELECT ATAN(2); -> 1.107149 mysql> SELECT ATAN(-2); -> -1.107149  
386 STRCMP 23 STRCMP(expr1,expr2) STRCMP() returns 0 if the strings are the same, -1 if the first argument is smaller than the second according to the current sort order, and 1 otherwise. mysql> SELECT STRCMP('text', 'text2'); -> -1 mysql> SELECT STRCMP('text2', 'text'); -> 1 mysql> SELECT STRCMP('text', 'text'); -> 0  
387 INSERT DELAYED 6 The DELAYED option for the INSERT statement is a MySQL extension to standard SQL that is very useful if you have clients that can't wait for the INSERT to complete. This is a common problem when you use MySQL for logging and you also periodically run SELECT and UPDATE statements that take a long time to complete. DELAYED was introduced in MySQL 3.22.15. When a client uses INSERT DELAYED, it gets an okay from the server at once, and the row is queued to be inserted when the table is not in use by any other thread. Another major benefit of using INSERT DELAYED is that inserts from many clients are bundled together and written in one block. This is much faster than doing many separate inserts. There are some constraints on the use of DELAYED: --- INSERT DELAYED works only with ISAM, MyISAM, and (beginning with MySQL 4.1) MEMORY tables. For MyISAM tables, if there are no free blocks in the middle of the data file, concurrent SELECT and INSERT statements are supported. Under these circumstances, you very seldom need to use INSERT DELAYED with MyISAM. See also : [MyISAM storage engine, , MyISAM storage engine]. See also : [MEMORY storage engine, , MEMORY storage engine]. --- INSERT DELAYED should be used only for INSERT statements that specify value lists. This is enforced as of MySQL 4.0.18. The server ignores DELAYED for INSERT DELAYED ... SELECT statements. --- The server ignores DELAYED for INSERT DELAYED ... ON DUPLICATE UPDATE statements. --- Because the statement returns immediately before the rows are inserted, you cannot use LAST_INSERT_ID() to get the AUTO_INCREMENT value the statement might generate. --- DELAYED rows are not visible to SELECT statements until they actually have been inserted. --- DELAYED are ignored on slaves, because this could cause the slave to have different data than the master. INSERT DELAYED ...  
388 MEDIUMTEXT 1 MEDIUMTEXT A TEXT column with a maximum length of 16,777,215 (2^24 - 1) characters.    
389 LN 4 LN(X) Returns the natural logarithm of X. mysql> SELECT LN(2); -> 0.693147 mysql> SELECT LN(-2); -> NULL  
390 LOG 4 LOG(X) LOG(B,X) If called with one parameter, this function returns the natural logarithm of X. mysql> SELECT LOG(2); -> 0.693147 mysql> SELECT LOG(-2); -> NULL  
391 SET SQL_LOG_BIN 6 SET SQL_LOG_BIN = {0|1} Disables or enables binary logging for the current connection (SQL_LOG_BIN is a session variable) if the client connects using an account that has the SUPER privilege. The statement is refused with an error if the client does not have that privilege. (Before MySQL 4.1.2, the statement was simply ignored in that case.)    
392 != 26 <> != Not equal: mysql> SELECT '.01' <> '0.01'; -> 1 mysql> SELECT .01 <> '0.01'; -> 0 mysql> SELECT 'zapp' <> 'zappp'; -> 1  
393 AES_DECRYPT 17 AES_ENCRYPT(str,key_str) AES_DECRYPT(crypt_str,key_str) These functions allow encryption and decryption of data using the official AES (Advanced Encryption Standard) algorithm, previously known as "Rijndael." Encoding with a 128-bit key length is used, but you can extend it up to 256 bits by modifying the source. We chose 128 bits because it is much faster and it is usually secure enough. The input arguments may be any length. If either argument is NULL, the result of this function is also NULL. Because AES is a block-level algorithm, padding is used to encode uneven length strings and so the result string length may be calculated as 16*(trunc(string_length/16)+1). If AES_DECRYPT() detects invalid data or incorrect padding, it returns NULL. However, it is possible for AES_DECRYPT() to return a non-NULL value (possibly garbage) if the input data or the key is invalid. You can use the AES functions to store data in an encrypted form by modifying your queries: INSERT INTO t VALUES (1,AES_ENCRYPT('text','password'));  
394 DAYNAME 14 DAYNAME(date) Returns the name of the weekday for date. mysql> SELECT DAYNAME('1998-02-05'); -> 'Thursday'  
395 COERCIBILITY 25 COERCIBILITY(str) Returns the collation coercibility value of the string argument. mysql> SELECT COERCIBILITY('abc' COLLATE latin1_swedish_ci); -> 0 mysql> SELECT COERCIBILITY(USER()); -> 3 mysql> SELECT COERCIBILITY('abc'); -> 4  
396 INT 1 INT[(M)] [UNSIGNED] [ZEROFILL] A normal-size integer. The signed range is -2147483648 to 2147483647. The unsigned range is 0 to 4294967295. INTEGER[(M)] [UNSIGNED] [ZEROFILL] This is a synonym for INT.    
397 RLIKE 23 expr REGEXP pat expr RLIKE pat Performs a pattern match of a string expression expr against a pattern pat. The pattern can be an extended regular expression. The syntax for regular expressions is discussed in [Regexp]. Returns 1 if expr matches pat, otherwise returns 0. If either expr or pat is NULL, the result is NULL. RLIKE is a synonym for REGEXP, provided for mSQL compatibility. The pattern need not be a literal string. For example, it can be specified as a string expression or table column. Note: Because MySQL uses the C escape syntax in strings (for example, '\n' to represent newline), you must double any '\' that you use in your REGEXP strings. As of MySQL 3.23.4, REGEXP is not case sensitive for normal (not binary) strings. mysql> SELECT 'Monty!' REGEXP 'm%y%%'; -> 0 mysql> SELECT 'Monty!' REGEXP '.*'; -> 1 mysql> SELECT 'new*\n*line' REGEXP 'new\\*.\\*line'; -> 1 mysql> SELECT 'a' REGEXP 'A', 'a' REGEXP BINARY 'A'; -> 1 0 mysql> SELECT 'a' REGEXP '^[a-d]'; -> 1  
398 GLENGTH 18 GLength(ls) Returns as a double-precision number the length of the LineString value ls in its associated spatial reference. mysql> SET @ls = 'LineString(1 1,2 2,3 3)'; mysql> SELECT GLength(GeomFromText(@ls)); +----------------------------+ | GLength(GeomFromText(@ls)) | +----------------------------+ | 2.8284271247462 | +----------------------------+  
399 RADIANS 4 RADIANS(X) Returns the argument X, converted from degrees to radians. mysql> SELECT RADIANS(90); -> 1.570796  
400 COLLATION 25 COLLATION(str) Returns the collation for the character set of the string argument. mysql> SELECT COLLATION('abc'); -> 'latin1_swedish_ci' mysql> SELECT COLLATION(_utf8'abc'); -> 'utf8_general_ci'  
401 COALESCE 26 COALESCE(value,...) Returns the first non-NULL value in the list. mysql> SELECT COALESCE(NULL,1); -> 1 mysql> SELECT COALESCE(NULL,NULL,NULL); -> NULL  
402 VERSION 25 VERSION() Returns a string that indicates the MySQL server version. As of MySQL 4.1, the string has the utf8 character set. mysql> SELECT VERSION(); -> '4.1.3-beta-log'  
403 MAKE_SET 23 MAKE_SET(bits,str1,str2,...) Returns a set value (a string containing substrings separated by ',' characters) consisting of the strings that have the corresponding bit in bits set. str1 corresponds to bit 0, str2 to bit 1, and so on. NULL values in str1, str2, ... are not appended to the result. mysql> SELECT MAKE_SET(1,'a','b','c'); -> 'a' mysql> SELECT MAKE_SET(1 | 4,'hello','nice','world'); -> 'hello,world' mysql> SELECT MAKE_SET(1 | 4,'hello','nice',NULL,'world'); -> 'hello' mysql> SELECT MAKE_SET(0,'a','b','c'); -> ''  
404 FIND_IN_SET 23 FIND_IN_SET(str,strlist) Returns a value 1 to N if the string str is in the string list strlist consisting of N substrings. A string list is a string composed of substrings separated by ',' characters. If the first argument is a constant string and the second is a column of type SET, the FIND_IN_SET() function is optimized to use bit arithmetic. Returns 0 if str is not in strlist or if strlist is the empty string. Returns NULL if either argument is NULL. This function does not work properly if the first argument contains a comma (',') character. mysql> SELECT FIND_IN_SET('b','a,b,c,d'); -> 2  

query result ( 405 records )

Posted by 나비:D
:

[mysql] 정리본

2007. 12. 5. 15:37

0. 포기 선언
1. 이 문서에 대해서


2. MySQL의 특징 및 일반적인 질문들
 2.1 MySQL의 특징은 무엇인가요?
 2.2 Transaction이 지원 안된다면서요?
 2.3 License 방식을 알고 싶습니다.
 2.4 와우~ MySQL을 설치하고 싶네요.
     어떻게 해야 되죠?
    
3. MySQL의 설치에 관한 질문들
 3.1 설치는 어렵나요?
 3.2 설치에 필요한 하드웨어 최소 사양은 얼마나 되나요?
 3.3 설치하는 방법 좀 알려주세요.
 3.4 MySQL의 데몬의 구동
 3.5 흑흑..-_-; Access Denied가 나옵니다.
 
4. MySQL의 관리에 관한 질문들
 4.1 설치 후에 해야 할 일들
 4.2 새로운 사용자 추가
 4.3 Access Denied 좀 해결해주세요!
 4.4 root 암호를 잊어 버렸어여 T.T
 4.5 흠... 백업을 하려고 하는데...
 4.6 MySQL을 업그레이드 하려고 합니다.
 4.7 MySQL을 부팅 시에 자동으로 실행되게 하고 싶은에요.
 4.8 mysqld ended라고 나오면서
   데몬이 계속 죽습니다.
   
5. MySQL에서의 SQL 언어에 관한 질문들
 5.1 SQL 이란게 모죠?
 5.2 ANSI SQL92와 MySQL의 SQL과의 차이점은 몹니까?
 5.3 MySQL의 데이타 타입에 대해서
  5.3.1 MySQL의 데이타 타입을 알려주세요
  5.3.2 값이 자동으로 1씩 증가하게 하고 싶은데요.
  5.3.3 AUTO_INCREAMENT는 몬가요?
  5.3.4 한 컬럼에서 최대 얼마나 저장할 수 있나요?
  5.3.5 게시판 등의 본문을 저장하고 싶은데요.. 뭘 써야 하죠?
 5.4 MySQL에서의 SQL 언어
  5.4.1 CREATE
  5.4.2 INSERT
  5.4.3 SELECT
  5.4.4 ALTER
     5.4.5 어떤 database들이 있나 알고 싶은데요?
     5.4.6 어떤 테이블들이 있나 알고 싶어요.
     5.4.7 테이블의 컬럼 형식을 알고 싶어여.
     
6. MySQL+PHP+Apache에 관한 질문들
 6.1 설치하는 방법
 
7. MySQL C API에 관한 질문들
 7.1 알파벳 순으로 정리한 각 함수들의 설명을 넣자.
 7.2 간단한 예를 얻을 수 없을까요?
 
8. MySQL과 Perl에 관한 질문들
 In the Future
------------------------


0. 포기 선언


 이 문서에 있는 내용을 따라해보다
 당신의 컴퓨터에 어떠한 문제가 발생해도
 필자에게는 전혀 책임이 없다.
 따라서 이 문서를 읽는 사람들은
 신중해야 한다.
 



1. 이 문서에 대해서
 
 필자는 1998년 7월 처음으로 MySQL을 사용해 보았다.
 지금처럼 많은 사람들이 MySQL을 쓰고 있지
 않았으므로 문제에 부딪쳤을 때 해결하기가
 쉽지 않았다.
 
 요즘은 필자에게 질문을 해오는 사람들이 많다.
 질문을 해오는 사람들의 질문을 보면 메뉴얼만
 보면 해결할 수 있는 문제들이 대부분이지만,
 처음부터 영어로 된 방대한 양의 메뉴얼을 읽기란
 쉬운 것이 아니고, 또한 문제에 봉착한 사람들의
 *답답한* 마음을 알기에 최대한 시간을 내어
 질문에 답을 해 주고 있다.
 
 이 문서는
 
 i)    필자에게 온 질문들
 ii)   필자가 생각한 '흠, 이 문제는 누가 질문할거 같은데'
 
 라고 생각한 질문들과 답을 모아 놓은 문서들이다.
 
 7개의 섹션으로 질문들을 나눠 놓았다.
 하지만, 이 문서를 수정하는 사람은
 누구나 새로운 섹션을 추가할 수 있고,
 질문이 적절한 섹션에 있지 않을 경우
 옮길 수 있다.
 현재 이 문서는 MySQL 3.22.20 버전의 메뉴얼을 참고하였다.
 
 
2. MySQL의 특징 및 일반적인 질문들
 
 2.1 MySQL의 특징은 무엇인가요?
 
  메뉴얼에는 MySQL의 특징을 다음과 같이 말하고 있습니다.
 
  i) 커널 스레드를 이용한 멀티 스레드를 지원한다.
     따라서, CPU가 여러 개 있을 경우 여러 개의 CPU를
     잘 활용할 수 있다.
  i) C, C++, Java, Perl, PHP, Python 과 TCL에 대한 API를 제공한다.
  i) 여러 플랫폼에서 작동한다.
  i) 많은 컬럼 타입을 제공한다.
  i) one-sweep multijoin을 이용하여 Join이 매우 빠르다.
  i) SQL 함수들은 Optimized된 class library를 이용하여 구현되었다.
     또한 매우 빠르며, 불필요한 메모리 할당을 하지 않는다.
  i) 권한과 암호 시스템은 flexible하고 보안이 잘 되어 있다.
     원격의 서버에 접속할 때 모든 암호들은 암호화 되어 전송된다.
  i) ODBC를 지원한다. 따라서 Access를 이용해서 MySQL에 연결할 수 있다.
  i) 테이블에 16개의 인덱스를 줄 수 있다.
  i) 크기가 큰 데이타 베이스도 다룰 수 있다. 우리는(MySQL 메뉴얼 작성자)
     50,000,000 개의 레코드를 가지고 있는 데이타베이스도 다루고 있다.
  i) 메모리 누수가 없다.(상용 메모리 누수 감지 프로그램으로 테스트 했다)
  i) isamchk라는 유틸리티로 테이블 검사, 성능향상, 수리 등을 할 수 있다.
 
  이상이 MySQL의 메뉴얼에서 말하는 MySQL의 특징들을 정리한 것입니다.
  하지만 개인적으로 MySQL의 가장 큰 특징은 _빠르다_ 라고 생각합니다.
  그리고 리눅스 상에서 손쉽게 무료로 구해서 쓸 수 있고,
  또한 사람들이 많이 쓰고 있으므로, 문제가 생겼을 때 대답을 해줄
  사람들도 그만큼 많겠죠.
 
 2.2 Transaction이 지원되지 않는 다면서요?
 
  네. 그렇습니다. MySQL은 Transaction을 지원하지 않습니다.
  MySQL 개발자들은 Transaction이 속도를 매우 느리게 하므로
  Transaction을 구현하지 않기로 했습니다.
  하지만, 꼭 Transaction을 써야 할 경우 lock/unlock tables를
  이용하여 비슷한 효과를 낼 수 있습니다.
 
 2.3 MySQL의 License 방식을 알고 싶습니다.
 
  기본적으로 MS Windows 계열을 제외한 모든
  OS에서는 무료로 사용할 수 있습니다.
  다만 상용을 목적으로 사용하거나, MS Windows 계열에서
  사용할 경우에는 License를 사야합니다.
  1 Copy에 US 200$입니다.
  상용으로 사용한다고 해고, License없이 쓸 수 있는 경우가
  있습니다.
  돈이 들어간 문제는 복잡하므로 더 이상 이야기 하고 싶지
  않습니다.
  중요한 것은 무료로 사용할 수 있다는 것이죠.
 
 2.4 와우~ MySQL을 설치하고 싶네요.
     어떻게 해야 되죠?
    
     이제 MySQL에 매력을 느꼇나 보죠? 설치 방법은
     _3.3 MySQL을 설치하는 방법 좀 알려주세요_ 부분을 읽어
     보시기 바랍니다.
   
 3. MySQL의 설치에 관한 질문들
 
  3.1 설치는 어렵나요?
 
   NEVER!
   절대 어렵지 않습니다. 간혹 어려움을 겪는 사람들이 있는데
   대부분은 메뉴얼 등을 읽지 않고 대충 설치를 한 경우입니다.
  
     3.2 설치에 필요한 하드웨어 최소 사양은 얼마나 되나요?
      
      리눅스가 설치될 수 있는 하드웨어면 됩니다.
      오라클을 설치하다가 하드 디스크가 모라자서 윈도
      파티션을 지웠던 기억이 나는군여 -_-.
      MySQL은 정말 작고 빠릅니다.
~
      
     3.3 설치하는 방법 좀 알려주세요.
    
      MySQL을 설치하는 방법에는 rpm으로 설치하는 방법과
      Source Code로 설치하는 방법이 있겠죠.
      
      개인적으로 rpm으로 설치하는 방법은 추천하지 않습니다.
      rpm으로 설치하면 뭐랄까.. 재미가 없죠.
      Source Code로 설치하면 재미도 있고, 더욱 좋은 것은
      설치하고자 하는 소프트웨어에 대해 좀더 깊이 알 수 있습니다.        
   
   일단 MySQL의 소스 코드를 http://www.mysql.com에서 다운 받습니다.
   다운받은 파일을 적당한 디렉터리로 복사한 후에 다음과 같은 명령을
   내리면 됩니다.
   
   $ gzip -d mysql-Version.tar.gz
   $ tar xvf mysql-Version.tar
   $ cd mysql-Version
   $ ./configure  
   $ make
   $ make check
   $ su   (root 유저가 아닐 경우에만 실행)  
   # make install
   $ cd scripts
   $ ./mysql_install_db
   
   특별한 문제 없이 설치가 잘 될 것입니다.
   
   기본적으로 MySQL이 설치되는 디렉터리는 /usr/local/mysql 입니다.
   
   하지만, 자기가 운영하는 서버가 아닌 학교의 서버 등에
   MySQL에 설치할 경우 /usr/local/mysql에 쓰기 권환이 없으므로
   다른 디렉터리로 지정을 해야 하죠
   설치할 디렉터리를 지정하는 방법은
   
   $ ./configure --prefix=/원하는/디렉터리
   
   위처럼 하시면 됩니다.
   
   설치된 디렉터리 밑의 bin 디렉터리에 실행 파일들이 생깁니다.


  3.4 MySQL 데몬의 구동
   
   MySQL의 데몬이 실행되고 있어야 mysql을 사용할 수 있겠죠.
   MySQL이 설치된 디렉터리 밑의 bin/ 디렉터리에 보면
   safe_mysqld라는 프로그램이 있습니다.
   
   $ safe_mysqld &
   
   이렇게 실행을 하면 MySQL의 데몬이 구동되죠.
   
   MySQL은 TCP/IP로 Client와 통신을 하게 될 때 3306번 포트를 사용합니다.
   이 포트를 바꾸려면
   
   $ safe_mysqld -P 3333 &
   
   이렇게 -P 옵션으로 포트 번호를 바꿀 수 있습니다.
   
  3.5 흑흑..-_-; Access Denied가 나옵니다.  
 
   _4.3 Access Denied 좀 해결해주세요!_ 부분을 보시기 바랍니다.
     
 4. MySQL의 관리에 대한 질문들
 
  4.1 설치 후 해야 할 일들
 
   설치 후 가장 먼저 해야 할 일은 root user의 암호를
   정하는 일입니다.
   MySQL은 사용자을 -u 옵션으로 지정합니다.
   
   -u 옵션이 없을 경우 기본적으로 사용자의 계정을 사용합니다.
   또한 MySQL의 root 유저에는 초기에 암호가 걸려있지 않습니다.
   따라서 root 가 아닌 아무 사용자라도
   
   [wertyu@ localhost] $ mysql -u root
   
   처럼 해서 MySQL의 root 사용자가 될 수 있습니다.
   시스템의 계정이름과 MySQL의 계정 이름이 다르 다른 것을
   꼭 기억하고 있어야 합니다.
   
   암호를 거는 방법은 세 가지가 있습니다.
   
   i) update를 이용하는 방법
    SQL 문 중 update를 이용해서 mysql database 중
    user table의 root 사용자의 암호를 거는 방법입니다.
   
    $ mysql -u root mysql
    mysql> update user set password = password('새로운암호') where user = 'root';
    mysql> flush privileges ;
   
    MySQL에서는 사용자의 암호를 암호화 하여 저장합니다.
    암호를 암호화 하는 함수가 password()라는 함수이죠.
   
   ii) SET PASSWORD를 이용하기
    mysql> SET PASSWORD for root=password('새로운암호');
   
   iii) mysqladmin를 이용하는 방법
    $ mysqladmin -u root password 새로운암호
   
   이렇게 3 가지 방법 중 하나로 root 사용자의 암호를 바꾸실 수 있습니다.
   이때 i) 번 방법으로 할 경우 꼭 flush privileges; 를 실행 시켜야
   합니다.
   
   이제 mysql을 쓸 때마다 -p 옵션을 붙여야 합니다.
   
   $ mysql -u root -p
   
   4.2 새로운 사용자 추가
   
    새로운 사용자를 추가해 보겠습니다.
   
    $ mysql -u root mysql
    mysql> GRANT ALL PRIVILEGES ON *.* TO
         > wertyu@localhost
         > IDENTIFIED BY '암호' WITH GRANT OPTION;
    이렇게 해서 모든 database에 대해서 모든 권한을 갖는
    localhost의 wertyu라는 사용자를 추가했습니다.
   
    필자는 귀찮은 명령을 기억하기 싫으므로
    보통 다음 처럼 사용자를 직접 INSERT합니다.
   
    $mysql -u root mysql
    mysql> INSERT INTO user VALUES('localhost', 'wertyu', password('암호')
      > 'Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y') ;
    mysql> FLUSH PRIVILEGES ;
   
    사용자가 어느 하나의 database에만 접근을 하도록 추가할
    경우가 있습니다. 그때는 다음과 같은 명령을 내리면 됩니다.
   
    mysql> GRANT ALL PRIVILEGES ON inos.*
         > TO wertyu@localhost IDENTIFIED by '암호';
   
    위처럼 하여 inos라는 database에 모든 권한을 갖는
    wertyu라는 사용자를 추가할 수 있습니다.
   
    다음 명령은 SELECT, INSERT, UPDATE 권한만을 줄때의 명령입니다.
   
    mysql> GRANT SELECT, INSERT, UPDATE ON inos.*
         > TO wertyu@localhost IDENTIFIED by '암호' ;
        
   4.3 Access Denied 좀 해결해주세요!
   
    Access Denied가 나오면서 연결이 안되는 이유는 많이 있죠
   
    MySQL을 처음 설치하고 난 후에
    $ mysql -u root mysql
    이라는 명령을 내렸는데도
    Access Denied가 나왔다면  설치과정의 mysql_install_db 명령을
    빼먹고 설치 하신 것입니다.
   
    Access Denied using password no
    라고 나온다면 암호가 걸려 있는 사용자인데 암호를 입력하지 않아서
    나는 에러입니다.
   
    Access Denied using password yes
    라고 나온다면 암호를 사용했는데 입력한 암호가 틀렸을 경우이죠.
   
    이 외에도 수많은 경우가 있는데, 이 부분은 이 글을 읽는 다른 사용자들이
    직접 추가했으면 하는 바램입니다. 다함께 참여하는 문서가 되었으면 합니다.
   
  4.4 root 암호를 잊어 버렸어여 T.T
   
   root의 암호를 잊어 버렷을 때 정말 난감하죠.
   그렇다고 다시 MySQL을 설치하기에도 귀찮고 말이죠.
   
   이 경우에도 방법이 있습니다.
   
   먼저 MySQL의 데몬이 실행 중이라면 데몬의 실행을 중지 시키세요.
   
   이제 다시 MySQL의 데몬을 실행 시키는데 -Sg라는 옵션을 줍니다.
   
   $ safe_mysqld -Sg &
   
   -Sg는 Skip grant table의 약자이지요.
   이렇게 데몬을 실행 시키면 권한을 검사하지 않으므로
   누구나 MySQL에 접근할 수 있습니다.
   이제 mysql database의 user table의 암호 부분을
   UPDATE를 이용해서 직접 수정해 주면 되겠죠.
   
   MySQL 전체를 다시 설치하는 수고를 덜었으면 합니다. ^^
 
  4.5 흠... 백업을 하려고 하는데...어떻게 해야 하나요?
 
   백업을 하는 방법은 크게 두 가지 방법이 있습니다.
   MySQL의 데이타가 있느 디렉터리 밑에 있는 파일들을
   그냥 모두 복사해뒀다가, 필요할 때 다시
   처음 위치에 덮어 씌우는 방법이 있습니다.
   다른 방법으로는  mysqldump라는 유틸리티를 이용하는 방법
   입니다.
   mysqldump를 사용하는 방법을 설명 드리겠습니다.
   
   $ mysqldump [OPTIONS] database [tables]
   
   mysqldump는 SQL statement들을 생성합니다.
   현재 database안에 들어 있는 테이블의 형식과
   테이블 안의 데이타들 똑같이 만들어 낼 수 있는
   SQL statement들을 생성합니다.
   예를들어 foo라는 database가 있다고 가정하고,
   foo를 백업받으려고 할 경우
   
   $ mysqldump foo > foo.backup
   
   이렇게 하면 됩니다.
   mysqldump는 기본적으로  표준 출력으로 SQL statement들을
   출력하므로 foo.backup이라는 파일로 저장했습니다.
   
   복구를 하려면,
   
   $ mysql foo < foo.backup
   
   이런 식으로 저정된 SQL statement를 실행 시키면 됩니다.


  4.6 MySQL을 업그레이드 하려고 합니다. 기존의 데이타들은 어떻게 되죠?
   
   업그레이드를 할 경우, 새로운 버전의 MySQL 문서에서 업그레이드에 관한
   문서를 꼭 읽어보셔야 합니다.
   
   3.22.x 버전과 3.23.x의 데이타들은 호환이 됩니다.
   그리고 Major 버전이 같으면 데이타들은 거의 호환이 됩니다.
   또한, 버전이 올라가면서 데이타들이 호환이 안 될 경우,
   테이블의 구조를 업그레이드 시켜주는 유틸리티도 같이 배포됩니다.
   
   따라서 버전이 크게 변하지 않는 이상 MySQL의 업그레이드는
   MySQL의 설치 과정에서 mysql_install_db 과정만 빼면 됩니다.


  4.7 MySQL을 부팅 시에 자동으로 실행되게 하고 싶은데요.  
   
   제가 보통 쓰는 방법은
   /etc/rc.d/rc.local (레드햇 기준) 파일에
   
   MySQL이/설치된/디렉터리/safe_mysqld&
   
   위의 한 줄을 추가 하는 방법입니다.
   
  4.8 mysqld ended라고 나오면서 데몬이 계속 죽습니다.
 
   이런 경우 MySQL의 error log 파일을 살펴 봐야
   정확한 이유를 알 수 있습니다.
   error log는 기본적으로
   MySQL의 데이타가 저장된 디렉터리에
   host_name.err 라는 이름으로 저장됩니다.
   정확히 어디인지 모를 경우
   safe_mysqld 파일을 보고 MySQL의 데이타들이 어느 디렉터리에
   저장되는지 확인해 보시면 됩니다.
   
   error log의 파일을 보고 에러의 원인을 알아낸 후
   문제를 해결하면 됩니다.
   문제가 해결이 안될 경우 error log 파일의 내용을
   wertyu@nownuri.net으로 보내주시면 최대한 도움을
   드리도록 노력해 보겠습니다.
   
 5. MySQL에서의 SQL 언어에 관한 질문들
 
  5.1 SQL 이란게 모죠?
   SQL(Structured Query Language)는 DBMS에서
   데이타들을 조작하기 위한 언어입니다.
   언어라고 해서 C 언어처럼 컴파일을 하고 그렇진 않습니다.
   단순히 DBMS에 Query를 하고 결과를 얻어 오는 언어입니다.
   하지만 DB를 배우기 위해서는 꼭 배워야 하는 언어입니다.
   SQL 언어에 대해서 간단하게 나마 배워보고자 하면
   _5.4 MySQL에서의 SQL 언어_부분을 읽어보시기 바랍니다.  


  5.2 ANSI SQL92와 MySQL의 SQL과의 차이점은 몹니까?
   
   이 부분은 MySQL 메뉴얼에서 5 장을 읽어 보시면 자세히
   알 수 있습니다.
   MySQL에 없는 기능들은 다음과 같습니다.
   
   i) sub-selects
   i) select into table
   i) Stored procedures and triggers
      ( Stored procedure는 앞으로 지원할 계획임)  
 
  5.3 MySQL의 데이타 타입에 대해서
 
   5.3.1 MySQL의 데이타 타입을 알려주세요
   
    밑의 정리된 자료는 제가 예전에 리눅스 월드라는
    잡지에 기고 했던 글 중의 일부입니다.
    새로 쓰기 귀찮아서 그냥 옛날의 글을 사용하도록 하겠습니다.
   
    **************************************************************
    TINYINT : 부호있는 수는 -128에서 127까지, 부호 없는 수는 0에서 255까지      표현할 수 있다. 1 바이트
    SMALLINT : 부호있는 수는 -32768에서 32767까지, 부호 없는 수는 0에서
         65535까지 표현할 수 있다. 2 바이트
    MEDIUMINT : 부호있는 수는 -8388608부터 8388607까지, 부호없는 수는 0에서
     16777215까지의 수를 표현할 수 있다. 3 바이트
    INT      : 부호있는 수는 -2147483648부터 2147483647까지, 부호없는 수는
     0에서 4294967295까지의 수를 표현할 수 있다. 4 바이트  
    INTEGER   : INT와 같다.
    BIGINT   : 부호있는 수는 -9223372036854775808부터 9223372036854775807
     까지의 수를 표현할 수 있고, 부호없는 수는 0부터 18446744073709551615까지
     표현할 수 있다. 8바이트
    FLOAT    : 단일 정밀도를 가진 부동 소수점을 나타낸다. 언제나 부호 있는 수이고,
     -3.402823466E+38부터 3.402823466E+38까지의 수를 표현할 수 있다.
    DOUBLE   : 2배 정밀도를 가진 부동 소수점 수이다. 언제나 부호있는 수이고,
           -1.79769313486231517E+308부터 1.7976931348623157E+308까지의
        수를 표현할 수 있다.
       DATE     : 날짜를 표현하는 타입으로 '1000-01-01'부터 '9999-12-31'까지를
        나타낼 수 있다. 3 바이트
       DATETIME : 날짜와 시간을 같이 나타내는 타입이다. '1000-01-01 00:00:00'
        부터 '9999-12-31 23:59:59'까지 나타낼 수 있다. 8 바이트
    TIMESTAMP: '1970-01-01 00:00:00'부터 2037년까지 나타낼 수 있다. 4 바이트
    TIME     : 시간을 나타낸다. '-839:59:59'부터 '838:59:59'까지 나타낼 수 있다.
    YEAR     : 년도를 나타낸다. 1901년부터 2155년, 0000년을 나타낼 수 있다.
    CHAR(M)  : 고정 길이를 갖는 문자열을 저장할 수 있다. M은 1부터255까지이다.
        M이 20이면 20개의 문자를 저장할 수 있다.
    VARCHAR(M):CHAR는 고정길이인 반면 VARCHAR는 가변 길이이다. 예를 들어
        VARCHAR(20)인 컬럼에 10자만 저장을 하면, 실제로도 10자 만큼을
       기억장소를 차지한다. 하지만, CHAR는 나머지 10자를 공백으로 매꾼다.  
      TINYBLOB,TINYTEXT : 255개의 문자를 저장할 수 있다. BLOB은 BINARY LARGE OBJECT의 약자이다.
      BLOB,TEXT     : 65535개의 문자를 저장할 수 있다.
      MEDIUMBLOB, MEDIUMTEXT : 16777215개의 문자를 저장할 수 있다.
      LONGBLOB,LONGTEXT : 4294967295(4기가)개의 문자를 저장할 수 있다.    
      
      ************************************************************************
   5.3.2 값이 자동으로 1씩 증가하게 하고 싶은데요.  
   
    컬럼의 값을 자동으로 1씩 증가시키는 경우는 매우 많습니다.
    간단히 게시판을 생각한다면, 현제 게시물의 경우가 140인데
    두 명이 동시에 게시물을 올린다고 생각해 봅시다.
    이런 경우 두 글이 모두 141번이 될 수 있기 때문에 ,
    어느 한쪽에서 먼저 table에 Lock을 거는 방법을 이용하죠.
    이런 경우 값을 자동으로 1씩 증가 시킬 수 있다면
    편하겠죠? ^^
   
    MySQL에서는 AUTO_INCREMENT를 이용하면 됩니다.
    다음의 예를 보죠.
   
    mysql> create table test( id int not null auto_increment,
         > primary key( id ) ) ;
    mysql> insert into test(NULL) ;
    mysql> insert into test(NULL) ;
    mysql> insert into test(NULL) ;
    mysql> select * from test ;
          -------
          | id  |
          -------
          |  1  |
          |  2  |
          |  3  |
          -------
    auto_increment를 사용하기 위한 컬럼은 언제나 not null이어야 하고,
    index이어야 합니다.
   
   5.3.3 AUTO_INCREAMENT는 몬가요?  
     
     _5.3.2_절을 보시기 바랍니다.
   
   5.3.4 한 컬럼에서 최대 얼마나 저장할 수 있나요?
   
    MySQL는 파일 시스템이 지원하는 최대 파일 크기까지의
    용량을 저장할 수 있습니다.
    리눅스의 경우는 최대 2GB까지 저장할 수 있고,
    UNIX 계열의 경우는 4GB입니다.
    주의하실 점은 MySQL이 다룰 수 있는 데이타의 크기가
    2GB혹은 4GB가 아니라는 점입니다.
   
    MySQL의 데이타 타입 중 가장 큰 타입은
    longtext, longblob으로 4294967295 개의 문자를 저장할 수 있죠.


   5.3.5 게시판 등의 본문을 저장하고 싶은데요.. 뭘 써야 하죠?
   
    text(65535자), mediumtext(16777215자), longtext(4294967295자)
    위의 세 개의 타입 중 원하는 것을 쓰시면 됩니다.
   
  5.4 MySQL에서의 SQL 언어
 
   이 부분은 In the Future에 쓰도록 하겠습니다.
   http://www.inos.co.kr/wertyu
   에 가시면 필자가 예전에 적어 놓은 글들이 있습니다.
   급하신 분들은 가서 보시고... 급하지 않으시거나
   공부하고 싶으신 분들은 책을 사서 보는게 더 좋습니다.
   SQL은 기초를 정말 확실히 닦아 놔야 뒤에 가서 고생하지
   않습니다.
   


 7. MySQL C API에 관한 질문들
  7.1 알파벳 순으로 정리한 각 함수들의 설명을 넣자.


   1) my_ulonglong mysql_affected_rows(MYSQL* mysql)
    INSERT, UPDATE, DELETE 등의 query로 영향을 받은 ROW의 수를 리턴한다.
   2) void mysql_close(MYSQL* mysql)   서버와의 연결을 종료한다.
   3) void mysql_data_seek(MYSQL_RES* result, unsigned int offset)
    result에서 임의의 ROW에 접근을 하도록 하는 함수이다. offset이 row의 번호를
    나타낸다. 0이면 처음 ROW, mysql_num_rows( result ) - 1 은 마지막 row를 나타낸다.
   4) unsigned int mysql_errno(MYSQL* mysql)  가장 최근에 mysql에 일어난 에러의 번호를 리턴한다.
   5) char* mysql_error(MYSQL* mysql)  가장 최근에 일어난 에러 메시지를 리턴한다.
   6) MYSQL_FIELD* mysql_fetch_field(MYSQL_RES* result)
    한번 호출할 때마다 한 나의 필드에 대한 정보를 리턴한다.
   7) MYSQL_FIELDS* mysql_fetch_fields(MYSQL_RES* result)
    배열 형대로 result의 필드에 대한 정보를 한꺼번에 리턴한다.
   8) MYSQL_FIELD_OFFSET mysql_field_seek(MYSQL* mysql, MYSQL_FIELD_OFFSET offset)
    임의의 필드에 접근을 하도록 한다.
   9) MYSQL_FIELD_OFFSET mysql_field_tell(MYSQL_RES* result)
    현재 필드의 offset을 리턴한다.
   10) void mysql_free_result(MYSQL_RES* result)
    result에 할당된 메모리를 해제한다.  
   11) MYSQL* mysql_init(MYSQL* mysql)
    mysql 객체를 초기화 한다. 인자가 NULL이면 새로운 MYSQL 객체를 생성하고, 초기화 하여 리턴한다.
   12) MYSQL_RES* mysql_list_dbs(MYSQL* mysql, const char* wild)
    현재 서버에 있는 데이타베이스의 목록을 리턴한다. wild는 MySQL에서
    사용할 수 있는 정규식을 나타낸다.    
    result = mysql_list_dbs( &mysql,"%" )
    는 모든 데이타베이스를 리턴하는 예이다.(%는 '모든'을 나타낸다)
   13) MYSQL_RES* mysql_list_tables(MYSQL* mysql, const char* wild)
    현재 데이타베이스에 있는 테이블들의 목록을 리턴한다.
   14) unsigned int mysql_num_fields(MYSQL_RES*result) 혹은
    unsigned int mysql_num_fields(MYSQL* mysql)  필드의 수를 리턴한다.
   15) my_ulonglong mysql_num_rows(MYSQL_RES* result)
    result에 총 몇 개의 ROW가 있는지 리턴한다. query 수행 후
    mysql_store_result()를 호출하였을 경우에만 사용할 수 있고,  
    mysql_use_result()는 사용할 수 없다.
   16) int mysql_ping(MYSQL* mysql)  
    서버에 연결 중인지를 리턴한다. 연결이 끊어 졌을 경우, 다시
    연결을 시도한다. 서버와 연결을 한 후 오랫동안 가만히 있으면
    서버가 연결을 끊어버리는데, 이런 경우에 사용한다.
   17) int mysql_query(MYSQL* mysql, const char* query)
    query가 포인트 하는 쿼리를 수행한다. query의 끝은 NULL 문자이다.
    성공적으로 query를 수행하였으면 0을 리턴한다.
   18) MYSQL* mysql_real_connect(MYSQL* mysql, const char* host, const char* user,
     const char* passwd, const char* db, uint port, const char* unix_socket,
     unit client_flag )
     host와의 연결을 시도한다.
   19) int mysql_real_query(MYSQL* mysql, const char* query, unsigned int length)
     mysql_query()처럼 query를 수행하나, query의 끝이 legnth인 것이 다르다.
   20) MYSQL_ROW_OFFSET mysql_row_tell(MYSQL_RES* result)
    현재 ROW의 offset을 리턴한다.
   21) int mysql_select_db(MYSQL* mysql, const char* db)
    사용하고자 하는 database를 변경한다. mysql_query()를 이용하여 "use db이름"
    의 query를 수행해도 같은 결과를 얻는다.
   22) int mysql_shutdown(MYSQL* mysql)
    서버를 종료시킨다. 현재 사용자에게 shutdown 권한이 있어야 한다.
   23) MYSQL_RES* mysql_store_result(MYSQL* mysql)
    query의 수행 결과를 서버로부터 한 번에 모두 받아 온다.
   24) MYSQL_RES* mysql_use_result(MYSQL* mysql)
    query의 수행 결과를 서버로부터 한 개의 ROW 씩 받아 온다.
   
  7.2 간단한 예를 얻을 수 없을까요?
   
   가끔씩 MySQL의 메일링 리스트에 같은 질문이 올라 옵니다.
   그런 질문에 대한 답변을 보면 모두,
   MySQL의 Client 프로그램인 mysql의소스를 보라고 하죠. ^^
   맞는 말입니다. mysqleh C API를 이용해서 만들었습니다.
   
   하지만 저는 이런 식의 답변을 무지 싫어 합니다.
   아주 간단한 소스는 바로 밑에 있습니다.
   
   소스의 원본이나 MySQL의 C API에 대한 더욱 자세한
   설명은
   http://www.inos.co.kr/wertyu
   방문하시면 됩니다.
   
   ***********************************************************
   1: #include <stdio.h>
   2: #include <mysql.h>
   3: #include <errno.h>
   4:
   5: void main(void)
   6: {
   7:  MYSQL   mysql ;
   8:  MYSQL_RES*  res ;
   9:  MYSQL_ROW row ;
   10:  int   fields ;
   11:  
   12:  mysql_init(&mysql) ;
   13:
   14:  if(!mysql_real_connect(&mysql, NULL, "사용자","암호", "test" ,3306, (char *)NULL, 0))
   15:  {
   16:   printf("%s\n",mysql_error(&mysql));
   17:   exit(1) ;
   18:  }
   19:
   20:  if(mysql_query(&mysql, "USE super") )
     // mysql_query()는 query 수행시에 에러가 나게 되면  
     // 0이 아닌 값을 리턴한다.  
     {
      printf("%s\n", mysql_error(&mysql) ;  
      exit(1) ;  
     }
   21:  if(mysql_query(&mysql, "SELECT * FROM dome") )  
     {
      printf("%s\n", mysql_error(&mysql) ;  
      exit(1) ;  
     }
   22:
   23:  res = mysql_store_result( &mysql ) ;
   24:  fields = mysql_num_fields(res) ;
   25:
   26:  while( ( row = mysql_fetch_row( res ) ))
   27:  {
   28:   for( cnt = 0 ; cnt < fields ; ++cnt)
   29:    printf("%12s ", row[cnt]) ;
   30:
   31:   printf("\n") ;
   32:  }
   33:
   34:  mysql_free_result( res ) ;
   35:  mysql_close(&mysql) ;
   36: }

Posted by 나비:D
:

처음으로 만들 Helloworld 는 함수였습니다.

함수와 프로시져를 서로 만드는 법이 틀리죠. 하지만 구조가 많이 비슷합니다.


Functions

함수는 항상 리턴 값이 존재합니다. 그리고 꼭 하나의 값만 리턴합니다.

MySQL에서 자주 사용하는 CONCAT 라는 함수를 보겠습니다.


mysql> select concat(emp_name,' ',dept_id) from emps;

+------------------------------+

| concat(emp_name,' ',dept_id) |

+------------------------------+

| Roger 1 |

| John 2 |

| Alan 1 |

+------------------------------+

3 rows in set (0.00 sec)



위와 같이 두개의 글자를 합해서 하나의 글자로 리턴하는 CONCAT 함수를 보았습니다.

MySQL에서 제공하는 스트링 함수이지만 이제부터는 개발자가 직접 함수를 만들어 사용할수 있습니다.


함수는 꼭 Select 명령을 통해서만 결과를 볼수 있습니다.


Procedures



프로시져는 함수보다 작은 기능을 가지고 있습니다.

함수와 거의 같지만 리턴 값만 없다고 보시면 됩니다.

간단한 함수를 하나 만들어보겠습니다.


--------------------------------


create procedure helloprocedure()

select 'Hello Procedure' ;


---------------------------------


위에 Procedure를 실행시킬때는 call 이라는 명령어를 통해 실행시킵니다.


mysql> call helloprocedure();

+-----------------+

| Hello Procedure |

+-----------------+

| Hello Procedure |

+-----------------+

1 row in set (0.00 sec)


Query OK, 0 rows affected (0.00 sec)


이제 기존이 프로시져를 삭제하고 다시 생성해보겠습니다.

아래의 코드는 helloprocedure 라는 프로시져를 만들고

begin .. end 을 통해 작성하였습니다.

-------------------------------------------------

delimiter //


drop procedure if exists helloprocedure

//


create procedure helloprocedure()

begin

select 'Hello Procedure 2' ;

end

//

-------------------------------------------------


mysql> call helloprocedure() //

+-------------------+

| Hello Procedure 2 |

+-------------------+

| Hello Procedure 2 |

+-------------------+

1 row in set (0.00 sec)


Query OK, 0 rows affected (0.00 sec)


이제 여러분 간단하게 프로시져와 함수를 만들고 실행시키는 법에 대해서

간단하게 이해 하셨을거라 생각합니다.


http://mysql.gilfster.com/page.php?parent_id=1.1&page_id=1.1.4


SQLGate Development Team


http://www.antwiz.com


Blog : http://isql.blogspot.com/

Posted by 나비:D
:

첫번째로 helloworld 을 만들었는데 좀더 자세히 설명하도록 하겠습니다.


현재 Helloworld 함수는 varchar(20) 을 return 하도록 구성되어 있습니다.


간단하게 출력해 보면 보시는 바와 같 "Hello World" 을 출력합니다.


참 함수를 실행할때는 Select 명령어를 실행해야 합니다.


그럼 다시 한번 Helloworld 함수를 삭제하고 다른 내용을 출력해 보겠습니다.


먼저 helloworld을 Drop 시켜 보겠습니다.


Drop 명령어는 두가지가 있습니다.


drop function helloworld //


or


drop function if exists helloworld //


두 차이점은 코드에서 보는거 처럼 함수가 있음면 삭제할것인지 여부를 한번더 물어보시는거라 생각하시면 됩니다.

첫번째 drop 명령어는 helloworld 라는 함수가 없으면 에러는 발생합니다.


이 강좌에서는 drop function if exists 를 사용하겠습니다.


--------------------------------------------------------------------------

drop function if exists helloworld

//

create function helloworld() returns varchar(20)

begin

return "Hello World 2";

end

//

select helloworld() //

--------------------------------------------------------------------------

결과는


mysql> select helloworld() //

+---------------+

| helloworld() |

+---------------+

| Hello World 2 |

+---------------+

1 row in set (0.00 sec)


이정도 보셨으면 아주 간단함을 알수 있습니다.

다만 확실히 기억하실것은 Function 은 Return 값이 있어야 하고

함수를 실행시키실때는 Select 명령어를 통해서 한다는것 기억하세요 ^^


참조 : http://mysql.gilfster.com/page.php?parent_id=1.1&page_id=1.1.3


SQLGate Development Team

http://www.antwiz.com


Blog : http://isql.blogspot.com/

Posted by 나비:D
:

MySQL 5.0 의 새로운 기능에 대해서 조금씩 살펴보겠습니다.

하루에 한시간씩 정리해서 올려 놓도록 노력해보겠습니다.


본 내용은 http://mysql.gilfster.com 에서 발취한 내용입니다.

보다 많은 정보는 http://mysql.gilfster.com/ 에서 참조하시기 바랍니다.


개발환경

OS : Windows 2003

DB : MySQL 5.0.11

사양 : 팬티엄 4 CPU 3.00GHZ, 1.0 GB RAM


모든샘플링은 직접 커멘트에서 작성하기 때문에 바로 Copy 하셔서 사용하셔도 무방하실거라 생각됩니다.

----------


----------

사이에 코드는 직접 카피하셔도 되는 코드들입니다.


Test 데이타를 샘플링 하기 위해서 데이타베이스를 생성하고 테이블을 만든 후에 함수를 생성해 보겠습니다.


-----------------------------------------------------------------------------------

DELIMITER //


drop database if exists pers

//

create database pers

//

use pers

//

create table emps(emp_id int NOT NULL,

emp_name varchar(30),

dept_id int,

salary decimal(5,2),

primary key(emp_id))

//

insert into emps (emp_id,emp_name,dept_id,salary)

values (1,'Roger',1,2000.00),(2,'John',2,2500.00),(3,'Alan',1,2100.00)

//

select * from emps

//

create table dept (dept_id int NOT NULL,

description varchar(30),

primary key(dept_id))

//

insert into dept (dept_id,description)

values (1,'Information Technology'),(2,'Sales')

//

select * from dept

//

-----------------------------------------------------------------------------------

mysql> select * from dept //

+---------+------------------------+

| dept_id | description |

+---------+------------------------+

| 1 | Information Technology |

| 2 | Sales |

+---------+------------------------+

2 rows in set (0.00 sec)


위와 같은 내용이 나타나면 됩니다.

데이타베이스 pers 와 테이블 emps , dept 를 만들었습니다.


MySQL 5.0 이후 부터 delimiter 라는것이 생겼는데, 이것은 그전 버전에서 ; 로 명령을 분리했던것과는 차별을 두기 위해 만든것입니다.


위에 코드에서 보듯이

select * from dept //


라는 명령을 쳐야 실행되는걸 볼수 있는거 처럼 사용자가 구분자를 직접 지정할수 있습니다.


예를 들면


mysql> delimiter $$

mysql> select 'hello' $$

+-------+

| hello |

+-------+

| hello |

+-------+

1 row in set (0.00 sec)


이제 첫번째로 function 을 만들어 보겠습니다.


------------------------------

delimiter //

create function helloworld() returns varchar(20)

return "Hello World" //

-------------------------------

Query OK, 0 rows affected (0.00 sec)


함수를 처음으로 생성하였습니다. 이제 이 생성한 helloworld 함수를 호출해 보겠습니다.


mysql> select helloworld() //

+--------------+

| helloworld() |

+--------------+

| Hello World |

+--------------+

1 row in set (0.00 sec)


처음으로 글을 쓰는거라 잘 이해가 가지 않더라도 차차 좋아질거라 생각합니다.

다음에 다시 글 쓰겠습니다.


참조 : http://mysql.gilfster.com/page.php?parent_id=1.1&page_id=1.1.2


SQLGate Development Team

http://www.antwiz.com


Blog : http://isql.blogspot.com/

Posted by 나비:D
:

1. MySql 5 다운받기

 

MySql 사이트에서 MySQL 5 Community Server 를 공짜로 다운을 받을 수 있습니다.

http://dev.mysql.com/downloads/mysql/5.0.html#downloads

 

* Enterprise 버전이 있기는 하나 이것은 유료버전이므로 다운을 받을 수 없습니다.

 

각자의 OS환경에 맞는 파일을 선택하여 다운받을 수 있는데

전 여기서 Windows downloads 에 있는 Windows(x86) Zip/Setup.EXE 을 다운받을 겁니다.

Windows Essentials (x86) 은 기본적인 버전이므로 그닥 필요하지도 않습니다.

 

 

2. MySQL 5 설치하기

  -> Custom 선택

  -> 설치위치 변경 (보통적으로 C:\Program Files\MySQL\MySQL Server 5.0\) 이므로 변경을 합니다.

  -> 만약 MySQL 사이트의 가입정보가 있으면 Login to MySQL.com 을 선택하여 정보를 입력하시고

      없으시면 Skip Sign-Up 를 선택하여 넘어가셔도 됩니다.

 

  -> 이렇게 다 설치하시면 이제 MySQL Server Instance Configuration Wizard 가 실행이 됩니다.

      이 부분은 설정을 잘 못하셨어도 재 설정을 할수 있습니다.

  -> Detailed Configuration 선택

  -> Server Machine 선택

      (* Dedicated MySQL Server Machine 는 한가지 일만 수행할 수 있도록 구성을 하는겁니다. 웹서버, 메일서버 등)

  -> Multifunctional Database 선택

  -> InnoDB Tablespace Setting 부분은 그냥 다음으로 넘어갑니다.

  -> Decisiion Support (DSS)/OLAP 선택

  -> Enable TCP/IP Networking 체크

      port Number : 3306 기본포트로 설정

      Enable Strict Mode 체크

  -> Manual Selected Default Character Set / Collation 선택하신 후

      Charter Set 을 euckr 로 선택하세요

  -> Install As windows Service 체크

      Include Bin Directory in Windows PATH 체크

      이렇게 2가지를 체크를 하면 윈도우즈의 서비스에 MySQL 을 등록하고

      윈도우즈의 환경설정부분의 PATH 부분에 MySQL의 bin 디렉토리를 자동으로 추가해줍니다.

  -> Modify Security Setting 체크 후 비밀번호를 입력해주세요

  -> 이제 Excute 를 클릭하면 설치가 끝납니다.

 

 

3. MySql GUI Tools 다운받기

MySQL 만 설치를 하면 불편한점이 MySQL 의 시작과 종료를 command 창을 통해서 해야합니다.

그런데 이 MySQL GUI Tools 이 있으면 다른 아파치나 톰캣처럼 윈도우즈 트레이창에 MySQL 이 떠있어서

편하게 시작/종료를 하고 많은 기능을 관리할 수 있습니다.

저도 몰랐었는데 이 툴을 설치하니까 그렇더군요..그래서 아주 편하게 관리를 하고 있습니다.

 

http://dev.mysql.com/downloads/gui-tools/5.0.html 에서 시스템의 OS에 맞는 버전을 다운로드합니다.

저는 Windows downloads 의 Windows(x86) 을 다운받았습니다.

 

 

참 유용한 MySQL 관리도구입니다.

mysql 의 관리도구로

 

 

4. MySQL GUI Tools 설치하기

  -> 설치시 설치파일의 위치를 MySQL과 동일한 부분에 설치를 하세요

      예) MySQL 을 C:\MySQL\MySQL Server 5.0\ 에 설치를 했으면

           MySQL GUI Tools 는 C:\MySQL\MySQL Tools for 5.0 에 설치를 하시면 됩니다.

  -> 그밖에는 변경할 것 없이 그냥 Next 를 클릭하여서 설치를 완료하시면 됩니다.

  -> 설치가 완료되면 프로그램에 다음과 같이 메뉴가 추가된것을 보실 수 있습니다.



  -> MySQL System Tray Monitor 을 실행하시면 트래이창에 MySQL 을 시작/종료 및 여러가지를 관리할 수 있습니다.



5. 기타

어디까지나 제가 알아낸 방식이므로 정확하지 않을 수도 있습니다. ^^;

그래도 GUI Tools 을 통해서 많은것을 컨트롤 할 수 있으니 참 재밌네요

Posted by 나비:D
:

BLOG main image
by 나비:D

공지사항

카테고리

분류 전체보기 (278)
Programming? (0)
---------------------------.. (0)
나비의삽질 (5)
Application (177)
SQL (51)
Web (27)
etc. (14)
Omnia (0)
---------------------------.. (0)

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함

달력

«   2024/03   »
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
31
Total :
Today : Yesterday :