MySQL (pronounced "my ess cue el") is an open source relational database management system (RDBMS) that uses Structured Query Language (SQL), the most popular language for adding, accessing, and processing data in a database. Because it is open source, anyone can download MySQL and tailor it to their needs in accordance with the general public license. MySQL is noted mainly for its speed, reliability, and flexibility.
If you look at the large variety of SQL commands, they can be divided into three large subgroups. Data Definition Language deals with database schemas and descriptions of how the data should reside in the database, therefore language statements like CREATE TABLE or ALTER TABLE belong to DDL. DML deals with data manipulation, and therefore includes most common SQL statements such SELECT, INSERT, etc. Data Control Language includes commands such as GRANT, and mostly concerns with rights, permissions and other controls of the database system.
SELECT COUNT (user_id) FROM users would only return the number of user_id’s.
Use DISTINCT in the query, such as SELECT DISTINCT user_firstname FROM users; You can also ask for a number of distinct values by saying SELECT COUNT (DISTINCT user_firstname) FROM users;
SELECT book_title FROM books LIMIT 25, 100. The first number in LIMIT is the offset, the second is the number.
SELECT SQL_CALC_FOUND_ROWS page_title FROM web_pages LIMIT 1,10; SELECT FOUND_ROWS(); The second query (not that COUNT() is never used) will tell you how many results there’re total, so you can display a phrase "Found 13,450,600 results, displaying 1-10". Note that FOUND_ROWS does not pay attention to the LIMITs you specified and always returns the total number of rows affected by query.
SELECT team_name FROM teams WHERE team_won IN (2, 4, 6, 8)
SELECT user_name FROM users WHERE ISNULL(user_phonenumber);
It’s equivalent to saying SELECT user_name, user_isp FROM users LEFT JOIN isps WHERE users.user_id=isps.user_id
SELECT LAST_INSERT_ID() will return the last value assigned by the auto_increment function. Note that you don’t have to specify the table name.
Makes the MySQL engine refuse UPDATE and DELETE commands where the WHERE clause is not present.
What it means is that so of the data that you’re trying to delete is still alive in another table. Like if you have a table for universities and a table for students, which contains the ID of the university they go to, running a delete on a university table will fail if the students table still contains people enrolled at that university. Proper way to do it would be to delete the offending data first, and then delete the university in question. Quick way would involve running SET foreign_key_checks=0 before the DELETE command, and setting the parameter back to 1 after the DELETE is done. If your foreign key was formulated with ON DELETE CASCADE, the data in dependent tables will be removed automatically.
When you’re not deleting by row ID. Such as in DELETE FROM techpreparation_com_questions ORDER BY timestamp LIMIT 1.
SHOW INDEX FROM techpreparation_questions;
ALTER TABLE techpreparation_questions CHANGE techpreparation_content techpreparation_CONTENT VARCHAR(50).
ALTER TABLE techpreparation_answers DROP answer_user_id.
ALTER TABLE techpreparation_questions ENGINE innodb;
1. VARCHARs with length less than 4 become CHARs
2. CHARs with length more than 3 become VARCHARs.
3. NOT NULL gets added to the columns declared as PRIMARY KEYs
4. Default values such as NULL are specified for each column
SHOW DATABASES LIKE ‘tech%’;
CONCAT (string1, string2, string3)
SELECT SUBSTR(title, 1, 10) from techpreparation_questions;
The first is, naturally, the character count. The second is byte count. For the Latin characters the numbers are the same, but they’re not the same for Unicode and other encodings.
SELECT (techpreparation_question USING utf8);
% corresponds to 0 or more characters, _ is exactly one character.
At least one character. Appendix G. Regular Expressions from MySQL manual is worth perusing before the interview.
SELECT MONTH(techpreparation_timestamp) from techpreparation_questions;
SELECT DATE_FORMAT(techpreparation_timestamp, ‘%Y-%m-%d’) from techpreparation_questions; A similar TIME_FORMAT function deals with time.
ADDDATE(techpreparation_publication_date, INTERVAL 3 MINUTE)
Internally Unix timestamps are stored as 32-bit integers, while MySQL timestamps are stored in a similar manner, but represented in readable YYYY-MM-DD HH:MM:SS format.
UNIX_TIMESTAMP converts from MySQL timestamp to Unix timestamp, FROM_UNIXTIME converts from Unix timestamp to MySQL timestamp.
You can limit the possible values that go into the table. CREATE TABLE months (month ENUM ‘January’, ‘February’, ‘March’,…); INSERT months VALUES (’April’);
As unique integers representing the powers of two, due to storage optimizations.
net start MySQL, net stop MySQL
mysql is the object-oriented version of mysql library functions.
3306 is the default port for MYSQL.
tee followed by a filename turns on MySQL logging to a specified file. It can be stopped by command note.
Yes, and name it ~/.my.conf. You might want to change the permissions on the file to 600, so that it’s not readable by others.
mysqladmin -u root -p password "newpassword"
mysqldump -h mysqlhost -u username -p mydatabasename > dbdump.sql
Describe the tasks you accomplished with these tools.
There is no user without a password. There is no user without a user name. There is no user whose Host column contains % (which here indicates that the user can log in from anywhere in the network or the Internet). There are as few users as possible (in the ideal case only root) who have unrestricted access.
In MyISAM static all the fields have fixed width. The Dynamic MyISAM table would include fields such as TEXT, BLOB, etc. to accommodate the data types with various lengths. MyISAM Static would be easier to restore in case of corruption, since even though you might lose some data, you know exactly where to look for the beginning of the next record.
It compressed the MyISAM tables, which reduces their disk usage.
Row-level locking, transactions, foreign key constraints and crash recovery.
Much more conservative approach to disk space management - each MyISAM table is stored in a separate file, which could be compressed then with myisamchk if needed. With InnoDB the tables are stored in tablespace, and not much further optimization is possible. All data except for TEXT and BLOB can occupy 8,000 bytes at most. No full text indexing is available for InnoDB. TRhe COUNT(*)s execute slower than in MyISAM due to tablespace complexity.
HEAP tables are in-memory. They are usually used for high-speed temporary storage. No TEXT or
BLOB fields are allowed within HEAP tables. You can only use the comparison operators = and <=>. HEAP tables do not support AUTO_INCREMENT. Indexes must be NOT NULL.
MySQL config variable max_heap_table_size.
Those are the special tables, data for which is saved into comma-separated values files. They cannot be indexed.
Introduced in MySQL 5.0, federated tables allow access to the tables located on other databases on other servers.
BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT
SERIAL is an alias for BIGINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE
It stops incrementing. It does not overflow to 0 to prevent data losses, but further inserts are going to produce an error, since the key has been used already.
Prior to MySQL 5.0.3: those are all synonyms. After MySQL 5.0.3: BIT data type can store 8 bytes of data and should be used for binary data.
FLOATs store floating point numbers with 8 place accuracy and take up 4 bytes.
DOUBLEs store floating point numbers with 16 place accuracy and take up 8 bytes.
REAL is a synonym of FLOAT for now.
999.99 to -99.99. Note that with the negative number the minus sign is considered one of the digits.
That field gets the current timestamp whenever the row gets altered.
Create two columns of type TIMESTAMP and use the second one for your real data.
The column exhibits the same behavior as a single timestamp column in a table with no other timestamp columns.
On initialization places a zero in that column, on future updates puts the current value of the timestamp in.
A default value is used on initialization, a current timestamp is inserted on update of the row.
CHAR(3), since MySQL automatically adjusted the data type.
MySQL is a very fast, multi-threaded, multi-user, and robust SQL (Structured Query Language) database server.
A database is a structured collection of data. It may be anything from a simple shopping list to a picture gallery or the vast amounts of information in a corporate network. To add, access, and process data stored in a computer database, you need a database management system such as MySQL. Since computers are very good at handling large amounts of data, database management plays a central role in computing, as stand-alone utilities, or as parts of other applications.
MySQL is very fast, reliable, and easy to use. If that is what you are looking for, you should give it a try. MySQL also has a very practical set of features developed in very close cooperation with our users. You can find a performance comparison of MySQL to some other database managers on our benchmark page. See section 12.7 Using Your Own Benchmarks. MySQL was originally developed to handle very large databases much faster than existing solutions and has been successfully used in highly demanding production environments for several years. Though under constant development, MySQL today offers a rich and very useful set of functions. The connectivity, speed, and security make MySQL highly suited for accessing databases on the Internet.
DISTINCT is converted to a GROUP BY on all columns, DISTINCT combined with ORDER BY will in many cases also need a temporary table.
When combining LIMIT # with DISTINCT, MySQL will stop as soon as it finds # unique rows.
If you don't use columns from all used tables, MySQL will stop the scanning of the not used tables as soon as it has found the first match.
SELECT DISTINCT t1.a FROM t1,t2 where t1.a=t2.a;
In the case, assuming t1 is used before t2 (check with EXPLAIN), then MySQL will stop reading from t2 (for that particular row in t1) when the first row in t2 is found.
In some cases MySQL will handle the query differently when you are using LIMIT # and not using HAVING:
If you are selecting only a few rows with LIMIT, MySQL will use indexes in some cases when it normally would prefer to do a full table scan.
If you use LIMIT # with ORDER BY, MySQL will end the sorting as soon as it has found the first # lines instead of sorting the whole table.
When combining LIMIT # with DISTINCT, MySQL will stop as soon as it finds # unique rows.
In some cases a GROUP BY can be resolved by reading the key in order (or do a sort on the key) and then calculate summaries until the key value changes. In this case LIMIT # will not calculate any unnecessary GROUP BY's.
As soon as MySQL has sent the first # rows to the client, it will abort the query.
LIMIT 0 will always quickly return an empty set. This is useful to check the query and to get the column types of the result columns.
The size of temporary tables uses the LIMIT # to calculate how much space is needed to resolve the query.
If you want to delete all rows in the table, you should use TRUNCATE TABLE table_name. The time to delete a record is exactly proportional to the number of indexes. To delete records more quickly, you can increase the size of the index cache.
mysql_fetch_array — Fetch a result row as an associative ARRAY, a numeric array, or both
mysql_fetch_object — Fetch a result row as an OBJECT.
MyISAM : This is default. Based on Indexed Sequntial Access Method. The above SQL will create a MyISA table.
ISAM : same
HEAP : Fast data access, but will loose data if there is a crash. Cannot have BLOB, TEXT & AUTO INCRIMENT fields
BDB : Supports Transactions using COMMIT & ROLLBACK. Slower that others.
InoDB : same as BDB
A primary key is a single column or multiple columns defined to have unique values that can be used as row identifications.
A foreign key is a single column or multiple columns defined to have values that can be mapped to a primary key in another table.
An index is a single column or multiple columns defined to have values pre-sorted to speed up data retrieval speed.
Join is data retrieval operation that combines rows from multiple tables under certain matching conditions to form a single row.
Join is data retrieval operation that combines multiple query outputs of the same structure into a single output. By default the MySQL UNION removes all duplicate rows from the result set even if you don’t explicit using DISTINCT after the keyword UNION.
SELECT customerNumber id, contactLastname name FROM customers UNION
SELECT employeeNurrber id, firstname name FROM employees
ISAM (Indexed Sequential Access Method) was developed by IBM to store and retrieve data on secondary storage systems like tapes.
lnnoDB is a transaction safe storage engine developed by Innobase Oy (an Oracle company now).
BDB (BerkeleyDB) is transaction safe storage engine originally developed at U.C. Berkeley. It is now developed by Sleepycat Software, Inc. (an Oracle company now).
CSV (Comma Separated Values) is a file format used to store database table contents, where one table row is stored as one line in the file, and each data field is separated with comma.
A transaction is a logical unit of work requested by a user to be applied to the database objects. MySQL server introduces the transaction concept to allow users to group one or more SQL statements into a single transaction, so that the effects of all the SQL statements in a transaction can be either all committed (applied to the database) or all rolled back (undone from the database).
Commit is a way to terminate a transaction with all database changes to be saved permanently to the database server.
Rollback is a way to terminate a transaction with all database changes not saving to the database server.
MySQL support 3 groups of data types as listed below:
String Data Types - CHAR, NCHAR, VARCHAR, NVARCHAR, BINARY, VARBINARY, TINYBLOB, TINYTEXT, BLOB, TEXT, MEDIUMBLOB, MEDIUMTEXT, LONGBLOB, LONGTEXT, ENUM, SET.
Numeric Data Types - BIT, TINYINT, BOOLEAN, SMALLINT, MEDIUMINT, INTEGER, BIGINT, FLOAT, DOUBLE, REAL, DECIMAL.
Date and Time Data Types - DATE, DATETIME, TIMESTAMP, TIME, YEAR.
Both CHAR and NCHAR are fixed length string data types. But they have the following differences:
There are a number of special characters that needs to be escaped (protected), if you want to include them in a character string. Here are some basic character escaping rules:
If you want concatenate multiple character strings into one, you need to use the CONCAT() function. Here are some good examples:
SELECT CONCAT(’Welcome’,’ to’) FROM DUAL; Welcome to SELECT CONCAT(wj’,’center’,’.com’) FROM DUAL; wisdomjobs.com
If you want to enter characters as HEX numbers, you can quote HEX numbers with single quotes and a prefix of (X), or just prefix HEX numbers with (Ox). A HEX number string will be automatically converted into a character string, if the expression context is a string. Here are some good examples:
SELECT X313233’ FROM DUAL; 123 SELECT 0x414243 FROM DUAL; ABC
If you want to enter Boolean values in SQL statements, you use (TRUE), (FALSE), (true), or (false). Here are some good examples:
SELECT TRUE, true, FALSE, false FROM DUAL;
You can convert numeric values to character strings by using the CAST(value AS CHAR) function as shown in the following examples:
SELECT CAST(4123.45700 AS CHAR) FROM DUAL; 4123.45700
SELECT CAST(4.12345700E+3 AS CHAR) FROM DUAL;
SELECT CAST(1/3 AS CHAR);
An IN condition is single value again a list of values. It returns TRUE, if the specified value is in the list. Otherwise, it returns FALSE. Some examples are :
SELECT 3 IN (1,2,3,4,5) FROM DUAL; 1 SELECT 3 NOT IN (1,2,3,4,5) FROM DUAL; 0 SELECT Y’ IN (‘F’,’Y’,I) FROM DUAL; 1
A LIKE condition is also called pattern patch. There are 3 main rules on using LIKE condition:
If you want show an article was posted “n hours n minutes and n seconds ago’, you can use the TIMEDIFF(NOWO, pastTime) function as shown in the following are:
SELECT TIMEDIFF(NOWO, ‘2006-07-01 04:09:49’) FROM DUAL; 06:42:58
SELECT TIM E_FORMAT(TI M EDI FF( NOWO, ‘2006-06-30 04:09:49’), ‘%H hours, %i minutes and %s seconds ago.’) FROM DUAL; 30 hours, 45 minutes and 22 seconds ago.
ALTER TABLE tip ADD COLUMN author VARCHAR(40);
Query OK, 1 row affected (0.18 sec)
Records: 1 Duplicates: 0 Warnings: 0
ALTER TABLE tip DROP COLUMN create_date;
Query OK, 1 row affected (0.48 sec)
Records: 1 Duplicates: 0 Warnings: 0
ALTER TABLE tip CHANGE COLUMN subject title VARCHAR(60);
ALTER TABLE tip RENAME TO faq;
If you have a table with a lots of rows, and you know that one of the columns will be used often as a search criteria, you can add an index for that column to improve the search performance. To add an index, you can use the “CREATE INDEX” statement as shown in the following script:
<pre>mysql> CREATE TABLE tip (id INTEGER PRIMARY KEY, subject VARCHAR(80) NOT NULL, description VARCHAR(256) NOT NULL, create_date DATE NULL); Query OK, 0 rows affected (0.08 sec)</pre>
mysql> CREATE INDEX tip_subject ON tip(subject); Query OK, 0 rows affected (0.19 sec) Records: 0 Duplicates: 0 Warnings: 0
If you want to see the index you have just created for an existing table, you can use the “SHOW INDEX FROM tableName” command to get a list of all indexes in a given table.
If you don’t need an existing index any more, you should delete it with the “DROP INDEX indexName ON tableName” statement. Here is an example SQL script :
mysqi> DROP INDEX tip_subject ON tip; Query OK, 0 rows affected (0.13 sec) Records: 0 Duplicates: 0 Warnings: 0
If you have an existing view, and you dont want it anymore, you can delete it by using the “DROP VIEW viewName” statement
You can create a new view based on one or more existing tables by using the
“CREATE VIEW viewName AS selectStatement” .
If you have a date, and you want to increment it by 1 day, you can use the DATE_ADD(date, INTERVAL 1 DAY) function. You can also use the date interval add operation as “date + INTERVAL 1 DAY.