MYSQL Q&A

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.

3.        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;

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

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

6.        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)

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

                SELECT user_name FROM users WHERE ISNULL(user_phonenumber);

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

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

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

11.      

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

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

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

15.     How can you see all indexes defined for a table?

SHOW INDEX FROM techinterviews_questions;

16.     How would you change a column from VARCHAR(10) to VARCHAR(50)? – ALTER TABLE techinterviews_questions CHANGE techinterviews_content techinterviews_CONTENT VARCHAR(50).

17.     How would you delete a column?

– ALTER TABLE techinterviews_answers DROP answer_user_id.

18.     How would you change a table to InnoDB?

         - ALTER TABLE techinterviews_questions ENGINE innodb;

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

20.     How do I find out all databases starting with ‘tech’ to which I have access to?

- SHOW DATABASES LIKE ‘tech%’;

21.     How do you concatenate strings in MySQL?

- CONCAT (string1, string2, string3)

22.     How do you get a portion of a string?

- SELECT SUBSTR(title, 1, 10) from techinterviews_questions;

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

24.     How do you convert a string to UTF-8?

- SELECT (techinterviews_question USING utf8);

25.     What do % and _ mean inside LIKE statement?

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

26.     What does + mean in REGEXP?

 - At least one character. Appendix G. Regular Expressions from MySQL manual is worth perusing before the interview.

27.     How do you get the month from a timestamp?

- SELECT MONTH(techinterviews_timestamp) from techinterviews_questions;

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

29.     How do you add three minutes to a date?

-ADDDATE(techinterviews_publication_date, INTERVAL 3 MINUTE)

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

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

32.     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’);

33.     How are ENUMs and SETs represented internally?

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

Reference Links:

 http://www.keithjbrown.co.uk/vworks/mysql/mysql_p5.php

http://www.tutorialspoint.com/mysql/mysql-useful-functions.htm

http://www.tutorialspoint.com/php/php_function_reference.htm

Fatal Error Customization

Everyone surely has already encountered it: A fatal error on a page that is online including the white page you get to see because of it. There’s a nice and easy way of showing an error page instead of a white page if a Fatal Error occurs by using output buffering. According to its documentation, ob_start() supports a callback as first parameter. The cool thing is that this callback is also called in case of a Fatal Error!

Here’s how it works:

class Redirector
{
    public static function redirectOnError($buffer)
    {
        $lastError = error_get_last();
        if(!is_null($lastError) && $lastError['type'] === E_ERROR) {
            header(‘HTTP/1.1 302 Moved Temporarily’);
            header(‘Status: 302 Moved Temporarily’);
            header(‘Location: error.php’);
            exit();
        }
        return $buffer;
    }
}

ob_start(array(‘Redirector’, ‘redirectOnError’));
print(‘Hello’);

foobar();

ob_end_flush();
The callback is called in the moment the content is flushed, that’s why the flush should always be the last line in your output script if you wanna catch all Fatal errors. Since the callback is always executed, I added a check whether a fatal error occured, since we don’t want a redirect when no error occurs. Also keep in mind that the callback has to return the buffered output (that is already passed to the callback as a parameter) which will be printed after its execution. (Note that error_get_last() is PHP >= 5.2.0)

Note: Instead of an 302 redirect, which I used in the example, you could also just output an error message on the same page:

public static function redirectOnError($buffer)
{
    $lastError = error_get_last();
    if(!is_null($lastError) && $lastError['type'] === E_ERROR) {
        header(‘HTTP/1.1 503 Service Temporarily Unavailable’);
        header(‘Status: 503 Service Temporarily Unavailable’);
        $buffer = ‘Sorry, an error occured’;
    }
    return $buffer;
}

Days/Months/Years Between in two Date

Below the code will illustrate, how to find the days,months and years between two selected dates.

The below code has  the example of two dates to show the Days/Month/Years Between on those,

$date = “06-29-1980″;
$currentDate = mktime();    
$tdate=’2009-04-16′;       

$dateSplit = explode(“-”, $date);

//$dateSplit[0] = Month
//$dateSplit[1] = Day
//$dateSplit[2] = Year

$previousDate = mktime(0, 0, 0, $dateSplit[0], $dateSplit[1], $dateSplit[2]);

$nrSeconds = $currentDate – $previousDate;

$nrSeconds = abs($nrSeconds);
$nrDaysPassed = floor($nrSeconds / 86400);
$nrWeeksPassed = floor($nrSeconds / 604800);
$nrYearsPassed = floor($nrSeconds / 31536000);

echo $nrDaysPassed . ” days have passed between ” . date(“F j, Y”, $previousDate) . ” and ” . date(“F j, Y”, $currentDate) . “<br />”;
echo $nrWeeksPassed . ” weeks have passed between ” . date(“F j, Y”, $previousDate) . ” and ” . date(“F j, Y”, $currentDate) . “<br />”;
echo $nrYearsPassed . ” years have passed between ” . date(“F j, Y”, $previousDate) . ” and ” . date(“F j, Y”, $currentDate) . “<br />”;

Sending messages via Gmail, Hotmail or Yahoo SMTP servers

Sending messages via Gmail, Hotmail or Yahoo SMTP servers

Several popular e-mail providers, like Gmail, Hotmail and Yahoo, now allow sending messages from remote e-mail clients via their SMTP servers.

PHP can act as an e-mail client and benefit of that possibility by using capable a SMTP client class.

The MIME message comes with a sub-class specialized in sending messages via SMTP. It requires using a separate SMTP class for establishing the connection to the SMTP server and sending the messages.

http://www.phpclasses.org/smtpclass

To use these classes to send messages to e-mail providers that support SMTP relay, certain measures need to be taken.

First you need to have an account in those services and make sure that SMTP relay support is enabled for that account.

All of those providers require authentication, i.e. the SMTP client needs to send the user name and password of the e-mail account.

There are several authentication mechanisms that can be used to identify the user account. The SMTP class needs to use the SASL library (Simple Authentication Support Library) to use an authentication mechanism supported by the server.

http://www.phpclasses.org/sasl

Each e-mail provider requires specific setting values to configure aspects of the SMTP protocol. These configuration values are set by the means of different variables of SMTP sub-class of the MIME message class. Here follows the list of the most common configuration variables:

- smtp_user

Account of the user to authenticate. Usually it is the e-mail address of the account. For services like Yahoo, you have to set the From: message header to the e-mail address of the account. Gmail sets the From header to the account address if you set it to a different address.

- smtp_password

Password of the user account

- smtp_host

Address of the SMTP server host to relay the messages

- smtp_port

TCP port that should be used to connect to the SMTP server. Some e-mail providers support more than one port to work around blocks that certain ISP impose.

- timeout

Time that the class should wait for a response from the server. If set to 0, it will wait forever. If your ISP is blocking the port of the remote SMTP server you want to connect, the class will fail when it reaches the timeout period. So, do not set it to 0. If it reaches the timeout because the port is blocked, you may need to try a different port or a different SMTP server.

- smtp_ssl

Option to determine whether a secure connection should be established using SSL protocol. This feature requires at least PHP 4.3 with the OpenSSL extension enabled.

- smtp_start_tls

Option to determine whether a secure connection should be set after the connection is already established using TLS protocol. This feature requires at least PHP 5.1 with the OpenSSL extension enabled.
Here follows the configuration values for each of the e-mail providers:

- Gmail

smtp_host: smtp.gmail.com
smtp_port: 465
smtp_ssl: 1

- Hotmail

smtp_host: smtp.live.com
smtp_port: 25 or 587
smtp_start_tls: 1

- Yahoo Mail Plus (currently a paid service)

smtp_host: smtp.mail.yahoo.com
smtp_port: 25
* Quick replacement for the mail() function

If you have a PHP application written using the mail function but you need to change it to relay messages to an SMTP service, the MIME message class comes with a replacement function in the smtp_mail.php script named smtp_mail() .

All you need to do is to include the smtp_mail.php script and replace all calls to the mail function by calls to smtp_mail(). The parameters are the same, so you do not need to change them.

You may need change that script to set the required configuration values to use a given SMTP service provider.
* Other difficulties

This tips should be sufficient to help you solve the problem of delivering messages using remote SMTP servers. If you still have difficulties, feel free to post a comment to this article.

Script to Disable Mouse Right Click

Following is the script to disable mouse right click to copy the text while browsing the sites,

<script language=JavaScript>
<!–

//Disable right click script III- By Renigade (renigade@mediaone.net)
//For full source code, visit http://www.dynamicdrive.com

var message=”";
///////////////////////////////////
function clickIE() {if (document.all) {(message);return false;}}
function clickNS(e) {if
(document.layers||(document.getElementById&&!document.all)) {
if (e.which==2||e.which==3) {(message);return false;}}}
if (document.layers)
{document.captureEvents(Event.MOUSEDOWN);document.onmousedown=clickNS;}
else{document.onmouseup=clickNS;document.oncontextmenu=clickIE;}

document.oncontextmenu=new Function(“return false”)
// –>
</script>

Add this script in every web page and invoke this script in the body of the page as seen like below type,

<body id=”home” onselectstart=”return false;” style=”-moz-user-select: none;”>

Calculate Distance using Google Maps API

Calculate Distance on different location in the world by placing the  source and destination place in the below code while runing the below code.

This application using the Maps API to calculate the distance between two place. Below are the code to download and screenshot to display the output while running the application.

GMAP Distance

GMAP Distance

The Output will look like:
 

GMAP Output

GMAP Output

Close window without the prompt message

Close window without the prompt message in IE7
If you tried to close a window using javascript window.close() method in IE7, and as you may noticed a message will prompt “The Webpage you are viewing is trying to close the window. Do you want to close this window”.

Because of the security enhancements in IE7, you can’t close a window unless it is opened by a script. so the walkaround will be to let the browser thinks that this page is opened using a script then closing the window. below is the implementation.

Create a javascript function which will be called to close the window

<script language=javascript>

function CloseWindow()
{
window.open(”,’_self’,”);
window.close();
}
</script>

the code in bold is used to open a window in this case it’s not defined into the current window. In this way, we let the browser thinks that the current window is opened using javascript, so when the window.close() is executed it will close it without the message being displayed.

Now you can try it by adding the below HTML code,

<a href=”" onclick=”CloseWindow();”>Testing Close Window</a>

Hope this post will help you.

Below is the example to close the parent window closing while chid get opend,

var win =window.open (“URL”,”TITLE”,”width=1200,height=740,location=no”);
win.moveTo(0,0);
win.resizeTo(1200, 870);
window.open(”,’_self’,”);
window.close();

CHASE Response Directory

Here is the attachment for CHASE Response error tracking report will help you to trace the error while processing the orders.

Download the Orbital CHASE Gateway Interface Specification

Newer entries »

Follow

Get every new post delivered to your Inbox.