MySQL performance tuning, stored procedure knowledge.
Performance Tuning 1. Server Status/Load # mysqladmin -u root -p status Enter password: Uptime: 80460 Threads: 2 Questions: 50 Slow queries: 0 Opens: 19 Flush tables: 1 Open tables: 12 Queries per second avg: 0.0 Uptime - The number of seconds the MySQL server has been running. Threads - The number of active threads (clients). Questions - The number of questions (queries) from clients since the server was started. Slow queries - The number of queries that have taken more than long_query_time seconds. Opens - The number of tables the server has opened. Flush tables - The number of flush-*, refresh, and reload commands the server has executed. Open tables - The number of tables that currently are open. uptime, queries processed, load 2. Tune Memory --> max simultanious client connections, table cache, size of InnoDB buffer pool, log file size. 3. Tune Query Cache --> querry_cache_type, size, limit Optimize querry --myISAM index caching and warnings
MySQL: MySQL Interview Questions and Answers.
mysqladmin is a command-line utility the comes with MySQL server and it is used by Database
Administrators to perform some basic MySQL tasks easily such as setting root password,
changing root password, monitoring mysql processes, reloading privileges, checking server status
etc.
You must have MySQL server installed on your system to perform these tasks.
20 MySQL (Mysqladmin) Commands for Database Administration in Linux
Find mySQL databse size
# ls /var/lib/mysql/ -lh | grep total
total 21M
# du -sh /var/lib/mysql/*
1. How to set MySQL Root password?
If you have fresh installation of MySQL server, then it doesn’t required any password to connect
it as root user. To set MySQL password for root user, use the following command.
# mysqladmin -u root password YOURNEWPASSWORD
2. How to Change MySQL Root password?
If you would like to change or update MySQL root password, then you need to type the following
command. For example, say your old password is 123456 and you want to change it with new
password say xyz123.
# mysqladmin -u root -p123456 password 'xyz123'
3. How to check MySQL Server is running?
To find out whether MySQL server is up and running, use the following command.
# mysqladmin -u root -p ping
Enter password:
mysqld is alive
4. How to Check which MySQL version I am running?
The following command shows MySQL version along with the current running status.
# mysqladmin -u root -p version
Enter password:
mysqladmin Ver 8.42 Distrib 5.1.69, for redhat-linux-gnu on i386
Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be
trademarks of their respective owners.
Server version 5.1.69-log
Protocol version 10
Connection Localhost via UNIX socket
UNIX socket /var/lib/mysql/mysql.sock
Uptime: 4 hours 24 min 40 sec
Threads: 2 Questions: 32 Slow queries: 0 Opens: 15 Flush tables: 1 Open tables: 8 Queries
per second avg: 0.2
5. How to Find out current Status of MySQL server?
To find out current status of MySQL server, use the following command. The mysqladmin
command shows the status of uptime with running threads and queries.
mysqladmin -u root -p status
Enter password:
Uptime: 27582 Threads: 2 Questions: 33 Slow queries: 0 Opens: 15 Flush tables: 1 Open
tables: 8 Queries per second avg: 0.1
6. How to check status of all MySQL Server Variable’s and value’s?
To check all the running status of MySQL server variables and values, type the following
command. The output would be similar to below.
# mysqladmin -u root -p extended-status
Enter password:
+-----------------------------------+----------+
| Variable_name | Value |
+-----------------------------------+----------+
| Aborted_clients | 0 |
| Aborted_connects | 5 |
| Binlog_cache_disk_use | 0 |
| Binlog_cache_use | 0 |
| Bytes_received | 2345 |
| Bytes_sent | 6867 |
| Com_admin_commands | 3 |
| ….. |
+-----------------------------------+----------+
7. How to see all MySQL server Variables and Values?
To see all the running variables and values of MySQL server, use the command as follows.
# mysqladmin -u root -p variables
Enter password:
+-----------------------------------------+-----------------------------------------------------
| Variable_name | Value
|-----------------------------------------+----------------------------------------------------
| auto_increment_increment | 1
| auto_increment_offset | 1
| autocommit | ON
|automatic_sp_privileges | ON
| …….
------------------------------------------+
8. How to check the entire running Process of MySQL server?
The following command will display all the running process of MySQL database queries.
mysqladmin -u root -p processlist
Enter password:
+----+-------------+-----------+----+---------+-------+-------------------------------------
| Id | User | Host | db | Command | Time | State | Info |
+----+-------------+-----------+----+---------+-------+-------------------------------------
| 12 | root | localhost | | Sleep | 13181 | | |
| 26 | root | localhost | | Query | 0 | show processlist | |
+----+-------------+-----------+----+---------+-------+-------------------------------------
9. How to create a Database in MySQL server?
To create a new database in MySQL server, use the command as shown below.
# mysqladmin -u root -p create databasename
Enter password:
# mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 30
Server version: 5.1.69-log Source distribution
Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be
trademarks of their respective owners.
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| database |
| lino |
| mysql |
| test |
| wpdb1 |
+--------------------+
9 rows in set (0.01 sec)
10. How to delete/drop a Database in MySQL server?
To delete/drop a Database in MySQL server, use the following command. You will be asked to
confirm press ‘y‘.
# mysqladmin -u root -p drop databasename
Enter password:
Dropping the database is potentially a very bad thing to do.
Any data stored in the database will be destroyed.
Do you really want to drop the 'databasename' database [y/N] y
Database "databasename" dropped
11. How to reload/refresh MySQL Privileges?
The reload command tells the server to reload the grant tables. The refresh command flushes all
tables and reopens the log files.
# mysqladmin -u root -p reload;
# mysqladmin -u root -p refresh
12. How to shutdown MySQL server Safely?
To shutdown MySQL server safely, type the following command.
mysqladmin -u root -p shutdown
Enter password:
You can also use the following commands to start/stop MySQL server.
# /etc/init.d/mysqld stop
# /etc/init.d/mysqld start
13. Some useful MySQL Flush commands
Following are some useful flush commands with their description.
flush-hosts: Flush all host information from host cache.
flush-tables: Flush all tables.
flush-threads: Flush all threads cache.
flush-logs: Flush all information logs.
flush-privileges: Reload the grant tables (same as reload).
flush-status: Clear status variables.\
# mysqladmin -u root -p flush-hosts
# mysqladmin -u root -p flush-tables
# mysqladmin -u root -p flush-threads
# mysqladmin -u root -p flush-logs
# mysqladmin -u root -p flush-privileges
# mysqladmin -u root -p flush-status
14. How to kill Sleeping MySQL Client Process?
Use the following command to identify sleeping MySQL client process.
# mysqladmin -u root -p processlist
Enter password:
+----+------+-----------+----+---------+------+-------+------------------+
| Id | User | Host | db | Command | Time | State | Info |
+----+------+-----------+----+---------+------+-------+------------------+
| 5 | root | localhost | | Sleep | 14 | | |
| 8 | root | localhost | | Query | 0 | | show processlist |
+----+------+-----------+----+---------+------+-------+------------------+
Now, run the following command with kill and process ID as shown below.
# mysqladmin -u root -p kill 5
Enter password:
+----+------+-----------+----+---------+------+-------+------------------+
| Id | User | Host | db | Command | Time | State | Info |
+----+------+-----------+----+---------+------+-------+------------------+
| 12 | root | localhost | | Query | 0 | | show processlist |
+----+------+-----------+----+---------+------+-------+------------------+
If you like to kill multiple process, then pass the process ID‘s with comma separated as shown
below.
# mysqladmin -u root -p kill 5,10
15. How to run multiple mysqladmin commands together?
If you would like to execute multiple ‘mysqladmin‘ commands together, then the command would
be like this.
# mysqladmin -u root -p processlist status version
Enter password:
+----+------+-----------+----+---------+------+-------+------------------+
| Id | User | Host | db | Command | Time | State | Info |
+----+------+-----------+----+---------+------+-------+------------------+
| 8 | root | localhost | | Query | 0 | | show processlist |
+----+------+-----------+----+---------+------+-------+------------------+
Uptime: 3801 Threads: 1 Questions: 15 Slow queries: 0 Opens: 15 Flush tables: 1 Open
tables: 8 Queries per second avg: 0.003
mysqladmin Ver 8.42 Distrib 5.5.28, for Linux on i686
Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be
trademarks of their respective owners.
Server version 5.5.28
Protocol version 10
Connection Localhost via UNIX socket
UNIX socket /var/lib/mysql/mysql.sock
Uptime: 1 hour 3 min 21 sec
Threads: 1 Questions: 15 Slow queries: 0 Opens: 15 Flush tables: 1 Open tables: 8 Queries
per second avg: 0.003
16. How to Connect remote mysql server
To connect remote MySQL server, use the -h (host) with IP Address of remote machine.
# mysqladmin -h 172.16.25.126 -u root –p
17. How to execute command on remote MySQL server
Let’s say you would like to see the status of remote MySQL server, then the command would be.
# mysqladmin -h 172.16.25.126 -u root -p status
18. How to start/stop MySQL replication on a slave server?
To start/stop MySQL replication on salve server, use the following commands.
# mysqladmin -u root -p start-slave
# mysqladmin -u root -p stop-slave
19. How to store MySQL server Debug Information to logs?
It tells the server to write debug information about locks in use, used memory and query usage
to the MySQL log file including information about event scheduler.
# mysqladmin -u root -p debug
Enter password:
20. How to view mysqladmin options and usage
To find out more options and usage of myslqadmin command use the help command as shown
below. It will display a list of available options.
# mysqladmin --help
We have tried our best to include almost all of ‘mysqladmin‘ commands with their examples in
this article, If still, we’ve missed anything, please do let us know via comments and don’t forget
to share with your friends.
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. TRhe 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.
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.
1.
How do you start and stop MySQL on Windows? – net start MySQL, net stop MySQL
2. How do you start MySQL on Linux? – /etc/init.d/mysql start
3. Explain the difference between mysql and mysqli interfaces in PHP? – mysqli is the object-
oriented version of mysql library functions.
4. What’s the default port for MySQL Server? – 3306
5. 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.
6. 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.
7. How do you change a password for an existing user via mysqladmin? – mysqladmin -u root -p
password “newpassword”
8. Use mysqldump to create a copy of the database? – mysqldump -h mysqlhost -u username -p
mydatabasename > dbdump.sql
9. Have you ever used MySQL Administrator and MySQL Query Browser? Describe the tasks
you accomplished with these tools.
10. 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.
11. 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.
12. What does myisamchk do? – It compressed the MyISAM tables, which reduces their disk usage.
13. Explain advantages of InnoDB over MyISAM? – Row-level locking, transactions, foreign key
constraints and crash recovery.
14. 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. TRhe COUNT(*)s execute slower than in
MyISAM due to tablespace complexity.
15. 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.
16. How do you control the max size of a HEAP table? – MySQL config variable
max_heap_table_size.
17. What are CSV tables? – Those are the special tables, data for which is saved into comma-
separated values files. They cannot be indexed.
18. Explain federated tables. – Introduced in MySQL 5.0, federated tables allow access to the tables
located on other databases on other servers.
19. What is SERIAL data type in MySQL? – BIGINT NOT NULL PRIMARY KEY
AUTO_INCREMENT
20. 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.
21. 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.
22. 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.
23. 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.
24. What happens if a table has one column defined as TIMESTAMP? – That field gets the current
timestamp whenever the row gets altered.
25. 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.
26. 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.
27. 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.
28. 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.
29. 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.
About these ads
1. 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.)
1. 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.
2. 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.
1. What are MySQL transactions? – A set of instructions/queries that should be executed or rolled back as a
single atomic unit.
2. 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.
3. Which storage engines support transactions in MySQL? – Berkeley DB and InnoDB.
4. How do you convert to a different table type? – ALTER TABLE customers TYPE = InnoDB
5. How do you index just the first four bytes of the column? – ALTER TABLE customers ADD INDEX
(business_name(4))
6. 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.
7. How do you prevent MySQL from caching a query? – SELECT SQL_NO_CACHE …
1.
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.
2. 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.
1. 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;
2. 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.
3. 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.
4. 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)
5. How would you select all the users, whose phone number is null? – SELECT user_name FROM users
WHERE ISNULL(user_phonenumber);
6. 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
7. 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.
8. 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.
9. 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.
10. When would you use ORDER BY in DELETE statement? – When you’re not deleting by row ID. Such as in
DELETE FROM techinterviews_com_questions ORDER BY timestamp LIMIT 1. This will delete the most
recently posted question in the table techinterviews_com_questions.
11. How can you see all indexes defined for a table? – SHOW INDEX FROM techinterviews_questions;
12. How would you change a column from VARCHAR(10) to VARCHAR(50)? – ALTER TABLE
techinterviews_questions CHANGE techinterviews_content techinterviews_CONTENT VARCHAR(50).
13. How would you delete a column? – ALTER TABLE techinterviews_answers DROP answer_user_id.
14. How would you change a table to InnoDB? – ALTER TABLE techinterviews_questions ENGINE innodb;
15. 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? -
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
16. How do I find out all databases starting with ‘tech’ to which I have access to? – SHOW DATABASES LIKE
‘tech%’;
17. How do you concatenate strings in MySQL? – CONCAT (string1, string2, string3)
18. How do you get a portion of a string? – SELECT SUBSTR(title, 1, 10) from techinterviews_questions;
19. 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’re not the
same for Unicode and other encodings.
20. How do you convert a string to UTF-8? – SELECT (techinterviews_question USING utf8);
21. What do % and _ mean inside LIKE statement? – % corresponds to 0 or more characters, _ is exactly one
character.
22. What does + mean in REGEXP? – At least one character. Appendix G. Regular Expressions from MySQL
manual is worth perusing before the interview.
23. How do you get the month from a timestamp? – SELECT MONTH(techinterviews_timestamp) from
techinterviews_questions;
24. How do you offload the time/date handling to MySQL? – SELECT
DATE_FORMAT(techinterviews_timestamp, ‘%Y-%m-%d’) from techinterviews_questions; A similar
TIME_FORMAT function deals with time.
25. How do you add three minutes to a date? – ADDDATE(techinterviews_publication_date, INTERVAL 3
MINUTE)
26. 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.
27. 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.
28. 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’);
29. How are ENUMs and SETs represented internally? - As unique integers representing the powers of two,
due to storage optimizations.
How to recover root password in MySQL? 1. As Linux system root user stop the database process: /etc/init.d/mysql stop
(or: service mysql stop)
2. Start MySQL in safe mode and skip the use of the “grant tables”: /usr/bin/mysqld_safe –user=mysql –
socket=/var/lib/mysql/mysql.sock –pid-file=/var/run/mysqld/mysqld.pid –datadir=/var/lib/mysql –skip-grant-tables –
skip-networking & 3. Reset the MySQL root password: mysqladmin -u root flush-privileges password newpassword
4. Stop MySQL running in safe mode: kill `cat /var/run/mysqld/mysqld.pid`
5. Start MySQL: /etc/init.d/mysql start
6. The new MySQL root password can now be used: mysql -u root -p
Respond withthe password: newpassword
Mysql database engine: Innodb vs Myisam
The 2 major types of table storage engines for MySQL databases are InnoDB and MyISAM. To summarize
the differences of features and performance,
1. InnoDB is newer while MyISAM is older.
2. InnoDB is more complex while MyISAM is simpler.
3. InnoDB is more strict in data integrity while MyISAM is loose.
4. InnoDB implements row-level lock for inserting and updating while MyISAM implementstable-
level lock.
5. InnoDB has transactions while MyISAM does not.
6. InnoDB has foreign keys and relationship contraints while MyISAM does not.
7. InnoDB has better crash recovery while MyISAM is poor at recovering data integrity at system
crashes.
8. MyISAM has full-text search index while InnoDB has not.
In light of these differences, InnoDB and MyISAM have their unique advantages and disadvantages against
each other. They each are more suitable in some scenarios than the other.
Advantages of InnoDB
1. InnoDB should be used where data integrity comes a priority because it inherently takes care of
them by the help of relationship constraints and transactions.
2. Faster in write-intensive (inserts, updates) tables because it utilizes row-level locking and only
hold up changes to the same row that’s being inserted or updated.
Disadvantages of InnoDB
1. Because InnoDB has to take care of the different relationships between tables, database
administrator and scheme creators have to take more time in designing the data models which are
more complex than those of MyISAM.
2. Consumes more system resources such as RAM. As a matter of fact, it is recommended by many
that InnoDB engine be turned off if there’s no substantial need for it after installation of MySQL.
3. No full-text indexing.
Advantages of MyISAM
1. Simpler to design and create, thus better for beginners. No worries about the foreign relationships
between tables.
2. Faster than InnoDB on the whole as a result of the simpler structure thus much less costs of server
resources.
3. Full-text indexing.
4. Especially good for read-intensive (select) tables.
Disadvantages of MyISAM
1. No data integrity (e.g. relationship constraints) check, which then comes a responsibility and
overhead of the database administrators and application developers.
2. Doesn’t support transactions which is essential in critical data applications such as that of
banking.
3. Slower than InnoDB for tables that are frequently being inserted to or updated, because the entire
table is locked for any insert or update.
You want to save the mysql DB “mySQLDB” to a file “mySQLDB.sql”, how can you do it? Answer: You can use the mysqldump command to dump a database –
mysqldump -u username -p mySQLDB > mySQLDB.sql
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.
1. Use mysqldump to create a copy of the database? - mysqldump -h mysqlhost -u username -p
mydatabasename > dbdump.sql
2. Have you ever used MySQL Administrator and MySQL Query Browser? Describe the tasks you
accomplished with these tools.
What are the different tables present in MySQL? MyISAM Heap Merge InnoDB ISAM show engines MyISAM is the default storage engine as of MySQL .
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. TRhe
COUNT(*)s execute slower than in MyISAM due to tablespace complexity
Question :How to import and export a mysql database using ssh.
Answer :
To export a database use:
mysqldump -u root -p db-name > backup.sql
To import a database:
mysql -u root -p db-name < backup.sql
- See more at: http://www.unixmen.com/how-to-import-and-export-a-mysql-database-using-
ssh/#sthash.hNL7AMRc.dpuf
21. 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.
Thee COUNT(*)s execute slower than in MyISAM due to tablespace complexity
22. Advantages of InnoDB over MyISAM.
Transactions
Row-level locking
Crash recovery
Foreign key constraints
23. Where MyISAM table will be stored and also give their formats of storage.
Each MyISAM table is stored on disk in three formats:-
1. The data file has a ‘.MYD’ (MYData) extension.
2. The ‘.frm’ file stores the table definition.
3. The index file has a ‘.MYI’ (MYIndex) extension.
26. Difference between mysql and mysqli interfaces in PHP.
mysqli is the object-oriented version of mysql library functions.
29. Difference between primary key and candidate key.
Every row of a table is identified uniquely by primary key. There is only one primary key for a
table.
Primary Key is also a candidate key. By common convention, candidate key can be designated as
primary and which can be used for any foreign key references.
30. What are the different table present in MYsql?
MyISAM:- This is default. Based on Indexed Sequntial Access Method. The above SQL will create
a MyISA table.
HEAP : - Fast data access, but will loose data if there is a crash. Cannot have BLOB, TEXT &
AUTO INCRIMENT fields.
ISAM :- Based on Indexed Sequntial Access Method.
InoDB :- Supports Transactions using COMMIT & ROLLBACK
BDB :- Supports Transactions using COMMIT & ROLLBACK. Slower that others.
34. How do you change a password for an existing user via mysqladmin.
mysqladmin -u root -p password “newpassword”
35. What does myisamchk do.
It compress the MyISAM tables, which reduces their disk or memory usage.
39. How to Use mysqldump to create a copy of the database.
mysqldump -h mysqlhost -u username -p mydatabasename > dbdump.sql
43. What is ISAM.
ISAM is abbreviated as Indexed Sequential Access Method.It was developed by IBM to store and
retrieve data on secondary storage systems like tapes.
44. What is InnoDB.
lnnoDB is a transaction safe storage engine developed by Innobase Oy which is a Oracle
Corporation now.
54. What is the difference between MyISAM Static and MyISAM Dynamic.
In MyISAM static all the fields will have fixed width. The Dynamic MyISAM table will have fields
like TEXT, BLOB, etc. to accommodate the data types with various lengths.
MyISAM Static would be easier to restore in case of corruption.
Phase I: Configure Master Server (192.168.1.1) for Replication
Login into MySQL as root user and create the slave user and grant privileges for replication.
Replace slave_user with user and your_password with password.
# mysql -h 192.168.2.30 -u root -p
mysql> GRANT REPLICATION SLAVE ON *.* TO 'slave_user'@'%' IDENTIFIED BY 'your_password';
mysql> FLUSH PRIVILEGES;
mysql> FLUSH TABLES WITH READ LOCK;
mysql> SHOW MASTER STATUS;
+------------------+----------+--------------+------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000003 | 11128001 | tecmint | |
+------------------+----------+--------------+------------------+
mysql> quit;
Please write down the File (mysql-bin.000003) and Position (11128001) numbers, we required these numbers later
on Slave server. Next apply READ LOCK to databases to export all the database and master database information
with mysqldump command.
# mysqldump -u root -p --all-databases --master-data > /root/dbdump.db
Once you’ve dump all the databases, now again connect to mysql as root user and unlcok tables.
mysql> UNLOCK TABLES;
mysql> quit;
Upload the database dump file on Slave Server (192.168.1.2) using SCP command.
scp /root/dbdump.db [email protected]:/root/
That’s it we have successfully configured Master server, let’s proceed to Phase II section.
Phase II: Configure Slave Server (192.168.1.2) for Replication
Open my.cnf configuration file with VI editor.
# vi /etc/my.cnf
Add the following entries under [mysqld] section and don’t forget to replace IP address ofMaster server, tecmint
with database name etc, that you would like to replicate with Master.
server-id = 2
master-host=192.168.1.1
master-connect-retry=60
master-user=slave_user
master-password=yourpassword
replicate-do-db=tecmint
relay-log = /var/lib/mysql/mysql-relay-bin
relay-log-index = /var/lib/mysql/mysql-relay-bin.index
log-error = /var/lib/mysql/mysql.err
master-info-file = /var/lib/mysql/mysql-master.info
relay-log-info-file = /var/lib/mysql/mysql-relay-log.info
log-bin = /var/lib/mysql/mysql-bin
Now import the dump file that we exported in earlier command and restart the MySQL service.
# mysql -u root -p < /root/dbdump.db
# /etc/init.d/mysqld restart
Login into MySQL as root user and stop the slave. Then tell the slave to where to look forMaster log file, that we
have write down on master with SHOW MASTER STATUS; command as File (mysql-bin.000003) and Position
(11128001) numbers. You must change192.168.1.1 to the IP address of the Master Server, and change the user and
password accordingly.
# mysql -u root –p
mysql> slave stop;
mysql> CHANGE MASTER TO MASTER_HOST='192.168.1.1', MASTER_USER='slave_user',
MASTER_PASSWORD='yourpassword', MASTER_LOG_FILE='mysql-bin.000003', MASTER_LOG_POS=11128001;
mysql> slave start;
mysql> show slave status\G