June 17, 2019

Srikaanth

MySQL Freshers Most Frequently Asked Interview Questions

MySQL Freshers Most Frequently Asked Interview Questions Answers

What's Mysql ?


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.

How Can You See All Indexes Defined For A Table?

SHOW INDEX FROM techpreparation_Questions;

How Would You Change A Column From Varchar(10) To Varchar(50)?


ALTER TABLE techpreparation_Questions CHANGE techpreparation_content techpreparation_CONTENT VARCHAR(50).

How Would You Delete A Column?

ALTER TABLE techpreparation_s DROP _user_id.

How Would You Change A Table To Innodb?

ALTER TABLE techpreparation_Questions ENGINE innodb;
MySQL Freshers Most Frequently Asked Interview Questions Answers
MySQL Freshers Most Frequently Asked Interview Questions Answers

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

How Do I Find Out All Databases Starting With 'tech' To Which I Have Access To?

SHOW DATABASES LIKE ‘tech%’;

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 techpreparation_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’re not the same for Unicode and other encodings.

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 techpreparation_com_Questions ORDER BY timestamp LIMIT 1.

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.


How Do You Convert A String To Utf-8?

SELECT (techpreparation_Question 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. Appendix G. Regular Expressions from MySQL manual is worth perusing before the interview.

How Do You Get The Month From A Timestamp?

SELECT MONTH(techpreparation_timestamp) from techpreparation_Questions;

How Do You Offload The Time/date Handling To Mysql?

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

How Do You Add Three Minutes To A Date?

ADDDATE(techpreparation_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.

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 Mysql Interfaces In Php?

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

What's The Default Port For Mysql Server?

3306 is the default port for MYSQL.

How To Drop An Existing View In Mysql?

If you have an existing view, and you dont want it anymore, you can delete it by using the “DROP VIEW viewName” statement

How To Create A New View In Mysql?

You can create a new view based on one or more existing tables by using the

“CREATE VIEW viewName AS selectStatement” .

How To Increment Dates By 1111 Mysql?

If you have a date, and you want to increment it by 1 day, you can use the DATE_ADD(date, INTERVAL 1 DAY) function. You can also use the date interval add operation as “date + INTERVAL 1 DAY.

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 note.

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

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

SERIAL is an alias for BIGINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE

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.

General Information About Mysql.

MySQL is a very fast, multi-threaded, multi-user, and robust SQL (Structured Query Language) database server.

What Is Join?

Join is data retrieval operation that combines rows from multiple tables under certain matching conditions to form a single row.

What Is Union?

Join is data retrieval operation that combines multiple query outputs of the same structure into a single output. By default the MySQL UNION removes all duplicate rows from the result set even if you don’t explicit using DISTINCT after the keyword UNION.

SELECT customerNumber id, contactLastname name
FROM customers
UNION
SELECT employeeNurrber id, firstname name
FROM employees
id name

103 Schmitt
112 King
114 Ferguson
119 Labrune
121 Bergulfsen

What Is Isam?

ISAM (Indexed Sequential Access Method) was developed by IBM to store and retrieve data on secondary storage systems like tapes.

What Is Innodb?

lnnoDB is a transaction safe storage engine developed by Innobase Oy (an Oracle company now).

What Is Bdb (berkeleydb)?

BDB (BerkeleyDB) is transaction safe storage engine originally developed at U.C. Berkeley. It is now developed by Sleepycat Software, Inc. (an Oracle company now).


How To Concatenate Two Character Strings?

If you want concatenate multiple character strings into one, you need to use the CONCAT() function. Here are some good examples:

SELECT CONCAT(’Welcome’,’ to’) FROM DUAL;
Welcome to
SELECT CONCAT(wj’,’center’,’.com’) FROM DUAL;
wisdomjobs.com

How To Enter Characters As Hex Numbers?

If you want to enter characters as HEX numbers, you can quote HEX numbers with single quotes and a prefix of (X), or just prefix HEX numbers with (Ox). A HEX number string will be automatically converted into a character string, if the expression context is a string. Here are some good examples:

SELECT X313233’ FROM DUAL;
123
SELECT 0x414243 FROM DUAL;
ABC

How To Enter Boolean Values In Sql Statements?

If you want to enter Boolean values in SQL statements, you use (TRUE), (FALSE), (true), or (false). Here are some good examples:

SELECT TRUE, true, FALSE, false FROM DUAL;

How To Convert Numeric Values To Character Strings?

You can convert numeric values to character strings by using the CAST(value AS CHAR) function as shown in the following examples:

SELECT CAST(4123.45700 AS CHAR) FROM DUAL;
4123.45700

How To Get Rid Of The Last 2 0's?

SELECT CAST(4.12345700E+3 AS CHAR) FROM DUAL;
4123.457
SELECT CAST(1/3 AS CHAR);
0.3333

How To Use In Conditions?
An IN condition is single value again a list of values. It returns TRUE, if the specified value is in the list. Otherwise, it returns FALSE. Some examples are :

SELECT 3 IN (1,2,3,4,5) FROM DUAL;
1
SELECT 3 NOT IN (1,2,3,4,5) FROM DUAL;
0
SELECT Y’ IN (‘F’,’Y’,I) FROM DUAL;
1

How To Use Like Conditions?
A LIKE condition is also called pattern patch. There are 3 main rules on using LIKE condition:

is used in the pattern to match any one character.
% is used in the pattern to match any zero or more characters.
ESCAPE clause is used to provide the escape character in the pattern.

How To Present A Past Time In Hours, Minutes And Seconds?

If you want show an article was posted “n hours n minutes and n seconds ago’, you can use the TIMEDIFF(NOWO, pastTime) function as shown in the following are:

SELECT TIMEDIFF(NOWO, ‘2006-07-01 04:09:49’) FROM DUAL;
06:42:58
SELECT TIM E_FORMAT(TI M EDI FF( NOWO, ‘2006-06-30 04:09:49’),
 ‘%H hours, %i minutes and %s seconds ago.’) FROM DUAL;
30 hours, 45 minutes and 22 seconds ago.

How To Add A New Column To An Existing Table In Mysql?

ALTER TABLE tip ADD COLUMN author VARCHAR(40);
Query OK, 1 row affected (0.18 sec)
Records: 1 Duplicates: 0 Warnings: 0

How To Delete An Existing Column In A Table?

ALTER TABLE tip DROP COLUMN create_date;
Query OK, 1 row affected (0.48 sec)
Records: 1 Duplicates: 0 Warnings: 0

How To Rename An Existing Column In A Table?

ALTER TABLE tip CHANGE COLUMN subject title VARCHAR(60);

How To Rename An Existing Table In Mysql?

ALTER TABLE tip RENAME TO faq;

How To Create A Table Index In Mvsql?

If you have a table with a lots of rows, and you know that one of the columns will be used often as a search criteria, you can add an index for that column to improve the search performance. To add an index, you can use the “CREATE INDEX” statement as shown in the following script:

<pre>mysql> CREATE TABLE tip (id INTEGER PRIMARY KEY,
subject VARCHAR(80) NOT NULL,
description VARCHAR(256) NOT NULL,
create_date DATE NULL);  Query OK,
0 rows affected (0.08 sec)</pre>
mysql> CREATE INDEX tip_subject ON tip(subject);
Query OK,
0 rows affected (0.19 sec)
Records: 0 Duplicates: 0 Warnings: 0

How To Get A List Of Indexes Of An Existing Table?

If you want to see the index you have just created for an existing table, you can use the “SHOW INDEX FROM tableName” command to get a list of all indexes in a given table.

How To Drop An Existing Index In Mysql?

If you don’t need an existing index any more, you should delete it with the “DROP INDEX indexName ON tableName” statement. Here is an example SQL script :

mysqi> DROP INDEX tip_subject ON tip;
Query OK, 0 rows affected (0.13 sec)
Records: 0 Duplicates: 0 Warnings: 0

What Is Csv?

CSV (Comma Separated Values) is a file format used to store database table contents, where one table row is stored as one line in the file, and each data field is separated with comma.

What Is Transaction?

A transaction is a logical unit of work requested by a user to be applied to the database objects. MySQL server introduces the transaction concept to allow users to group one or more SQL statements into a single transaction, so that the effects of all the SQL statements in a transaction can be either all committed (applied to the database) or all rolled back (undone from the database).


Why Sql Is A Database Management System?

A database is a structured collection of data. It may be anything from a simple shopping list to a picture gallery or the vast amounts of information in a corporate network. To add, access, and process data stored in a computer database, you need a database management system such as MySQL. Since computers are very good at handling large amounts of data, database management plays a central role in computing, as stand-alone utilities, or as parts of other applications.

Why Use Mysql?

MySQL is very fast, reliable, and easy to use. If that is what you are looking for, you should give it a try. MySQL also has a very practical set of features developed in very close cooperation with our users. You can find a performance comparison of MySQL to some other database managers on our benchmark page. See section 12.7 Using Your Own Benchmarks. MySQL was originally developed to handle very large databases much faster than existing solutions and has been successfully used in highly demanding production environments for several years. Though under constant development, MySQL today offers a rich and very useful set of functions. The connectivity, speed, and security make MySQL highly suited for accessing databases on the Internet.

How Mysql Optimizes Distinct ?

DISTINCT is converted to a GROUP BY on all columns, DISTINCT combined with ORDER BY will in many cases also need a temporary table.

When combining LIMIT # with DISTINCT, MySQL will stop as soon as it finds # unique rows.

If you don't use columns from all used tables, MySQL will stop the scanning of the not used tables as soon as it has found the first match.

SELECT DISTINCT t1.a FROM t1,t2 where t1.a=t2.a;
In the case, assuming t1 is used before t2 (check with EXPLAIN), then MySQL will stop reading from t2 (for that particular row in t1) when the first row in t2 is found.

How Mysql Optimizes Limit ?

In some cases MySQL will handle the query differently when you are using LIMIT # and not using HAVING:

If you are selecting only a few rows with LIMIT, MySQL will use indexes in some cases when it normally would prefer to do a full table scan.

If you use LIMIT # with ORDER BY, MySQL will end the sorting as soon as it has found the first # lines instead of sorting the whole table.

When combining LIMIT # with DISTINCT, MySQL will stop as soon as it finds # unique rows.

In some cases a GROUP BY can be resolved by reading the key in order (or do a sort on the key) and then calculate summaries until the key value changes. In this case LIMIT # will not calculate any unnecessary GROUP BY's.

As soon as MySQL has sent the first # rows to the client, it will abort the query.

LIMIT 0 will always quickly return an empty set. This is useful to check the query and to get the column types of the result columns.

The size of temporary tables uses the LIMIT # to calculate how much space is needed to resolve the query.

Mysql - Speed Of Delete Queries ?

If you want to delete all rows in the table, you should use TRUNCATE TABLE table_name. The time to delete a record is exactly proportional to the number of indexes. To delete records more quickly, you can increase the size of the index cache.

What Is The Difference Between Mysql_fetch_array And Mysql_fetch_object?

mysql_fetch_array — Fetch a result row as an associative ARRAY, a numeric array, or both
mysql_fetch_object — Fetch a result row as an OBJECT.

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.

ISAM : same

HEAP : Fast data access, but will loose data if there is a crash. Cannot have BLOB, TEXT & AUTO INCRIMENT fields

BDB : Supports Transactions using COMMIT & ROLLBACK. Slower that others.

InoDB : same as BDB

What Is Primary Key?

A primary key is a single column or multiple columns defined to have unique values that can be used as row identifications.

What Is Foreign Key?

A foreign key is a single column or multiple columns defined to have values that can be mapped to a primary key in another table.

What Is Index?

An index is a single column or multiple columns defined to have values pre-sorted to speed up data retrieval speed.

What Is Commit?

Commit is a way to terminate a transaction with all database changes to be saved permanently to the database server.

What Is Rollback?

Rollback is a way to terminate a transaction with all database changes not saving to the database server.

How Many Groups Of Data Types?

MySQL support 3 groups of data types as listed below:

String Data Types - CHAR, NCHAR, VARCHAR, NVARCHAR, BINARY, VARBINARY, TINYBLOB, TINYTEXT, BLOB, TEXT, MEDIUMBLOB, MEDIUMTEXT, LONGBLOB, LONGTEXT, ENUM, SET.

Numeric Data Types - BIT, TINYINT, BOOLEAN, SMALLINT, MEDIUMINT, INTEGER, BIGINT, FLOAT, DOUBLE, REAL, DECIMAL.

Date and Time Data Types - DATE, DATETIME, TIMESTAMP, TIME, YEAR.

What Is The Differences Between Char And Nchar?

Both CHAR and NCHAR are fixed length string data types. But they have the following differences:

CHARs full name is CHARACTER.
NCHARs full name is NATIONAL CHARACTER.
By default, CHAR uses ASCII character set. So 1 character is always stored as 1 byte.
By default, NCHAR uses Unicode character set. NCHAR data are stored in UTF8 format. So 1 character could be stored as 1 byte or upto 4 bytes.
Both CHAR and NCHAR columns are defined with fixed lengths in units of characters.

How To Escape Special Characters In Sql Statements?

There are a number of special characters that needs to be escaped (protected), if you want to include them in a character string. Here are some basic character escaping rules:

The escape character () needs to be escaped as (\).
The single quote (‘) needs to be escaped as (‘) or (“) in single-quote quoted strings.
The double quote () needs to be escaped as (“) or (““) in double-quote quoted strings.
The wild card character for a single character () needs to be escaped as (_).
The wild card character for multiple characters (%) needs to be escaped as (%).
The tab character needs to be escaped as (t).
The new line character needs to be escaped as (n).
The carriage return character needs to be escaped as (r).

Subscribe to get more Posts :