MySQL: Some Questions & Answers

  • Explain MySQL architecture

The front layer takes care of network connections and security authentications, the middle layer does the SQL query parsing, and then the query is handled off to the storage engine. A storage engine could be either a default one supplied with MySQL (MyISAM) or a commercial one supplied by a third-party vendor (ScaleDB, InnoDB, etc.)

  • Explain MySQL locks

Table-level locks allow the user to lock the entire table, page-level locks allow locking of certain portions of the tables (those portions are referred to as tables), row-level locks are the most granular and allow locking of specific rows.

  • Explain multi-version concurrency control in MySQL.

Each row has two additional columns associated with it – creation time and deletion time, but instead of storing timestamps, MySQL stores version numbers.

  • What are MySQL transactions? 

A set of instructions/queries that should be executed or rolled back as a single atomic unit.

  • What’s ACID? 

Automicity – transactions are atomic and should be treated as one in case of rollback. Consistency – the database should be in consistent state between multiple states in transaction. Isolation – no other queries can access the data modified by a running transaction. Durability – system crashes should not lose the data.

  • Which storage engines support transactions in MySQL?

Berkeley DB and InnoDB.

  • How do you convert to a different table type? 

ALTER TABLE customers TYPE = InnoDB

  • How do you index just the first four bytes of the column? 

ALTER TABLE customers ADD INDEX (business_name(4))

  • What’s the difference between PRIMARY KEY and UNIQUE in MyISAM? 

PRIMARY KEY cannot be null, so essentially PRIMARY KEY is equivalent to UNIQUE NOT NULL.

  • How do you prevent MySQL from caching a query? 

SELECT SQL_NO_CACHE …

  • What’s the difference between query_cache_type 1 and 2? 

The second one is on-demand and can be retrieved via SELECT SQL_CACHE … If you’re worried about the SQL portability to other servers, you can use SELECT /* SQL_CACHE */ id FROM … – MySQL will interpret the code inside comments, while other servers will ignore it.

  • How do you start and stop MySQL on Windows? 

net start MySQL, net stop MySQL

  • How do you start MySQL on Linux? 

/etc/init.d/mysql start

  • Explain the difference between mysql and mysqli interfaces in PHP? 

mysqli is the object-oriented version of mysql library functions.

  • What’s the default port for MySQL Server? 

3306

  • What does tee command do in MySQL? 

tee followed by a filename turns on MySQL logging to a specified file. It can be stopped by command notee.

  • Can you save your connection settings to a conf file? 

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.

  • How do you change a password for an existing user via mysqladmin? 

mysqladmin -u root -p password “newpassword”

  • Use mysqldump to create a copy of the database? 

mysqldump -h mysqlhost -u username -p mydatabasename > dbdump.sql

  • Have you ever used MySQL Administrator and MySQL Query Browser? Describe the tasks you accomplished with these tools.
  • What are some good ideas regarding user security in MySQL? 

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.

  • Explain the difference between MyISAM Static and MyISAM Dynamic

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.

  • What does myisamchk do? 

It compressed the MyISAM tables, which reduces their disk usage.

  • Explain advantages of InnoDB over MyISAM? 

Row-level locking, transactions, foreign key constraints and crash recovery.

  • Explain advantages of MyISAM over InnoDB? 

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. The COUNT(*)s execute slower than in MyISAM due to tablespace complexity.

  • What are HEAP tables in MySQL? 

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.

  • How do you control the max size of a HEAP table? 

MySQL config variable max_heap_table_size.

  • What are CSV tables? 

Those are the special tables, data for which is saved into comma-separated values files. They cannot be indexed.

  • Explain federated tables

Introduced in MySQL 5.0, federated tables allow access to the tables located on other databases on other servers.

  • What is SERIAL data type in MySQL? 

BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT

  • What happens when the column is set to AUTO INCREMENT and you reach the maximum value for that table? 

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.

  • Explain the difference between BOOL, TINYINT and BIT

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.

  • Explain the difference between FLOAT, DOUBLE and REAL

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.

  • If you specify the data type as DECIMAL (5,2), what’s the range of values that can go in this table?

– 999.99 to -99.99. Note that with the negative number the minus sign is considered one of the digits.

  • What happens if a table has one column defined as TIMESTAMP?

That field gets the current timestamp whenever the row gets altered.

  • But what if you really want to store the timestamp data, such as the publication date of the article? 

Create two columns of type TIMESTAMP and use the second one for your real data.

  • Explain data type TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP 

The column exhibits the same behavior as a single timestamp column in a table with no other timestamp columns.

  • What does TIMESTAMP ON UPDATE CURRENT_TIMESTAMP data type do? 

On initialization places a zero in that column, on future updates puts the current value of the timestamp in.

  • Explain TIMESTAMP DEFAULT ‘2006:09:02 17:38:44′ ON UPDATE CURRENT_TIMESTAMP

A default value is used on initialization, a current timestamp is inserted on update of the row.

  • If I created a column with data type VARCHAR(3), what would I expect to see in MySQL table? 

CHAR(3), since MySQL automatically adjusted the data type.

  • What is DDL, DML and DCL? 

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.

  • How do you get the number of rows affected by query? 

SELECT COUNT (user_id) FROM users would only return the number of user_id’s.

  • If the value in the column is repeatable, how do you find out the unique values? 

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;

  • How do you return the a hundred books starting from 25th? 

SELECT book_title FROM books LIMIT 25, 100. The first number in LIMIT is the offset, the second is the number.

  • You wrote a search engine that should retrieve 10 results at a time, but at the same time you’d like to know how many rows there’re total. How do you display that to the user? 

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.

  • How would you write a query to select all teams that won either 2, 4, 6 or 8 games? 

SELECT team_name FROM teams WHERE team_won IN (2, 4, 6, 8);

  • How would you select all the users, whose phone number is null? 

SELECT user_name FROM users WHERE ISNULL(user_phonenumber);

  • What does this query mean: SELECT user_name, user_isp FROM users LEFT JOIN isps USING (user_id) 

It’s equivalent to saying SELECT user_name, user_isp FROM users LEFT JOIN isps WHERE users.user_id=isps.user_id.

  • How do you find out which auto increment was assigned on the last insert? 

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.

  • What does –i-am-a-dummy flag to do when starting MySQL? 

Makes the MySQL  engine refuse UPDATE and DELETE commands where the WHERE clause is not present.

  • On executing the DELETE statement I keep getting the error about foreign key constraint failing. What do I do? 

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 would you use ORDER BY in DELETE statement? 

When you’re not deleting by row ID. Such as in DELETE FROM int_questions ORDER BY timestamp LIMIT 1. This will delete the most recently posted question in the table int_questions.

  • How can you see all indexes defined for a table? 

SHOW INDEX FROM int_questions;

  • How would you change a column from VARCHAR(10) to VARCHAR(50)? 

ALTER TABLE int_questions CHANGE int_content int_CONTENT VARCHAR(50).

  • How would you delete a column? 

ALTER TABLE int_answers DROP answer_id.

  • How would you change a table to InnoDB? 

ALTER TABLE int_questions ENGINE innodb;

  • When you create a table, and then run SHOW CREATE TABLE on it, you occasionally get different results than what you typed in. What does MySQL modify in your newly created tables? 

VARCHARs with length less than 4 become CHARs

CHARs with length more than 3 become VARCHARs.

NOT NULL gets added to the columns declared as PRIMARY KEYs

Default values such as NULL are specified for each column

  • How do I find out all databases starting with ‘int’ to which I have access to? 

SHOW DATABASES LIKE ‘int%’;

  • How do you concatenate strings in MySQL? 

CONCAT (string1, string2, string3)

  • How do you get a portion of a string? 

SELECT SUBSTR(title, 1, 10) from int_questions;

  • What’s the difference between CHAR_LENGTH and LENGTH? 

The first is, naturally, the character count. The second is byte count. For the Latin characters the numbers are the same, but they are not the same for Unicode and other encodings.

  • How do you convert a string to UTF-8? 

SELECT (int_questions USING utf8);

  • What do % and _ mean inside LIKE statement? 

% corresponds to 0 or more characters, _ is exactly one character.

  • What does + mean in REGEXP? 

At least one character.

  • How do you get the month from a timestamp? 

SELECT MONTH(int_timestamp) from int_questions;

  • How do you offload the time/date handling to MySQL? 

SELECT DATE_FORMAT(int_timestamp, ‘%Y-%m-%d’) from int_questions; A similar TIME_FORMAT function deals with time.

  • How do you add three minutes to a date? 

ADDDATE(int_publication_date, INTERVAL 3 MINUTE)

  • What’s the difference between Unix timestamps and MySQL timestamps? 

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.

  • How do you convert between Unix timestamps and MySQL timestamps? 

UNIX_TIMESTAMP converts from MySQL timestamp to Unix timestamp, FROM_UNIXTIME converts from Unix timestamp to MySQL timestamp.

  • What are ENUMs used for in MySQL? 

You can limit the possible values that go into the table. CREATE TABLE months (month ENUM ‘January’, ‘February’, ‘March’,…); INSERT months VALUES (’April’);

  • How are ENUMs and SETs represented internally? 

As unique integers representing the powers of two, due to storage optimizations.

  • What is a correlated subquery?

If a subquery involves a table that also appears in the outer SELECT statement, it is known as correlated subquery. 

  • How SQL errors are handled in Stored Procedures?

There is an elegant way of handling errors and exceptions: the handler. There are two types of handler supported by MySQL – EXIT handlers that immediately exit the current BEGIN/END block, and CONTINUE handlers that allow processing to continue after the handler actions have been performed.

MySQL programs have access to several types of error information when the server returns an error. For example, the mysql client program displays errors using the following format:

 shell> SELECT * FROM no_such_table;

ERROR 1146 (42S02): Table ‘test.no_such_table’ doesn’t exist

The message displayed contains three types of information:   

  1. A numeric error value (1146). This number is MySQL-specific and is not portable to other database systems.

  2. A five-character SQLSTATE value (’42S02′). The values are specified by ANSI SQL and ODBC and are more standardized. Not all MySQL error numbers are mapped to SQLSTATE error codes. The value ‘HY000’ (general error) is used for unmapped errors.
  3. A string that provides a textual description of the error.

  • Explain LEFT JOIN, RIGHT JOIN, INNER JOIN and OUTER JOIN.

LEFT OUTER JOIN – This returns all the matching rows and the unmatched rows of the left table of the SQL code.

RIGHT OUTER JOIN – This returns all the matching rows and the unmatched rows of the right table of the SQL.

LEFT OUTER JOIN is equivalent to LEFT JOIN. RIGHT OUTER JOIN is equivalent to RIGHT JOIN.

Advertisements

One thought on “MySQL: Some Questions & Answers

  1. Sridhar

    Hi John,

    Must tell you, its a complete reference for mysql 5.0 over older versions.

    Good collection.

    John, would u be interested in joining and contributing to OpenIndx project? PLease check out my blog for further details.

    Cheers
    Shri

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s