Anda di halaman 1dari 9

MySQL Interview Questions

1. How do you start and stop MySQL on Windows?


1. net start MySQL, net stop MySQL
2. How do you start MySQL on Linux?
1. /etc/init.d/mysql start
3. Explain the difference between mysql and mysqli interfaces in PHP?
1. mysqli is the object-oriented version of mysql library functions.
4. Whats the default port for MySQL Server?
1. 3306
5. What does tee command do in MySQL?
1. 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?
1. Yes, and name it ~/.my.conf. You might want to change the permissions on the file
to 600, so that its not readable by others.
7. How do you change a password for an existing user via mysqladmin?
1. mysqladmin -u root -p password newpassword
8. Use mysqldump to create a copy of the database?
1. mysqldump -h mysqlhost -u username -p mydatabasename > dbdump.sql
9. What are some good ideas regarding user security in MySQL?
1. 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.
10. Explain the difference between MyISAM Static and MyISAM Dynamic.
1. 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.
11. What does myisamchk do?
1. It compressed the MyISAM tables, which reduces their disk usage.
12. Explain advantages of InnoDB over MyISAM?
1. Row-level locking, transactions, foreign key constraints and crash recovery.
13. Explain advantages of MyISAM over InnoDB?
1. 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.
14. What are HEAP tables in MySQL?
1. 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.
15. How do you control the max size of a HEAP table?
1. MySQL config variable max_heap_table_size.
16. What are CSV tables?
1. Those are the special tables, data for which is saved into comma-separated values
files. They cannot be indexed.
17. Explain federated tables.
1. Introduced in MySQL 5.0, federated tables allow access to the tables located on
other databases on other servers.
18. What is SERIAL data type in MySQL?
1. BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT
19. What happens when the column is set to AUTO INCREMENT and you reach the
maximum value for that table?
1. 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.
20. Explain the difference between BOOL, TINYINT and BIT.
1. 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.
21. Explain the difference between FLOAT, DOUBLE and REAL.
1. 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.
22. If you specify the data type as DECIMAL (5,2), whats the range of values that
can go in this table?
1. 999.99 to -99.99. Note that with the negative number the minus sign is considered
one of the digits.
23. What happens if a table has one column defined as TIMESTAMP?
1. That field gets the current timestamp whenever the row gets altered.
24. But what if you really want to store the timestamp data, such as the publication
date of the article?
1. Create two columns of type TIMESTAMP and use the second one for your real data.
25. Explain MySQL architecture.
1. 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.)
26. Explain MySQL locks.
1. 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.
27. Explain multi-version concurrency control in MySQL.
1. Each row has two additional columns associated with it - creation time and deletion
time, but instead of storing timestamps, MySQL stores version numbers.

28. What are MySQL transactions?


1. A set of instructions/queries that should be executed or rolled back as a single
atomic unit.
29. Whats ACID?
1. 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.
30. Which storage engines support transactions in MySQL?
1. Berkeley DB and InnoDB.
31. How do you convert to a different table type?
1. ALTER TABLE customers TYPE = InnoDB
32. How do you index just the first four bytes of the column?
1. ALTER TABLE customers ADD INDEX (business_name(4))
33. Whats the difference between PRIMARY KEY and UNIQUE in MyISAM?
1. PRIMARY KEY cannot be null, so essentially PRIMARY KEY is equivalent to UNIQUE
NOT NULL.
34. How do you prevent MySQL from caching a query?
1. SELECT SQL_NO_CACHE
35. What is DDL, DML and DCL?
1. 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.
36. How do you get the number of rows affected by query?
1. SELECT COUNT (user_id) FROM users; would return the number of user_ids.
37. If the value in the column is repeatable, how do you find out the unique values?
1. 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;
38. You wrote a search engine that should retrieve 10 results at a time, but at the
same time youd like to know how many rows therere total. How do you display
that to the user?
1. 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 therere 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.
39. How do you find out which auto increment was assigned on the last insert?
1. SELECT LAST_INSERT_ID() will return the last value assigned by the
auto_increment function. Note that you dont have to specify the table name.
40. Is it possible to delete duplicate rows in a table without using a temporary table
(i.e., just do it with a single SQL statement)?

1. All you need to do is compare the table to itself to find out which candidates are
duplicates. Do this by assigning aliases to the table so you can use it twice, once as
A and again as B, like this: delete from jobs where job_desc in (select a.job_desc
from jobs a, jobs b where a.job_desc = b.job_desc group by a.job_desc having
count(a.job_desc) >1);
41. Explain ACID rule of thumb for transactions?
1. Transaction must be: Atomic - it is one unit of work and does not dependent on
previous and following transactions.
2. Consistent - data is either committed or roll back, no in-between case where
something has been updated and something hasnt.
3. Isolated - no transaction sees the intermediate results of the current transaction.
4. Durable - the values persist if the data had been committed even if the system
crashes right after.
42. On executing the DELETE statement I keep getting the error about foreign key
constraint failing. What do I do?
1. What it means is that so of the data that youre 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.
43. When would you use ORDER BY in DELETE statement?
1. When youre 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.
44. How can you see all indexes defined for a table?
1. SHOW INDEX FROM techinterviews_questions;
45. How would you change a table to InnoDB?
1. ALTER TABLE techinterviews_questions ENGINE innodb;
46. 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. 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.
47. How do you get a portion of a string?
1. SELECT SUBSTR(title, 1, 10) from techinterviews_questions;
48. Whats the difference between CHAR_LENGTH and LENGTH?
1. The first is, naturally, the character count. The second is byte count. For the Latin
characters the numbers are the same, but theyre not the same for Unicode and
other encodings.
49. How do you get the month from a timestamp?
1. SELECT MONTH(techinterviews_timestamp) from techinterviews_questions;
50. How do you offload the time/date handling to MySQL?
1. SELECT DATE_FORMAT(techinterviews_timestamp, %Y-%m-%d) from
techinterviews_questions; A similar TIME_FORMAT function deals with time.
51. How do you add three minutes to a date?

1. ADDDATE(techinterviews_publication_date, INTERVAL 3 MINUTE);


52. What are CLUSTERS?
1. A CLUSTER is a means of storing together data from multiple tables, when the data
in those tables contains information and is likely to be accessed concurrently.
53. What are the different types of SQL commands ?
1. DDL ( Data definition language ), DML ( Data manipulation language ), TCL
( Transact control language), Session Control Statements. ( ALTER SESSION,
ROLE ), System Control Statements ( ALTER SYSTEM ).
54. What
1.
2.
3.

is difference between Count and Count(*)?


The Difference between Count and Count(*)
Count: Counts the number of non-null values.
Count(*): Counts the number of rows in the table, including null values and
duplicates.

55. What is an Index?


1. When queries are run against a db, an index on that db basically helps in the way
the data is sorted to process the query for faster and data retrievals are much
faster when we have an index.
56. Whats the difference between a primary key and a unique key?
1. Both primary key and unique enforce uniqueness of the column on which they are
defined. But by default primary key creates a clustered index on the column, where
are unique creates a nonclustered index by default. Another major difference is
that, primary key doesnt allow NULLs, but unique key allows one NULL only.
57. What is the difference among dropping a table, truncating a table and
deleting all records from a table?
1. Dropping: (Table structure + Data are deleted), Invalidates the dependent objects,
Drops the indexes. Truncating: (Data alone deleted), Performs an automatic
commit, faster than delete. Delete: (Data alone deleted), doesnt perform
automatic commit.
58. What is the difference between TRUNCATE and DELETE commands?
1. TRUNCATE is a DDL command whereas DELETE is a DML command. Hence DELETE
operation can be rolled back, but TRUNCATE operation cannot be rolled back.
WHERE clause can be used with DELETE and not with TRUNCATE.
59. What does the following query do?
1. SELECT SAL + NVL(COMM,0) FROM EMP;This displays the total salary of all
employees. The null values in the commission column will be replaced by 0 and
added to salary.
60. What command is used to create a table by copying the structure of another
table?
1. CREATE TABLE .. AS SELECT command
2. Explanation : To copy only the structure, the WHERE clause of the SELECT
command should contain a FALSE statement as in the following.CREATE TABLE
NEWTABLE AS SELECT * FROM EXISTINGTABLE WHERE 1=2;
3. If the WHERE condition is true, then all the rows or rows satisfying the condition
will be copied to the new table.
61. What is the purpose of the following files having extensions: frm, myd, and myi?
1. In MySQL, the default table type is MyISAM. Each MyISAM table is stored on disk in
three files. The files have names that begin with the table name and have an
extension to indicate the file type. The '.frm' file stores the table definition. The
data file has a '.MYD' (MYData) extension. The index file has a '.MYI' (MYIndex)
extension.

PHP Interview Questions


What is the difference between interface and abstract class?
Interface contains methods that must be abstract; abstract class may contain concrete methods.
Interface contains variables that must be static and final; abstract class may contain non-final
and final variables.
Members in an interface are public by default; abstract class may contain non-public members.
Interface is used to "implements"; whereas abstract class is used to "extends".
Interface can be used to achieve multiple inheritance; abstract class can be used as a single
inheritance.
Interface can "extends" another interface, abstract class can "extends" another class and
"implements" multiple interfaces.
Interface is absolutely abstract; abstract class can be invoked if a main() exists.
Interface is more flexible than abstract class because one class can only "extends" one super
class, but "implements" multiple interfaces.
If given a choice, use interface instead of abstract class.
What is difference between overloading and overriding?
a) In overloading, there is a relationship between methods available in the same class whereas in
overriding, there is relationship between a superclass method and subclass method.
b) Overloading does not block inheritance from the superclass whereas overriding blocks
inheritance from the superclass.
c) In overloading, separate methods share the same name whereas in overriding, subclass
method replaces the superclass.
d) Overloading must have different method signatures whereas overriding must have same
signature.
How many ways can an argument be passed to a subroutine?
An argument can be passed in two ways. They are Pass by Value and Passing by Reference.
Passing by value: This method copies the value of an argument into the formal parameter of the
subroutine.
Passing by reference: In this method, a reference to an argument (not the value of the
argument) is passed to the parameter.
What is the difference between procedural and object-oriented programs?
1. In procedural program, programming logic follows certain procedures and the instructions are
executed one after another. In OOP program, unit of program is object, which is nothing but
combination of data and code.
2. In procedural program, data is exposed to the whole program whereas in OOPs program, it is
accessible with in the object and which in turn assures the security of the code.
Can a method be overloaded based on different return type but same argument type ?
No, because the methods can be called without using their return type in which case there is
ambiquity for the compiler.
What is Downcasting ?
Downcasting is the casting from a general to a more specific type, i.e. casting down the
hierarchy.
Differentiate persistent & non-persistent objects?

Persistent refers to an objects ability to transcend time or space. A persistent object stores/saves
its state in a permanent storage system with out losing the information represented by the
object.
A non-persistent object is said to be transient or ephemeral. By default objects are considered as
non-persistent.
List out some of the object-oriented methodologies.
Object Oriented Development (OOD) (Booch 1991,1994).
Object Oriented Analysis and Design (OOA/D) (Coad and Yourdon 1991).
Object Modelling Techniques (OMT) (Rumbaugh 1991).
Object Oriented Software Engineering (Objectory) (Jacobson 1992).
Object Oriented Analysis (OOA) (Shlaer and Mellor 1992).
The Fusion Method (Coleman 1991).
What do you mean by analysis and design?
Analysis: It is the process of determining what needs to be done before how it should be done. In
order to accomplish this, the developer refers the existing systems and documents. So, simply it
is an art of discovery.
Design: It is the process of adopting/choosing the one among the many, which best accomplishes
the users needs. So, simply, it is compromising mechanism.
What Is a Persistent Cookie?
A persistent cookie is a cookie which is stored in a cookie file permanently on the browser's
computer. By default, cookies are created as temporary cookies which stored only in the
browser's memory. When the browser is closed, temporary cookies will be erased. You should
decide when to use temporary cookies and when to use persistent cookies based on their
differences:
Temporary cookies can not be used for tracking long-term information.
Persistent cookies can be used for tracking long-term information.
Temporary cookies are safer because no programs other than the browser can access them.
Persistent cookies are less secure because users can open cookie files see the cookie values.
What are the differences between require and include, include_once?
Anwser: require_once() and include_once() are both the functions to include and evaluate the
specified file only once. If the specified file is included previous to the present call occurrence, it
will not be done again. But require() and include() will do it as many times they are asked to do.
Anwser: The include_once() statement includes and evaluates the specified file during the
execution of the script. This is a behavior similar to the include() statement, with the only
difference being that if the code from a file has already been included, it will not be included
again. The major difference between include() and require() is that in failure include() produces a
warning message whereas require() produces a fatal errors.
Anwser: All three are used to an include file into the current page.
If the file is not present, require(), calls a fatal error, while in include() does not.
The include_once() statement includes and evaluates the specified file during the execution of the
script. This is a behavior similar to the include() statement, with the only difference being that if
the code from a file has already been included, it will not be included again. It des not call a fatal
error if file not exists. require_once() does the same as include_once(), but it calls a fatal error if
file not exists.
What is the Difference between GET and POST method?
The GET method, which was used in the example earlier, appends name/value pairs to the URL.
Unfortunately, the length of a URL is limited, so this method only works if there are only a few
parameters. The URL could be truncated if the form uses a large number of parameters, or if the
parameters contain large amounts of data. Also, parameters passed on the URL are visible in the
address field of the browser not the best place for a password to be displayed.
The alternative to the GET method is the POST method. This method packages the name/value
pairs inside the body of the HTTP request, which makes for a cleaner URL and imposes no size
limitations on the forms output. It is also more secure.

What are the different types of errors in PHP?


Here are three basic types of runtime errors in PHP:
1. Notices: These are trivial, non-critical errors that PHP encounters while executing a script - for
example, accessing a variable that has not yet been defined. By default, such errors are not
displayed to the user at all - although you can change this default behavior.
2. Warnings: These are more serious errors - for example, attempting to include() a file which
does not exist. By default, these errors are displayed to the user, but they do not result in script
termination.
3. Fatal errors: These are critical errors - for example, instantiating an object of a non-existent
class, or calling a non-existent function. These errors cause the immediate termination of the
script, and PHP's default behavior is to display them to the user when they take place.
Where can you put your database username and password file?
We can put database username and password in .htaccess file.
What is session and cookie? Which one is best to use?
Cookies can be set to a long lifespan, which means that data stored in a cookie can be stored for
months if not years. Cookies, having their data stored on the client, work smoothly when you
have a cluster of web servers, whereas sessions are stored on the server, meaning in one of your
web servers handles the first request, the other web servers in your cluster will not have the
stored information.
Sessions are stored on the server, which means clients do not have access to the information you
store about them - this is particularly important if you store shopping baskets or other
information you do not want you visitors to be able to edit by hand by hacking their cookies.
Session data, being stored on your server, does not need to be transmitted with each page;
clients just need to send an ID and the data is loaded from the local file. Finally, sessions can be
any size you want because they are held on your server, whereas many web browsers have a
limit on how big cookies can be to stop rogue web sites chewing up gigabytes of data with
meaningless cookie information.
So, as you can see, each have their own advantages, but at the end of the day it usually comes
down one choice: do you want your data to work when you visitor comes back the next day? If
so, then your only choice is cookies - if you have any particularly sensitive information, your best
bet is to store it in a database, then use the cookie to store an ID number to reference the data.
If you do not need semi-permanent data, then sessions are generally preferred, as they are a
little easier to use, do not require their data to be sent in entirety with each page, and are also
cleaned up as soon as your visitor closes their web browser.
How to upload file using php?
Using following code we can upload the files in PHP script:
We need to set the following configuration variables in php.ini file
upload_max_filesize = 8M; // change this at runtime according to need.
file_uploads = On;
upload_tmp_dir = "C:\Inetpub\wwwroot\uploads"; // /tmp in case of linux.
Note: Be sure your file upload form has attribute enctype="multipart/form-data" otherwise the
file upload will not work.
<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Problem uploading file!\n";
}
?>

How can you create secure cookie?


bool setcookie ( string $name [, string $value [, int $expire [, string $path [, string $domain [,
bool $secure [, bool $httponly]]]]]] );
in above syntax we need to keep value 1 for $secure to create secure cookie.
Explain MVC architecture.
Model: The domain-specific representation of the information on which the application operates.
Domain logic adds meaning to raw data (e.g., calculating whether today is the user's birthday, or
the totals, taxes, and shipping charges for shopping cart items).
Many applications use a persistent storage mechanism (such as a database) to store data. MVC
does not specifically mention the data access layer because it is understood to be underneath or
encapsulated by the Model.
View: Renders the model into a form suitable for interaction, typically a user interface element.
Multiple views can exist for a single model for different purposes.
Controller: Processes and responds to events, typically user actions, and may invoke changes
on the model. MVC is often seen in web applications, where the view is the actual HTML page,
and the controller is the code that gathers dynamic data and generates the content within the
HTML. Finally, the model is represented by the actual content, usually stored in a database or
XML files.
How to export data into excel file?
Use following headers to export data in excel file.
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$this->filename");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";

Anda mungkin juga menyukai