Articles by "MySQL"

Showing posts with label MySQL. Show all posts

Justin Silverton at Jaslabs has a supposed list of 10 tips for optimizing MySQL queries. I couldn’t read this and let it stand because this list is really, really bad. Some guy named Mike noted this, too. So in this entry I’ll do two things: first, I’ll explain why his list is bad; second, I’ll present my own list which, hopefully, is much better. Onward, intrepid readers!

Why That List Sucks

  1. He’s swinging for the top of the trees

    The rule in any situation where you want to opimize some code is that you first profile it and then find the bottlenecks. Mr. Silverton, however, aims right for the tippy top of the trees. I’d say 60% of database optimization is properly understanding SQL and the basics of databases. You need to understand joins vs. subselects, column indices, how to normalize data, etc. The next 35% is understanding the performance characteristics of your database of choice. COUNT(*) in MySQL, for example, can either be almost-free or painfully slow depending on which storage engine you’re using. Other things to consider: under what conditions does your database invalidate caches, when does it sort on disk rather than in memory, when does it need to create temporary tables, etc. The final 5%, where few ever need venture, is where Mr. Silverton spends most of his time. Never once in my life have I used SQL_SMALL_RESULT.
  2. Good problems, bad solutions

    There are cases when Mr. Silverton does note a good problem. MySQL will indeed use a dynamic row format if it contains variable length fields like TEXT or BLOB, which, in this case, means sorting needs to be done on disk. The solution is not to eschew these datatypes, but rather to split off such fields into an associated table. The following schema represents this idea :


    CREATE TABLE posts (
        id int UNSIGNED NOT NULL AUTO_INCREMENT,
        author_id int UNSIGNED NOT NULL,
        created timestamp NOT NULL,
        PRIMARY KEY(id)
    );

    CREATE TABLE posts_data (
        post_id int UNSIGNED NOT NULL.
        body text,
        PRIMARY KEY(post_id)
    );

  3. That’s just…yeah

    Some of his suggestions are just mind-boggling, e.g., “remove unnecessary paratheses.” It really doesn’t matter whether you do SELECT * FROM posts WHERE (author_id = 5 AND published = 1) or SELECT * FROM posts WHERE author_id = 5 AND published = 1. None. Any decent DBMS is going to optimize these away. This level of detail is akin to wondering when writing a C program whether the post-increment or pre-increment operator is faster. Really, if that’s where you’re spending your energy, it’s a surprise you’ve written any code at all

My list

Let’s see if I fare any better. I’m going to start from the most general.
  1. Benchmark, benchmark, benchmark!

    You’re going to need numbers if you want to make a good decision. What queries are the worst? Where are the bottlenecks? Under what circumstances am I generating bad queries? Benchmarking is will let you simulate high-stress situations and, with the aid of profiling tools, expose the cracks in your database configuration. Tools of the trade include supersmack, ab, and SysBench. These tools either hit your database directly (e.g., supersmack) or simulate web traffic (e.g., ab).

  2. Profile, profile, profile!

    So, you’re able to generate high-stress situations, but now you need to find the cracks. This is what profiling is for. Profiling enables you to find the bottlenecks in your configuration, whether they be in memory, CPU, network, disk I/O, or, what is more likely, some combination of all of them.
    The very first thing you should do is turn on the MySQL slow query log and install mtop. This will give you access to information about the absolute worst offenders. Have a ten-second query ruining your web application? These guys will show you the query right off.
    After you’ve identified the slow queries you should learn about the MySQL internal tools, like EXPLAIN, SHOW STATUS, and SHOW PROCESSLIST. These will tell you what resources are being spent where, and what side effects your queries are having, e.g., whether your heinous triple-join subselect query is sorting in memory or on disk. Of course, you should also be using your usual array of command-line profiling tools like top, procinfo, vmstat, etc. to get more general system performance information.

  3. Tighten Up Your Schema

    Before you even start writing queries you have to design a schema. Remember that the memory requirements for a table are going to be around #entries * size of a row. Unless you expect every person on the planet to register 2.8 trillion times on your website you do not in fact need to make your user_id column a BIGINT. Likewise, if a text field will always be a fixed length (e.g., a US zipcode, which always has a canonical representation of the form “XXXXX-XXXX”) then a VARCHAR declaration just adds a superfluous byte for every row.
    Some people poo-poo database normalization, saying it produces unecessarily complex schema. However, proper normalization results in a minimization of redundant data. Fundamentally that means a smaller overall footprint at the cost of performance — the usual performance/memory tradeoff found everywhere in computer science. The best approach, IMO, is to normalize first and denormalize where performance demands it. Your schema will be more logical and you won’t be optimizing prematurely.

  4. Partition Your Tables

    Often you have a table in which only a few columns are accessed frequently. On a blog, for example, one might display entry titles in many places (e.g., a list of recent posts) but only ever display teasers or the full post bodies once on a given page. Horizontal vertical partitioning helps :


    CREATE TABLE posts (
        id int UNSIGNED NOT NULL AUTO_INCREMENT,
        author_id int UNSIGNED NOT NULL,
        title varchar(128),
        created timestamp NOT NULL,
        PRIMARY KEY(id)
    );

    CREATE TABLE posts_data (
        post_id int UNSIGNED NOT NULL,
        teaser text,
        body text,
        PRIMARY KEY(post_id)
    );

    The above represents a situation where one is optimizing for reading. Frequently accessed data is kept in one table while infrequently accessed data is kept in another. Since the data is now partitioned the infrequently access data takes up less memory. You can also optimize for writing: frequently changed data can be kept in one table, while infrequently changed data can be kept in another. This allows more efficient caching since MySQL no longer needs to expire the cache for data which probably hasn’t changed.

  5. Don’t Overuse Artificial Primary Keys

    Artificial primary keys are nice because they can make the schema less volatile. If we stored geography information in the US based on zip code, say, and the zip code system suddenly changed we’d be in a bit of trouble. On the other hand, many times there are perfectly fine natural keys. One example would be a join table for many-to-many relationships. What not to do :


    CREATE TABLE posts_tags (
        relation_id int UNSIGNED NOT NULL AUTO_INCREMENT,
        post_id int UNSIGNED NOT NULL,
        tag_id int UNSIGNED NOT NULL,
        PRIMARY KEY(relation_id),
        UNIQUE INDEX(post_id, tag_id)
    );

    Not only is the artificial key entirely redundant given the column constraints, but the number of post-tag relations are now limited by the system-size of an integer. Instead one should do :


    CREATE TABLE posts_tags (
        post_id int UNSIGNED NOT NULL,
        tag_id int UNSIGNED NOT NULL,
        PRIMARY KEY(post_id, tag_id)
    );

  6. Learn Your Indices

    Often your choice of indices will make or break your database. For those who haven’t progressed this far in their database studies, an index is a sort of hash. If we issue the query SELECT * FROM users WHERE last_name = 'Goldstein' and last_name has no index then your DBMS must scan every row of the table and compare it to the string ‘Goldstein.’ An index is usually a B-tree (though there are other options) which speeds up this comparison considerably.
    You should probably create indices for any field on which you are selecting, grouping, ordering, or joining. Obviously each index requires space proportional to the number of rows in your table, so too many indices winds up taking more memory. You also incur a performance hit on write operations, since every write now requires that the corresponding index be updated. There is a balance point which you can uncover by profiling your code. This varies from system to system and implementation to implementation.

  7. SQL is Not C

    C is the canonical procedural programming language and the greatest pitfall for a programmer looking to show off his database-fu is that he fails to realize that SQL is not procedural (nor is it functional or object-oriented, for that matter). Rather than thinking in terms of data and operations on data one must think of sets of data and relationships among those sets. This usually crops up with the improper use of a subquery :


    SELECT a.id,
        (SELECT MAX(created)
        FROM posts
        WHERE author_id = a.id)
    AS latest_post
    FROM authors a

    Since this subquery is correlated, i.e., references a table in the outer query, one should convert the subquery to a join


    SELECT a.id, MAX(p.created) AS latest_post
    FROM authors a
    INNER JOIN posts p
        ON (a.id = p.author_id)
    GROUP BY a.id

  8. Understand your engines

    MySQL has two primary storange engines: MyISAM and InnoDB. Each has its own performance characteristics and considerations. In the broadest sense MyISAM is good for read-heavy data and InnoDB is good for write-heavy data, though there are cases where the opposite is true. The biggest gotcha is how the two differ with respect to the COUNT function.
    MyISAM keeps an internal cache of table meta-data like the number of rows. This means that, generally, COUNT(*) incurs no additional cost for a well-structured query. InnoDB, however, has no such cache. For a concrete example, let’s say we’re trying to paginate a query. If you have a query SELECT * FROM users LIMIT 5,10, let’s say, running SELECT COUNT(*) FROM users LIMIT 5,10 is essentially free with MyISAM but takes the same amount of time as the first query with InnoDB. MySQL has a SQL_CALC_FOUND_ROWS option which tells InnoDB to calculate the number of rows as it runs the query, which can then be retreived by executing SELECT FOUND_ROWS(). This is very MySQL-specific, but can be necessary in certain situations, particularly if you use InnoDB for its other features (e.g., row-level locking, stored procedures, etc.).
  9. MySQL specific shortcuts

    MySQL provides many extentions to SQL which help performance in many common use scenarios. Among these are INSERT ... SELECT, INSERT ... ON DUPLICATE KEY UPDATE, and REPLACE.
    I rarely hesitate to use the above since they are so convenient and provide real performance benefits in many situations. MySQL has other keywords which are more dangerous, however, and should be used sparingly. These include INSERT DELAYED, which tells MySQL that it is not important to insert the data immediately (say, e.g., in a logging situation). The problem with this is that under high load situations the insert might be delayed indefinitely, causing the insert queue to baloon. You can also give MySQL index hints about which indices to use. MySQL gets it right most of the time and when it doesn’t it is usually because of a bad scheme or poorly written query.

  10. And one for the road…

    Last, but not least, read Peter Zaitsev’s MySQL Performance Blog if you’re into the nitty-gritty of MySQL performance. He covers many of the finer aspects of database administration and performance. 

Sources : http://20bits.com

To connect to the server, you will usually need to provide a MySQL user name when you invoke mysql and, most likely, a password. If the server runs on a machine other than the one where you log in, you will also need to specify a host name. Contact your administrator to find out what connection parameters you should use to connect (that is, what host, user name, and password to use). Once you know the proper parameters, you should be able to connect like this:


shell> mysql -h host -u user -p
Enter password: ********

host and user represent the host name where your MySQL server is running and the user name of your MySQL account. Substitute appropriate values for your setup. The ******** represents your password; enter it when mysql displays the Enter password: prompt.

If that works, you should see some introductory information followed by a mysql> prompt:

shell> mysql -h host -u user -p
Enter password: ********

Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 25338 to server version: 5.0.89-standard

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql>

The mysql> prompt tells you that mysql is ready for you to enter commands.

If you are logging in on the same machine that MySQL is running on, you can omit the host, and simply use the following:

shell> mysql -u user -p

If, when you attempt to log in, you get an error message such as ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2), it means that the MySQL server daemon (Unix) or service (Windows) is not running. Consult the administrator or see the section of Chapter 2, Installing and Upgrading MySQL that is appropriate to your operating system.

For help with other problems often encountered when trying to log in, see Section B.5.2, “Common Errors When Using MySQL Programs”.

Some MySQL installations allow users to connect as the anonymous (unnamed) user to the server running on the local host. If this is the case on your machine, you should be able to connect to that server by invoking mysql without any options:

shell> mysql

After you have connected successfully, you can disconnect any time by typing QUIT (or \q) at the mysql> prompt:

mysql> QUIT
Bye

On Unix, you can also disconnect by pressing Control-D.

Most examples in the following sections assume that you are connected to the server. They indicate this by the mysql> prompt.


Source : http://dev.mysql.com

* Essentially three books in one, provides thorough introductions to the PHP language, MySQL database, and shows you how these two technologies can be effectively integrated to build powerful websites.
* Provides over 500 code examples, including real-world tasks such as providing an auto-login feature, sending HTML-formatted email, testing password guessability, and uploading files via a Web interface.
* Updated for MySQL 5, includes new chapters introducing triggers, stored procedures, and views.

Interested in becoming a master of the PHP language and MySQL database but don't know where to begin? This bestselling book ranks among the most thorough and practical guides in print, covering all of the key concepts and features, and showing you how to effectively integrate PHP and MySQL to build powerful websites.

The book begins with a vast overview of PHP's capabilities, starting with a survey of the installation and configuration process on both the Windows and Linux platforms. Next, several chapters are devoted to basic PHP concepts, including variables, datatypes, arrays, functions, string manipulation, and processing user input. Other key PHP topics are also covered, including PEAR, session handling, LDAP integration, the Smarty templating engine, Web services, and PDO.

Next up is a presentation of MySQL's key features. You're first guided through MySQL's installation and configuration process, and are presented with an introduction to its storage engines, datatypes, administration utilities, security features, and data import/export facilities. New MySQL 5-specific chapters have been added in this edition, covering triggers, stored procedures, and views. Along the way, you'll gain insight into PHP's assortment of MySQL functions (using both the mysql and mysqli extensions), and learn how to create and execute queries, perform searches, and carry out key database tasks from within your Web application.
What You Will Learn from This Book

  • Install and configure Apache, PHP and MySQL on both Windows and Linux
  • Accept and process information submitted via HTML forms
  • Authenticate users and track user preferences and data using PHP's session-handling capabilities
  • Process Web-based file uploads using the HTTP_Upload PEAR package
  • Create your own RSS aggregator using Magpie, and process XML files in amazingly efficient fashion using SimpleXML
  • Use both command-line and graphical MySQL clients to effectively manage your data
  • Secure the MySQL server, creating roles and restricting access even at very granular levels
  • Effectively integrate PHP and MySQL to create dynamic, data-driven web applications

Who This Book Is For

This book is for the budding web developer searching for a powerful and low-cost solution to building flexible, scalable websites.

Read More : Beginning PHP and MySQL: From Novice to Professional, Third Edition

Pembahsan kali ini tentang dasar-dasar MySQL, buat yang sudah mahir share ilmunya disini donk. Perintah apa aja yang terdapat dalam MySQL ??

Perintah dalam MySQL ada 2 macam :
  1. Perintah untuk lingkungan MySQL itu sendiri
  2. Perintah untuk mengelola database

Perintah dalam lingkungan MySQL
Kalian dapat menggunakan perintah \h atau help, perintah ini untuk menampilkan daftar perintah yang dapat digunakan dalam lingkungan MySQL. Menggunkan perintah ada 2 cara yaitu \ diikuti dengan satu huruf atau dengan menuliskan secara lengkap perintahnya help . Di bawah ini daftar perintah yang digunakan dalam lingkungan MySQL serta kegunaannya

help (\h) : Menampilkan daftar perintah di lingkungan MySQL
? (\?) : Sinonim dari help
clear (\c) : Perintah menghapus
Connect (\r) : Menghubungkan kembali kepada database MySQL, dapat disertai dengan option db dan host
edit (\e) : Melakukan pengeditan perintah-perintah SQL yang ada di dalam buffer, dengan menggunakan editor teks default dari sistem Unix *)
exit (\q) : Keluar dari MySQL
go (\g) : Mengirimkan perintah kepada MySQL
ego(\G) : Mengirimkan perintah kepada MySQL, menampilkan hasiknya secara vertikal
print (\p) : Mencetak perintah saat ini
quit (\q) : Keluar dari MySQL
rehast (\#) : Membangun kembali hash
status (\s) : menampilkan status server MySQL
use (\u) : Membuat/mengganti koneksi kepada database
source (\.) : Mengeksekusi perintah SQL dari dalam file **)
tee (\t) : Mengarahkan keluaran untuk disimpan ke dalam file, selalu menambahkan hasil kepada file output **)
notee (\T) : Mencegah output supaya tidak ditulis ke dalam file **)

*) menunjukkan bahwa perintah ini hanya tersedia di lingkungan MySQL dengan sistem operasi *nik (Linux)
**) Perintah ini hanya ada pada MySQL di lingkungan Windows

MySQL dalam Windows mempunyai perintah tambahan notee, source dan tee, sedangkan dalam Linux tidak mempunyainya tetapi mempunyai perintah tambahan edit.

Perintah untuk mengelola Database

Pengelolaan database dapat dilakukan dengan menggunakan perintah-perintah SQL (Structured Query Language), bahasa yang khusus digunakan untuk melakukan akses database relasional.

Perintah SQL, dikelompokkan menjadi :

  • DDL (Data Definition Language)
  • DML (Data Manipulation Language)
  • DCL (Data Control Language)

DDL merupakan perintah yang digunakan untuk membuat dan mendefinisikan database dan stuktur datanya.

DML merupakan perintah yang digunakan untuk melakukan pengelolaan data yang ada dalam database.

DCL merupakan perintah untuk melakukan pendifinisian pemakai yang boleh mengakses database dan apa saja privilegenya.

Wah dah banyak nih tulisannya, mungkin itu yang bisa saya sampaikan, dan semoga pembahasan tersebut bermanfaat bagi pembacanya,, amin...

Buat kalian yang ingin belajar tentang database dengan menggunakan open source terutama MySQL simak deh penjelasan berikut :

MYSQL merupakan software siatem manajemen database (Database Manajemen System - DBMS) yang sangat populer di kalangan pemrograman web, terutama di lingkungan Linux dengan menggunakan script PHP dan Perl. Software database ini kini telah tersedia juga pada platform sistem operasi Windows (98/ME ataupun NT/2000/XP).

MySQL kini dikenal sebagai software manajemen open source, sebelumnya merupakan software shareware. Shareware adalah suatu software yang dapat didistribusikan secara bebas untuk keperluan penggunaan secara pribadi, tetapi jika digunakan secara komersial maka pemakai harus membayar lisensi dari pembuatnya, sedangkan open source menjadikan software dapat didistribusikan secara bebas dapat dipergunakan untuk keperluan pribadi ataupun komersial, lebih dari setengah juta server yang memasangnya termasuk didalamnya yahoo!, MP3.com, Motorola, Nasa, Silicon Graphics, HP, Xerox, Cisco, dan Texas Instruments.

Penghargaan terhadap MySQL

MyQL mendapatkan pengharagaan sebagai database terbaik untuk server Linux versi Linux Magazine tahun 2002 dan 2001, dan sebagai database favorite pada tahun 2000
Mungkin ini bisa menambah wawasan kalian dan pembahasan selanjutnya tentang dasar-dasar MySQL....

Untuk perancangan database kalian harus mengetahui lebih detail tentang spesifikasi tipe data yang tersedia dalam MySQL, sehingga pada saat perancangan dapat dengan tepat memilih tipe data berkaitan dengan optimasi penggunaan space di dalam storage komputer.

Tipe data secara umum dapat dikelompokkan menjadi data,

1. Nilai Numerik : semua data yang berupa bilangan (angka) yang dapat dimanipulasikan dengan menggunakan operasi matematika.

Nilai Numerik dibedakan ada dua :

1. Integer : tidak memiliki pecahan
2. Float : memiliki angka pecahan

Tipe Data Numerik :

TINYINT : Nilai integer yang sangat kecil
SMALLINT : Nilai integer yang kecil
MEDIUMINT : Integer dengan nilai medium
INT : Integer dengan nilai standar
BIGINT : Integer dengan nilai besar
FLOAT : Bilangan desimal dengan single-precission
DOUBLE : Bilangan desimal dengan double-precission
DECIMAL : Bilangan float (desimal) yang dinyatakan sebagai string
Spesifikasi tipe data numerik
TINYINT : Signed : -128 s/d 127, Unsigned : 0 s/d 255, Byte = 1
SMALLINT : Signed : -32768 s/d 32767, Unsigned : 0 s/d 255, Byte = 2
MEDIUMINT : Signed : -8388608 s/d 8388607, Unsigned : 0 s/d 16777215, Byte = 3
INT : Signed : -2147483648 s/d 2147483647, Unsigned : 0 s/d 4294967295, Byte = 4
BIGINT : Signed : -9223372036854775808 s/d 9223372036854775807, Unsigned : 0 s/d 18446744073709551615, Byte = 8
FLOAT : Minimum : +- 1.175494351e-38, Maksimum : +- 3.402823466e+38, Byte : 4
DOUBLE : Minimum : +- 2.2205738585072014e-308, Maksimum : +- 1.7976931348623457e+308, Byte : 8
DECIMAL (M,D) : tergantung pada nilai M dan D, Byte : M+2


Keterangan :

Signed : data yang disimpan dalam suatu kolom bisa – s/d +
Unsigned : Digunakan agar data yang dimasukkan bukan data negatif, (>=0).

Untuk pembahasan “Nilai String” dan “Nilai tanggal dan jam” akan saya bahas lain waktu, so tungguin aja selanjutnya....
Bersambung....

Author Name

Contact Form

Name

Email *

Message *

Powered by Blogger.