MySQL Interview Questions And Answers
1) What’s MySQL ?
Ans: 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.
2) What is DDL, DML and DCL ? Ans: 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.
3) How do you get the number of rows affected by query? Ans: SELECT COUNT (user_id) FROM users would only return the number of user_id?s.
4) If the value in the column is repeatable, how do you find out the unique values? Ans: 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;
5) How do you return the a hundred books starting from 25th? Ans: SELECT book_title FROM books LIMIT 25, 100. The first number in LIMIT is the offset, the second is the number.
6) 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? Ans: 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.
7) How would you write a query to select all teams that won either 2, 4, 6 or 8 games? Ans: SELECT team_name FROM teams WHERE team_won IN (2, 4, 6, 8)
8) How would you select all the users, whose phone number is null? Ans: SELECT user_name FROM users WHERE ISNULL(user_phonenumber);
9) What does this query mean: SELECT user_name, user_isp FROM users LEFT JOIN isps USING (user_id) ? Ans: It?s equivalent to saying SELECT user_name, user_isp FROM users LEFT JOIN isps WHERE users.user_id=isps.user_id
10) What does ?i-am-a-dummy flag to do when starting MySQL? Ans: Makes the MySQL engine refuse UPDATE and DELETE commands where the WHERE clause is not present.
11) On executing the DELETE statement I keep getting the error about foreign key constraint failing. What do I do? Ans: 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.
12) When would you use ORDER BY in DELETE statement? Ans: 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.
13) How many ways we can we find the current date using MySQL? Ans: SELECT CURDATE(); SELECT CURRENT_DATE(); SELECT CURTIME(); SELECT CURRENT_TIME();
14) Give the syntax of GRANT commands? Ans: The generic syntax for GRANT is as following GRANT [rights] on [database] TO [username@hostname] IDENTIFIED BY [password] Now rights can be: a) ALL privilages b) Combination of CREATE, DROP, SELECT, INSERT, UPDATE and DELETE etc. We can grant rights on all databse by usingh *.* or some specific database by database.* or a specific table by database.table_name
15) Give the syntax of REVOKE commands? Ans: The generic syntax for revoke is as following REVOKE [rights] on [database] FROM [username@hostname] Now rights can be: a) ALL privileges b) Combination of CREATE, DROP, SELECT, INSERT, UPDATE and DELETE etc. We can grant rights on all database by using *.* or some specific database by database.* or a specific table by database.table_name.
16) How can we encrypt and decrypt a data present in a mysql table using mysql? Ans: AES_ENCRYPT() and AES_DECRYPT()
17) How can I load data from a text file into a table? Ans: The MySQL provides a LOAD DATA INFILE command. You can load data from a file. Great tool but you need to make sure that: a) Data must be delimited b) Data fields must match table columns correctly
18) How can we know the number of days between two given dates using MySQL? Ans: Use DATEDIFF() SELECT DATEDIFF(NOW(),’2006-07-01′);
19) How can we change the name of a column of a table? Ans: This will change the name of column: ALTER TABLE table_name CHANGE old_colm_name new_colm_name
20) How can we change the data type of a column of a table? Ans: This will change the data type of a column: ALTER TABLE table_name CHANGE colm_name same_colm_name [new data type]
21) What is the difference between GROUP BY and ORDER BY in SQL? Ans: To sort a result, use an ORDER BY clause. The most general way to satisfy a GROUP BY clause is to scan the whole table and create a new temporary table where all rows from each group are consecutive, and then use this temporary table to discover groups and apply aggregate functions (if any). ORDER BY [col1],[col2],…[coln]; Tells DBMS according to what columns it should sort the result. If two rows will have the same value in col1 it will try to sort them according to col2 and so on. GROUP BY [col1],[col2],…[coln]; Tells DBMS to group (aggregate) results with same value of column col1. You can use COUNT(col1), SUM(col1), AVG(col1) with it, if you want to count all items in group, sum all values or view average.
22) What are the MySQL database files stored in system ? Ans: Data is stored in name.myd Table structure is stored in name.frm Index is stored in name.myi
23) In how many ways we can retrieve data in the result set of MYSQL using PHP? Ans: mysql_fetch_array – Fetch a result row as an associative array, a numeric array, or both mysql_fetch_assoc – Fetch a result row as an associative array mysql_fetch_object – Fetch a result row as an object mysql_fetch_row ?- Get a result row as an enumerated array
24) How do you start and stop MySQL on Windows? Ans: net start MySQL, net stop MySQL
25) How do you start MySQL on Linux? Ans: /etc/init.d/mysql start
26)Explain the difference between mysql and mysqli interfaces in PHP? Ans: mysqli is the object- oriented version of mysql library functions.
27) What’s the default port for MySQL Server? Ans: 3306
28) What does tee command do in MySQL? Ans: tee followed by a filename turns on MySQL logging to a specified file. It can be stopped by command notee.
29) Can you save your connection settings to a conf file? Ans: 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.
30) How do you change a password for an existing user via mysqladmin? Ans: mysqladmin -u root -p password “newpassword”
31) Use mysqldump to create a copy of the database? Ans: mysqldump -h mysqlhost -u username -p mydatabasename > dbdump.sql
32) What are some good ideas regarding user security in MySQL? – Ans: 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.
33) Explain the difference between MyISAM Static and MyISAM Dynamic. Ans: 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.
34) What does myisamchk do? Ans: It compressed the MyISAM tables, which reduces their disk usage.
35) Explain advantages of InnoDB over MyISAM? Ans: Row-level locking, transactions, foreign key constraints and crash recovery.
36) Explain advantages of MyISAM over InnoDB? Ans: 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.
37) What are HEAP tables in MySQL? Ans: 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.
38) How do you control the max size of a HEAP table? Ans: MySQL config variable max_heap_table_size.
39) What are CSV tables? Ans: Those are the special tables, data for which is saved into comma-separated values files. They cannot be indexed.
40) Explain federated tables. Ans: Introduced in MySQL 5.0, federated tables allow access to the tables located on other databases on other servers.
41) What is SERIAL data type in MySQL? Ans: BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT
42: What happens when the column is set to AUTO INCREMENT and you reach the maximum value for that table? Ans: 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.
2) What is DDL, DML and DCL ? Ans: 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.
3) How do you get the number of rows affected by query? Ans: SELECT COUNT (user_id) FROM users would only return the number of user_id?s.
4) If the value in the column is repeatable, how do you find out the unique values? Ans: 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;
5) How do you return the a hundred books starting from 25th? Ans: SELECT book_title FROM books LIMIT 25, 100. The first number in LIMIT is the offset, the second is the number.
6) 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? Ans: 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.
7) How would you write a query to select all teams that won either 2, 4, 6 or 8 games? Ans: SELECT team_name FROM teams WHERE team_won IN (2, 4, 6, 8)
8) How would you select all the users, whose phone number is null? Ans: SELECT user_name FROM users WHERE ISNULL(user_phonenumber);
9) What does this query mean: SELECT user_name, user_isp FROM users LEFT JOIN isps USING (user_id) ? Ans: It?s equivalent to saying SELECT user_name, user_isp FROM users LEFT JOIN isps WHERE users.user_id=isps.user_id
10) What does ?i-am-a-dummy flag to do when starting MySQL? Ans: Makes the MySQL engine refuse UPDATE and DELETE commands where the WHERE clause is not present.
11) On executing the DELETE statement I keep getting the error about foreign key constraint failing. What do I do? Ans: 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.
12) When would you use ORDER BY in DELETE statement? Ans: 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.
13) How many ways we can we find the current date using MySQL? Ans: SELECT CURDATE(); SELECT CURRENT_DATE(); SELECT CURTIME(); SELECT CURRENT_TIME();
14) Give the syntax of GRANT commands? Ans: The generic syntax for GRANT is as following GRANT [rights] on [database] TO [username@hostname] IDENTIFIED BY [password] Now rights can be: a) ALL privilages b) Combination of CREATE, DROP, SELECT, INSERT, UPDATE and DELETE etc. We can grant rights on all databse by usingh *.* or some specific database by database.* or a specific table by database.table_name
15) Give the syntax of REVOKE commands? Ans: The generic syntax for revoke is as following REVOKE [rights] on [database] FROM [username@hostname] Now rights can be: a) ALL privileges b) Combination of CREATE, DROP, SELECT, INSERT, UPDATE and DELETE etc. We can grant rights on all database by using *.* or some specific database by database.* or a specific table by database.table_name.
16) How can we encrypt and decrypt a data present in a mysql table using mysql? Ans: AES_ENCRYPT() and AES_DECRYPT()
17) How can I load data from a text file into a table? Ans: The MySQL provides a LOAD DATA INFILE command. You can load data from a file. Great tool but you need to make sure that: a) Data must be delimited b) Data fields must match table columns correctly
18) How can we know the number of days between two given dates using MySQL? Ans: Use DATEDIFF() SELECT DATEDIFF(NOW(),’2006-07-01′);
19) How can we change the name of a column of a table? Ans: This will change the name of column: ALTER TABLE table_name CHANGE old_colm_name new_colm_name
20) How can we change the data type of a column of a table? Ans: This will change the data type of a column: ALTER TABLE table_name CHANGE colm_name same_colm_name [new data type]
21) What is the difference between GROUP BY and ORDER BY in SQL? Ans: To sort a result, use an ORDER BY clause. The most general way to satisfy a GROUP BY clause is to scan the whole table and create a new temporary table where all rows from each group are consecutive, and then use this temporary table to discover groups and apply aggregate functions (if any). ORDER BY [col1],[col2],…[coln]; Tells DBMS according to what columns it should sort the result. If two rows will have the same value in col1 it will try to sort them according to col2 and so on. GROUP BY [col1],[col2],…[coln]; Tells DBMS to group (aggregate) results with same value of column col1. You can use COUNT(col1), SUM(col1), AVG(col1) with it, if you want to count all items in group, sum all values or view average.
22) What are the MySQL database files stored in system ? Ans: Data is stored in name.myd Table structure is stored in name.frm Index is stored in name.myi
23) In how many ways we can retrieve data in the result set of MYSQL using PHP? Ans: mysql_fetch_array – Fetch a result row as an associative array, a numeric array, or both mysql_fetch_assoc – Fetch a result row as an associative array mysql_fetch_object – Fetch a result row as an object mysql_fetch_row ?- Get a result row as an enumerated array
24) How do you start and stop MySQL on Windows? Ans: net start MySQL, net stop MySQL
25) How do you start MySQL on Linux? Ans: /etc/init.d/mysql start
26)Explain the difference between mysql and mysqli interfaces in PHP? Ans: mysqli is the object- oriented version of mysql library functions.
27) What’s the default port for MySQL Server? Ans: 3306
28) What does tee command do in MySQL? Ans: tee followed by a filename turns on MySQL logging to a specified file. It can be stopped by command notee.
29) Can you save your connection settings to a conf file? Ans: 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.
30) How do you change a password for an existing user via mysqladmin? Ans: mysqladmin -u root -p password “newpassword”
31) Use mysqldump to create a copy of the database? Ans: mysqldump -h mysqlhost -u username -p mydatabasename > dbdump.sql
32) What are some good ideas regarding user security in MySQL? – Ans: 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.
33) Explain the difference between MyISAM Static and MyISAM Dynamic. Ans: 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.
34) What does myisamchk do? Ans: It compressed the MyISAM tables, which reduces their disk usage.
35) Explain advantages of InnoDB over MyISAM? Ans: Row-level locking, transactions, foreign key constraints and crash recovery.
36) Explain advantages of MyISAM over InnoDB? Ans: 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.
37) What are HEAP tables in MySQL? Ans: 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.
38) How do you control the max size of a HEAP table? Ans: MySQL config variable max_heap_table_size.
39) What are CSV tables? Ans: Those are the special tables, data for which is saved into comma-separated values files. They cannot be indexed.
40) Explain federated tables. Ans: Introduced in MySQL 5.0, federated tables allow access to the tables located on other databases on other servers.
41) What is SERIAL data type in MySQL? Ans: BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT
42: What happens when the column is set to AUTO INCREMENT and you reach the maximum value for that table? Ans: 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.
Arun Gandham
Author
Hola peeps! A fitness freak, a lover of games, I catch a flick on the weekends and write for you about current trends.