×
Create a new article
Write your page title here:
We currently have 3,189 articles on s23. Type your article name above or create one of the articles listed here!



    s23
    3,189Articles

    The World's Most Popular Open Source Database[edit]

    The MySQL database server is the world's most popular open source database. Its architecture makes it extremely fast and easy to customize. Extensive reuse of code within the software and a minimalistic approach to producing functionally-rich features has resulted in a database management system unmatched in speed, compactness, stability and ease of deployment. The unique separation of the core server from the storage engine makes it possible to run with strict transaction control or with ultra-fast transactionless disk access, whichever is most appropriate for the situation.

    The MySQL database server is available for free under the GNU General Public License (GPL). Commercial licenses are available for users who prefer not to be restricted by the terms of the GPL.

    Four different versions[edit]

    There are four versions of the database server available:


    1. MySQL Standard includes the standard MySQL storage engines and the InnoDB storage engine. InnoDB is a transaction-safe, ACID-compliant storage engine with commit, rollback, crash recovery and row-level locking capabilities. This version is for users who want the high-performance MySQL database with full transaction support. MySQL Standard is licensed under the GPL. MySQL Pro is the commercially-licensed version of the server with the same feature-set.
    2. MySQL Max is for the user who wants early access to new features. This version includes the standard MySQL storage engines, the InnoDB storage engine, and other extras like the Berkeley database (BDB) storage engine, SSL transport-layer encryption, and support for splitting tables across multiple files to avoid operating system file size limitations. In future releases, MySQL Max will include more cutting-edge features.
    3. MySQL Pro is the commercially licensed version of the MySQL Standard database server, including InnoDB support.
    4. MySQL Classic only includes the standard MySQL storage engines, differing from MySQL Pro and MySQL Standard only by the omission of the InnoDB storage engine. It is only available under a commercial license.

    Examples[edit]

    The structure from top to bottom is: server->database->table->field->content

    So get to the place you want in this order:

    Connecting to mysql server from the shell.[edit]

    shell> mysql -u root -p
    Enter password:
    Welcome to the MySQL monitor.
    mysql>
    


    Switching into a database.[edit]

    mysql> use wikidb;
    Database changed
    mysql>
    


    Showing tables[edit]

    mysql> show tables;
    +------------------+
    | Tables_in_wikidb |
    +------------------+
    | archive          |
    | blobs            |
    ...
    | imagelinks       |
    | interwiki        |
    ...
    | watchlist        |
    +------------------+
    23 rows in set (0.00 sec)
    

    Getting field names[edit]

    mysql> describe interwiki;
    +-----------+------------+------+-----+---------+-------+
    | Field     | Type       | Null | Key | Default | Extra |
    +-----------+------------+------+-----+---------+-------+
    | iw_prefix | char(32)   |      | PRI |         |       |
    | iw_url    | char(127)  |      |     |         |       |
    | iw_local  | tinyint(1) |      |     | 0       |       |
    +-----------+------------+------+-----+---------+-------+
    3 rows in set (0.00 sec)
    

    Selecting content[edit]

    mysql> select iw_prefix from interwiki;
    +-------------------+
    | iw_prefix         |
    +-------------------+
    | AbbeNormal        |
    | AcadWiki          |
    | Acronym           |
    | Advogato          |
    | AIWiki            |
    ...
    | Wiktionary        |
    | YpsiEyeball       |
    | ZWiki             |
    +-------------------+
    107 rows in set (0.00 sec)
    

    Using wildcards[edit]

    You can use wildcards like in:

    mysql> select * from interwiki;
    

    Conditions (WHERE-clause)[edit]

    You can combine with conditions like in:

    exact match:

    mysql> select iw_url from interwiki where iw_prefix="UseMod";
    +------------------------------------------+
    | iw_url                                   |
    +------------------------------------------+
    | http://www.usemod.com/cgi-bin/wiki.pl?$1 |
    +------------------------------------------+
    1 row in set (0.00 sec)
    

    approximate match:

    at beginning

    mysql> select cur_title from cur where cur_text LIKE "Fnord%";
    

    in the middle

    mysql> select cur_title from cur where cur_text LIKE "%Foobar%";
    


    Sorting[edit]

    ascending:[edit]

    mysql> select rc_id,rc_title from recentchanges ORDER BY rc_id;
    

    descending:[edit]

    mysql> select rc_id,rc_title from recentchanges ORDER BY rc_id DESC;
    

    Limiting[edit]

    
    mysql> select rc_id from recentchanges LIMIT 0,3;
    +-------+
    | rc_id |
    +-------+
    |     1 |
    |     2 |
    |     3 |
    +-------+
    3 rows in set (0.00 sec)
    
    mysql> select rc_id from recentchanges LIMIT 1,4;
    +-------+
    | rc_id |
    +-------+
    |     2 |
    |     3 |
    |     4 |
    |     5 |
    +-------+
    4 rows in set (0.00 sec)
    

    (output max. 4 line from offset 1). Starts with offset 0 and 0 is default if second parameter not given.


    Creating databases and tables[edit]

    Creating a database[edit]

    mysql> CREATE DATABASE foobar;
    Query OK, 1 row affected (0.02 sec)
    

    Switching to database[edit]

    mysql> use foobar;
    Database changed
    

    Creating a simple table[edit]

    mysql> CREATE TABLE blargh (name VARCHAR(20), owner VARCHAR(20), sex CHAR(1), birth DATE);
    

    Creating a table with auto-incrementing id[edit]

    mysql> CREATE table fnord (id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id),name VARCHAR(30), whatever VARCHAR(7));
    Query OK, 0 rows affected (0.00 sec)
    

    Data field types used in CREATE syntax[edit]

    Numbers[edit]

    TINYINT - -128 to 127 normal / 0 to 255 UNSIGNED.

    SMALLINT - -32768 to 32767 normal / 0 to 65535 UNSIGNED.

    MEDIUMINT - -8388608 to 8388607 normal / 0 to 16777215 UNSIGNED.

    INT - a numeric type which can accept values in the range of -2147483648 to 2147483647

    BIGINT( ) - -9223372036854775808 to 9223372036854775807 normal / 0 to 18446744073709551615 UNSIGNED.

    DECIMAL - a numeric type with support for floating-point or decimal numbers

    FLOAT - A small number with a floating decimal point.

    DOUBLE - a numeric type for double-precision floating-point numbers. If you don't know what these are, chances are you won't be using it much.

    Text[edit]

    CHAR - a string type with a maximum size of 255 characters and a fixed length

    VARCHAR - a string type with a maximum size of 255 characters and a variable length

    TEXT - a string type with a maximum size of 65535 characters

    MEDIUMTEXT - a string with a maximum length of 16777215 characters.

    LONGTEXT A string with a maximum length of 4294967295 characters.

    Date and Time[edit]

    DATE - a date field in the YYYY-MM-DD format

    TIME - a time field in the HH:MM:SS format

    DATETIME - a combined date/time type in the YYYY-MM-DD HH:MM:SS format

    YEAR - a field specifically for year displays in the range 1901 to 2155, in either YYYY or YY formats

    TIMESTAMP - a timestamp type, in YYYYMMDDHHMMSS format

    Misc[edit]

    BLOB - a binary type for variable data (MEDIUMBLOB, LONGBLOB .. )

    ENUM - a string type which can accept one value from a list of previously-defined possible values

    SET - a string type which can accept zero or more values from a set of previously-defined possible values

    Giving access to users[edit]

    Examples:


    mysql> GRANT ALL PRIVILEGES ON test.* TO 'root'@'localhost' IDENTIFIED BY 'goodsecret' REQUIRE SSL;
    
    mysql> GRANT SELECT ON foo.bar TO 'fnord'@'somehost' IDENTIFIED BY 'somepass';
    


    These are random examples, for further syntax check:

    Client does not support authentication protocol[edit]

    If you happen to get Client does not support authentication protocol, The most likely reason is that: MySQL 5.0 uses an authentication protocol based on a password hashing algorithm that is incompatible with that used by older (pre-4.1) clients.

    You can fix it either by upgrading all client programs to use a 4.1.1 or newer client library or by resetting a password to the old style via:

    mysql> SET PASSWORD FOR 'some_user'@'some_host' = OLD_PASSWORD('newpwd');
    

    read here for details

    Setting the initial root password[edit]

    shell> mysql -u root mysql
    mysql> SET PASSWORD FOR root@localhost=PASSWORD('new_password');
    

    Reset forgotten root password[edit]

    1. Take down the mysqld server by sending a kill (not kill -9) to the mysqld server.
    2. Restart mysqld with the --skip-grant-tables option.
    3. mysqladmin -u root password 'mynewpassword'
    4. Restart mysqld normally

    You are also able to reset the mysql root password by the help of the following line, while server is up:

    # /etc/init.d/mysql reset-password
    New MySQL root password:
    Verify:
    Setting new MySQL root password
    


    How to Reset a Forgotten Root Password

    Making backups / mysqldump[edit]

    Create[edit]

    mysqldump -u root -p somedatabase > dumpfile.sql
    
    mysqldump --compatible=mysql40 -u root -p somedatabase > dumpfile.sql 
    

    (to be compatible with certain versions, you can also use other '--compatible=' strings)

    Import[edit]

    mysql -u root -p somedatabase < dumpfile.sql
    


    Sending output to textfile[edit]

    mysql> select foo from bar INTO OUTFILE '/tmp/dump.txt';
    
    bash> mv /tmp/dump.txt .
    

    (if trouble writing because mysql user has different permissions)


    Taking input from textfile[edit]

    mysql> mysql -u root -p < dumpfile.sql
    Enter password:
    


    Cheat Sheet[edit]

    to prevent SQL injections never trust user input and never insert user filled variables into mysql statements right away, in PHP mysql_real_escape_string ()

    Get total size of .MYI files[edit]

    weirdo way[edit]

    echo "Size of MYI files in current directory: `(for file in \`ls | grep MYI\`; do echo -n "\`du -bs $file | cut -f1\`+"; done; echo "0") | bc` bytes"

    normal way[edit]

    You can do the same "a little" shorter,too ;) (< LordFrith> mutante, du -ch *MYI), *gg*

    du -ch *MYI | tail -n1


    symbiosis[edit]

    for file in `ls -d /var/lib/mysql/ */`; do echo -n "$file "; du -ch ./$file/*MYI | tail -n1; done


    du -ch /var/lib/mysql/*/*MYI

    Why ?[edit]

    (*) - "By adding up the size of the .MYI files for the tables, you'll have a good idea how large to set the buffer." [1]

    mytop[edit]

    mytop - top like query monitor for MySQL
    

    drop tables with wildcard / by prefix[edit]

    in Bash: for file in /var/lib/mysql/database/prefix*.MYI; do echo "drop table `basename $file | cut -d. -f1`;" > droptables.sql; done

    loops through all tables with "prefix*" and writes a bunch of "drop table blah;" statements into a file "droptables.sql". This file can then be executed via something like mysql -u root -p database < droptables.sql either manually or as a second line in a bash script. the password should be entered interactively to avoid it showing up in process list on a multiuser host.

    External Links[edit]

    IRC[edit]

    Help channels on IRC:

    1. #mysql on EfNet
    2. #mysql on Freenode


    Group by Delete via temp table[edit]

    <+mutante> hi, i do something like "select foo,bar,count(id) from table group by foo order by count(id);"
    <+mutante> now i would like to "delete ... where count(id) (from above) = 1"
    <+mutante> can i combine that?
    <+mutante> i want to delete all rows where there is only one foo per bar
    
    <+salle> mutante: Create temporary table out of the query above
    <+salle> mutante: CREATE TEMPORARY TABLE temp SELECT foo, COUNT(id) AS c FROM tbl GROUP BY foo HAVING c = 1;
    
    <+salle> mutante: CREATE TEMPORARY TABLE temp SELECT foo AS c FROM tbl GROUP BY foo HAVING c = 1;
    <+salle> mutante: Now use that table in DELETE
    <+salle> mutante: If it's so small MEMORY engine works perfect. If big it's wise to add some index on the fly
    <+salle> mutante: DELETE FROM your_table WHERE foo IN (SELECT foo FROM temp); should work
    <+salle> mutante: MySQL doesn't allow DELETE FROM x WHERE .. (SELECT ... FROM x)
    <+salle> mutante: same for UPDATE. In many cases it is doable with multi-table DELETE and UPDATE syntax, but GROUP BY makes it more difficult if possible at all
    
    Cookies help us deliver our services. By using our services, you agree to our use of cookies.
    Cookies help us deliver our services. By using our services, you agree to our use of cookies.