Web Technology Viva Questions

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 52

Viva Questions

Q) What is HTML?

HTML stands for Hyper Text Markup Language. It is a language of World Wide Web. It is a standard text formatting language which is used
to create and display pages on the Web.

Q) What are Tags?

HTML tags are composed of three things: opening tag, content and ending tag. Some tags are unclosed tags.

HTML documents are made of two things:

content, and
tags
Content is placed between tags to display data on the web page.

Q) Do all HTML tags have end tag?

No. There are some HTML tags that don't need a closing tag. For example: <image> tag, <br> tag.

Q) What are some common lists that are used when designing a page?

There are many common lists which are used to design a page. You can choose any or a combination of the following list types:

Ordered list
Unordered list
Menu list
Directory list
Definition list

Q) What is the difference between HTML elements and tags?

HTML elements communicate to the browser to render text. When the elements are surrounded by brackets <>, they form HTML tags. Most
of the time, tags come in pair and surround content.

Q) What is semantic HTML?

Semantic HTML is a coding style. It is the use of HTML markup to reinforce the semantics or meaning of the content. For example: In
semantic HTML <b> </b> tag is not used for bold statement as well as <i> </i> tag is used for italic. Instead of these we use
<strong></strong> and <em></em> tags.

Q) What is image map?

Image map facilitates you link many different web pages using a single image. You can define shapes in images that you want to make part
of an image mapping.

Q) How to insert a copyright symbol on a browser page?

can insert a copyright symbol by using &copy; or &#169; in an HTML file.

Q) How do you keep list elements straight in an HTML file?

You can keep the list elements straight by using indents.

Q) Does a hyperlink only apply to text?

No, you can use hyperlinks on text and images both.

Q) What is a style sheet?

A style sheet is used to build a consistent, transportable, and well designed style template. You can add these templates on several different
web pages.

Q) Can you create a multi colored text on a web page?

Yes. To create a multicolor text on a web page you can use <font color ="color"> </font> for the specific texts you want to color.

Q) Is it possible to change the color of the bullet?

The color of the bullet is always the color of the first text of the list. So, if you want to change the color of the bullet, you must change the
color of the text.

Q) What is a marquee?
Marquee is used to put the scrolling text on a web page. You should put the text which you want to scroll within the
<marquee>......</marquee> tag.

Q) How many tags can be used to separate section of texts?

There are three tags used to separate the texts. i.e. usually <br> tag is used to separate line of texts. Other tags are<p> tag and
<blockquote> tag.

Q) How to make a picture a background image of a web page?

To make a picture a background image on a web page, you should put the following tag code after the </head> tag.

<body background = "image.gif">


Here, replace the "image.gif" with the name of your image file which you want to display on your web page.

Q) What are empty elements?

HTML elements with no content are called empty elements. For example: <br>, <hr> etc.

Q) What is the use of span tag? Give one example.

The span tag is used for following things:

For adding color on text


For adding background on text
Highlight any color text etc.
Example:

<p>
<span style="color:#ffffff;">
In this page we use span.
</span>
</p>

Q) What is the use of iframe tag?

An iframe is used to display a web page within a web page.

Syntax:

<iframe src="URL"></iframe>
Example:

<iframe src="demo_iframe.html" width="200px" height="200px"></iframe>


Target to a link:

<iframe src="http://www.javatpoint.com" name="iframe_a"></iframe>


HTML5 Interview Questions

Let's see a list of top HTML5 interview questions and answers.

Q) What is canvas in HTML5?

Canvas is an HTML area which is used to draw graphics.

Q) What is SVG?

HTML SVG is used to describe the two dimensional vector and vector/raster graphics.

Q) What are the different new form element types in HTML 5?

Following is a list of 10 important new elements in HTML 5:

Color
Date
Datetime-local
Email
Time
Url
Range
Telephone
Number
Search
Q) Is there any need to change the web browsers to support HTML5?

No. Almost all browsers (updated versions) support HTML 5. For example: Chrome, Firefox, Opera, Safari, IE etc.

Q) Which video formats are supported by HTML5?

HTML 5 supports three types of video format:

mp4
webm
ogg

Q) Is audio tag supported in HTML 5?

Yes. It is used to add sound or music files on the web page.

Q) What is the difference between progress and meter tag?

The progress tag is used to represent the progress of the task only while the meter tag is used to measure data within a given range.

Q) What is the use of figure tag in HTML 5?

The figure tag is used to add a photo in the document on the web page.

Q) What is button tag?

The button tag is used in HTML 5. It is used to create a clickable button within HTML form on the web page. It is generally used to create a
"submit" or "reset" button.

Q) What does details and summary tag?

The details tag is used to specify some additional details on the web page. It can be viewed or hidden on demand. The summary tag is used
with details tag.

Q) What is datalist tag?

The HTML 5 datalist tag provides an auto complete feature on form element. It facilitates users to choose the predefined options.

Q) If I do not put <!DOCTYPE html> will HTML 5 work?

No, browser will not be able to identify that it is a HTML document and HTML 5 tags will not function properly.

Q) What is JavaScript?

JavaScript is a scripting language. It is different from Java language. It is object-based, lightweight and cross platform. It is widely used for
client side validation.

Q) What is the difference between JavaScript and jscript?

Netscape provided the JavaScript language. Microsoft changed the name and called it JScript to avoid the trademark issue.In other words,
you can say JScript is same as JavaScript, but it is provided by Microsoft.

Q) How to write a hello world example of JavaScript?

A simple example of JavaScript hello world is given below. You need to place it inside the body tag of html.

<script type="text/javascript">
document.write("JavaScript Hello World!");
</script>

Q) How to use external JavaScript file?

I am assuming that js file name is message.js, place the following script tag inside the head tag.

<script type="text/javascript" src="message.js"></script>

Q) Is JavaScript case sensitive language?

Yes.
Q) What is DOM? What is the use of document object?

DOM stands for Document Object Model. A document object represent the html document. It can be used to access and change the content
of html.

Q) What is the use of window object?

The window object is automatically created by the browser that represents a window of a browser.

It is used to display the popup dialog box such as alert dialog box, confirm dialog box, input dialog box etc.

Q) What is the use of history object?

The history object of browser can be used to switch to history pages such as back and forward from current page or another page. There are
three methods of history object.

history.back()
history.forward()
history.go(number): number may be positive for forward, negative for backward.

Q) How to write comment in JavaScript?

There are two types of comments in JavaScript.

Single Line Comment: It is represented by // (double forward slash)


Multi Line Comment: It is represented by slash with asterisk symbol as /* write comment here */

Q) How to create function in JavaScript?

To create function in JavaScript, follow the following syntax.

function function_name(){
//function body
}

Q) What are the JavaScript data types?

There are two types of data types in JavaScript:

Primitive Data Types


Non-primitive Data Types

Q) What is the difference between == and ===?

The == operator checks equality only whereas === checks equality and data type i.e. value must be of same type.

Q) How to write html code dynamically using JavaScript?

The innerHTML property is used to write the HTML code using JavaScript dynamically. Let's see a simple example:

document.getElementById('mylocation').innerHTML="<h2>This is heading using JavaScript</h2>";

Q) How to write normal text code using JavaScript dynamically?

The innerText property is used to write the simple text using JavaScript dynamically. Let's see a simple example:

document.getElementById('mylocation').innerText="This is text using JavaScript";

Q) How to create objects in JavaScript?

There are 3 ways to create object in JavaScript.

By object literal
By creating instance of Object
By Object Constructor
Let's see a simple code to create object using object literal.

emp={id:102,name:"Rahul Kumar",salary:50000}

Q) How to create array in JavaScript?

There are 3 ways to create array in JavaScript.


By array literal
By creating instance of Array
By using an Array constructor
Let's see a simple code to create array using object literal.

var emp=["Shyam","Vimal","Ratan"];  

Q) What does the isNaN() function?

The isNan() function returns true if the variable value is not a number.

Q) What is the output of 10+20+"30" in JavaScript?

3030 because 10+20 will be 30. If there is numeric value before and after +, it is treated is binary + (arithmetic operator).

Q) What is the output of "10"+20+30 in JavaScript?

102030 because after a string all the + will be treated as string concatenation operator (not binary +).

Q) Difference between Client side JavaScript and Server side JavaScript?

Client side JavaScript comprises the basic language and predefined objects which are relevant to running java script in a browser. The client
side JavaScript is embedded directly by in the HTML pages. This script is interpreted by the browser at run time.

Server side JavaScript also resembles like client side java script. It has relevant java script which is to run in a server. The server side
JavaScript are deployed only after compilation.

Q) In which location cookies are stored on the hard disk?

The storage of cookies on the hard disk depends on OS and the browser.

The Netscape navigator on Windows uses cookies.txt file that contains all the cookies. The path is : c:\Program Files\Netscape\Users\
username\cookies.txt

The Internet Explorer stores the cookies on a file [email protected]. The path is: c:\Windows\Cookies\[email protected].

Q) What is the real name of JavaScript?

The original name was Mocha, a name chosen by Marc Andreessen, founder of Netscape. In September of 1995, the name was changed to
LiveScript. In December 1995, after receiving a trademark license from Sun, the name JavaScript was adopted.

Q) What is the difference between undefined value and null value?

Undefined value: A value that is not defined and has no keyword is known as undefined value. For example:

int number;//Here, number has undefined value.


Null value: A value that is explicitly specified by the keyword "null" is known as null value. For example:

String str=null;//Here, str has a null value.

Q) How to set the cursor to wait in JavaScript?

The cursor can be set to wait in JavaScript by using the property "cursor". The following example illustrates the usage:

<script>
window.document.body.style.cursor = "wait";
</script>

Q) What is this?

var myArray = [[[]]];


Ans: Three dimensional array.

Q) Are Java and JavaScript same?

No, Java and JavaScript are the two different languages. Java is a robust, secured and object-oriented programming language whereas
JavaScript is a client side scripting language with some limitations.

Q) What is negative infinity?

Negative Infinity is a number in JavaScript which can be derived by dividing negative number by zero.

Q) What is difference between View state and Session state?


"View state" is specific to a page in a session whereas "Session state" is specific to a user or browser that can be accessed across all pages
in the web application.

Q) What are the pop up boxes available in JavaScript?

Alert Box
Confirm Box
Prompt Box

Q) How can we detect OS of the client machine using JavaScript?

The navigator.appVersion string can be used to detect the operating system on the client machine.

Q) How to submit a form using JavaScript by clicking a link?

Let's see the JavaScript code to submit form on clicking the link.

<form name="myform" action="index.php">


Search: <input type='text' name='query' />
<a href="javascript: submitform()">Search</a>
</form>
<script type="text/javascript">
function submitform()
{
  document.myform.submit();
}
</script>

Q) Is JavaScript faster than ASP script?

Yes, because it doesn't require web server's support for execution.

Q) How to change the background color of HTML document using JavaScript?

<script type="text/javascript">
document.body.bgColor="pink";
</script>

Q) How to handle exceptions in JavaScript?

By the help of try/catch block, we can handle exceptions in JavaScript. JavaScript supports try, catch, finally and throw keywords for
exception handling.

Q)What is JSP?

Java Server Pages technology (JSP) is used to create dynamic web page. It is an extension to the servlet technology. A JSP page is
internally converted into servlet.

1) What is XML?

XML stands for eXtensible Markup Language. It is a simple and flexible markup language. It is known as universal language for data
on the web because XML documents can be created and used in any language. It is universal standard for information interchange.

XML technology facilitates you to create your own markup language.

more details...

2) How XML is different from HTML?

HTML stands for Hyper Text Markup Language while XML stands for eXtensible Markup Language. The key differences between
HTML and XML are given below:

Backward Skip 10sPlay VideoForward Skip 10s


No. HTML XML

1) HTML is used to display data and focuses XML is a software and hardware independent tool used to transport
on how data looks. and store data. It focuses on what data is.

2) HTML is a markup language itself. XML provides a framework to define markup languages.

3) HTML is not case sensitive. XML is case sensitive.

4) HTML is a presentation language. XML is neither a presentation language nor a programming language.

3) What is the meaning of version in XML?

Version is a tag used to show which version of XML is used.

4) What are the benefits of XML?

These are the main benefits of using XML.

Simplicity: Very easy to read and understand the information coded in XML.

Openness: It is a W3C standard, endorsed by software industry market leaders.

Extensibility: It is extensible because it has no fixed set of tags. You can define them as you need.

Self-descriptive: XML documents do not need special schema set-up like traditional databases to store data. XML documents can
be stored without such definitions, because they contain metadata in the form of tags and attributes.

Scalable: XML is not in binary format so you can create and edit files with anything and it is also easy to debug.

Fast access: XML documents are arranged in hierarchical form so it is comparatively faster.

5) What is XML DOM?

DOM stands for Document Object Model which is used to describe the logical structure of XML document. It is a hierarchical model
that provides a way to access and manipulate an XML document.

DOM methods and objects can be used with any languages like C#, VB, JavaScript and VB Script.

6) What is SAX in XML?

SAX stands for Simple API for XML. It is a sequential access parser. It is a simple API for XML which provides a mechanism for reading
data from an XML document. It is an alternative of DOM. DOM operates on the documents as whole, SAX parsers operate on each
piece of the XML document sequentially.
SAX has no formal specification like DOM and consumes less memory. But it can be used to read the XML document only not write.

7) What is XSNL?

XSNL is an XML search neutral language. This language acts between the meta search interface and targeted system.

8) What is a well formed XML document?

A syntactically correct document is called well formed XML document. A well formed XML document must follow the XML?s basic
rules of syntax:

o It must have a closing tag.


o The closing tag must exactly match the open tag: XML is case sensitive.
o All elements should be included within a single root tag.
o Child elements must be closed within parent tag.

9) What is a valid XML document?

A structurally correct element is called a valid XML document. It should follow some predefined rules of a specific type of document.
These rules determine the type of data that each part of the document can contain. These rules can be written by the author of an
XML document or someone other.

1) What is PHP?

PHP stands for Hypertext Preprocessor. It is an open source server-side scripting language which is widely used for web
development. It supports many databases like MySQL, Oracle, Sybase, Solid, PostgreSQL, generic ODBC etc.

More Details...

2) What is PEAR in PHP?

PEAR is a framework and repository for reusable PHP components. PEAR stands for PHP Extension and Application Repository. It
contains all types of PHP code snippets and libraries.

PauseNext
Unmute

Current Time 1:00

/
Duration 18:10
Loaded: 11.37%
 
Fullscreen

It also provides a command line interface to install "packages" automatically.

3) Who is known as the father of PHP?

Rasmus Lerdorf

4) What was the old name of PHP?

The old name of PHP was Personal Home Page.

5) Explain the difference b/w static and dynamic websites?

In static websites, content can't be changed after running the script. You can't change anything on the site. It is predefined.

In dynamic websites, content of script can be changed at the run time. Its content is regenerated every time a user visit or reload.
Google, yahoo and every search engine is the example of dynamic website.

6) What is the name of scripting engine in PHP?

The scripting engine that powers PHP is called Zend Engine 2.

7) Explain the difference between PHP4 and PHP5.

PHP4 doesn't support oops concept and uses Zend Engine 1.

PHP5 supports oops concept and uses Zend Engine 2.

8) What are the popular Content Management Systems (CMS) in PHP?


o WordPress: WordPress is a free and open-source content management system (CMS) based on PHP & MySQL. It includes
a plug-in architecture and template system. It is mostly connected with blogging but supports another kind of web
content, containing more traditional mailing lists and forums, media displays, and online stores.
o Joomla: Joomla is a free and open-source content management system (CMS) for distributing web content, created by
Open Source Matters, Inc. It is based on a model-view-controller web application framework that can be used
independently of the CMS.
o Magento: Magento is an open source E-trade programming, made by Varien Inc., which is valuable for online business. It
has a flexible measured design and is versatile with many control alternatives that are useful for clients. Magento utilizes
E-trade stage which offers organization extreme E-business arrangements and extensive support network.
o Drupal: Drupal is a CMS platform developed in PHP and distributed under the GNU (General Public License).

9) What are the popular frameworks in PHP?

o CakePHP
o CodeIgniter
o Yii 2
o Symfony
o Zend Framework etc.

10) Which programming language does PHP resemble to?

PHP has borrowed its syntax from Perl and C.

11) List some of the features of PHP7.

o Scalar type declarations


o Return type declarations
o Null coalescing operator (??)
o Spaceship operator
o Constant arrays using define()
o Anonymous classes
o Closure::call method
o Group use declaration
o Generator return expressions
o Generator delegation
o Space ship operator

12) What is "echo" in PHP?


PHP echo output one or more string. It is a language construct not a function. So the use of parentheses is not required. But if you
want to pass more than one parameter to echo, the use of parentheses is required.

Syntax:

1. void echo ( string $arg1 [, string $... ] )  
More details...

13) What is "print" in PHP?

PHP print output a string. It is a language construct not a function. So the use of parentheses is not required with the argument list.
Unlike echo, it always returns 1.

Syntax:

1. int print ( string $arg)  
More details...

14) What is the difference between "echo" and "print" in PHP?

Echo can output one or more string but print can only output one string and always returns 1.

Echo is faster than print because it does not return any value.

15) How a variable is declared in PHP?

A PHP variable is the name of the memory location that holds data. It is temporary storage.

Syntax:

1. $variableName=value;  
More details...

16) What is the difference between $message and $$message?

$message stores variable data while $$message is used to store variable of variables.

$message stores fixed data whereas the data stored in $$message may be changed dynamically.

More Details...

17) What are the ways to define a constant in PHP?


PHP constants are name or identifier that can't be changed during execution of the script. PHP constants are defined in two ways:

o Using define() function


o Using const() function

More details...

18) What are magic constants in PHP?

PHP magic constants are predefined constants, which change based on their use. They start with a double underscore (__) and end
with a double underscore (__).

More Details...

19) How many data types are there in PHP?

PHP data types are used to hold different types of data or values. There are 8 primitive data types which are further categorized in 3
types:

o Scalar types
o Compound types
o Special types

More Details...

20) How to do single and multi line comment in PHP?

PHP single line comment is made in two ways:

o Using // (C++ style single line comment)


o Using # (Unix Shell style single line comment)

PHP multi-line comment is made by enclosing all lines within.

More details...

21) What are the different loops in PHP?

For, while, do-while and for each.

22) What is the use of count() function in PHP?

The PHP count() function is used to count total elements in the array, or something an object.
23) What is the use of header() function in PHP?

The header() function is used to send a raw HTTP header to a client. It must be called before sending the actual output. For example,
you can't print any HTML element before using this function.

24) What does isset() function?

The isset() function checks if the variable is defined and not null.

25) Explain PHP parameterized functions.

PHP parameterized functions are functions with parameters. You can pass any number of parameters inside a function. These given
parameters act as variables inside your function. They are specified inside the parentheses, after the function name. Output depends
upon dynamic values passed as parameters into the function.

More details...

26) Explain PHP variable length argument function

PHP supports variable length argument function. It means you can pass 0, 1 or n number of arguments in function. To do this, you
need to use 3 ellipses (dots) before the argument name. The 3 dot concept is implemented for variable length argument since PHP
5.6.

More details...

27) Explain PHP variable length argument function.

PHP supports variable length argument function. It means you can pass 0, 1 or n number of arguments.

28) What is the array in PHP?

An array is used to store multiple values in a single value. In PHP, it orders maps of pairs of keys and values. It saves the collection of
the data type.

More Details...

29) How many types of array are there in PHP?


There are three types of array in PHP:

1. Indexed array: an array with a numeric key.


2. Associative array: an array where each key has its specific value.
3. Multidimensional array: an array containing one or more arrays within itself.

30) Explain some of the PHP array functions?

There are many array functions in PHP:

o array()
o array_change_key_case()
o array_chunk()
o count()
o sort()
o array_reverse()
o array_search()
o array_intersect()

More details...

31) What is the difference between indexed and associative array?

The indexed array holds elements in an indexed form which is represented by number starting from 0 and incremented by 1. For
example:

1. $season=array("summer","winter","spring","autumn");    

The associative array holds elements with name. For example:

1. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");    

More Details...

32) How to get the length of string?

The strlen() function is used to get the length of the string.

More Details...

33) Explain some of the PHP string functions?


There are many array functions in PHP:

o strtolower()
o strtoupper()
o ucfirst()
o lcfirst()
o ucwords()
o strrev()
o strlen()

More details...

34) What are the methods to submit form in PHP?

There are two methods GET and POST.

More Details...

35) How can you submit a form without a submit button?

You can use JavaScript submit() function to submit the form without explicitly clicking any submit button.

36) What are the ways to include file in PHP?

PHP allows you to include file so that page content can be reused again. There are two ways to add the file in PHP.

1. include
2. require

More details...

37) Differentiate between require and include?

Require and include both are used to include a file, but if data is not found include sends warning whereas require sends Fatal error.

More Details...

38) Explain setcookie() function in PHP?

PHP setcookie() function is used to set cookie with HTTP response. Once the cookie is set, you can access it by $_COOKIE
superglobal variable.
Syntax:

1. bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path     
2. [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )    
More details...

39) How can you retrieve a cookie value?

1. echo $_COOKIE ["user"];  
More Details...

40) What is a session?

PHP Engine creates a logical object to preserve data across subsequent HTTP requests, which is known as session.

Sessions generally store temporary data to allow multiple PHP pages to offer a complete functional transaction for the same user.

Simply, it maintains data of an user (browser).

More Details...

41) What is the method to register a variable into a session?

1. <?php  
2. Session_register($ur_session_var);  
3. ?>  

42) What is $_SESSION in PHP?

A session creates a file in a temporary directory on the server where registered session variables and their session id are stored. This
data will be available to all pages on the site amid that visit.

The area of the temporary record is controlled by a setting in the php.ini document called session.save_path.

At the point when a session is begun following things happen -

1. PHP first makes two duplicates of one of a kind session id for that particular session of the client which is an arbitrary
string of 32 hexadecimal numbers, for example, 3c7foj34c3jjhkyepop2fc937e3443.
2. One copy of unique session id automatically sent to the user?s computer for the sake of synchronization in future ahead,
and one copy is being maintained at server side till the session is running.
3. Whenever you want to access the page of website or web app, then session id of the current user will be associated with
the HTTP header, and that will be compared by the session id which is being maintained at the server. After completing
the comparison process, you can easily access the page of the website or web app
4. A session ends when the user closes the browser, or after leaving the site, the server will terminate the session after a
predetermined period, commonly 30 minutes duration.

43) What is PHP session_start() and session_destroy() function?

PHP session_start() function is used to start the session. It starts new or resumes the current session. It returns the current session if
the session is created already. If the session is not available, it creates and returns new sessions.

More details...

44) What is the difference between session and cookie?

The main difference between session and cookie is that cookies are stored on user's computer in the text file format while sessions are
stored on the server side.

Cookies can't hold multiple variables, on the other hand, Session can hold multiple variables.

You can manually set an expiry for a cookie, while session only remains active as long as browser is open.

45) Write syntax to open a file in PHP?

PHP fopen() function is used to open file or URL and returns resource. It accepts two arguments: $filename and $mode.

Syntax:

1. resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )  
More details...

46) How to read a file in PHP?

PHP provides various functions to read data from the file. Different functions allow you to read all file data, read data line by line,
and read data character by character.

PHP file read functions are given below:

o fread()
o fgets()
o fgetc()

More details...

47) How to write in a file in PHP?


PHP fwrite() and fputs() functions are used to write data into file. To write data into a file, you need to use w, r+, w+, x, x+, c or c+
mode.

More details...

48) How to delete file in PHP?

The unlink() function is used to delete a file in PHP.

1. bool unlink (string $filename)      

More Details...

49) What is the method to execute a PHP script from the command line?

You should just run the PHP command line interface (CLI) and specify the file name of the script to be executed as follows.

50) How to upload file in PHP?

The move_uploaded_file() function is used to upload file in PHP.

1. bool move_uploaded_file ( string $filename , string $destination )    

More Details...

51) How to download file in PHP?

The readfile() function is used to download the file in PHP.

1. int readfile ( string $filename )     

More Details...

52) How can you send email in PHP?

The mail() function is used to send email in PHP.

1. bool mail($to,$subject,$message,$header);    

More Details...
53) How do you connect MySQL database with PHP?

There are two methods to connect MySQL database with PHP. Procedural and object-oriented style.

More Details...

54) How to create connection in PHP?

The mysqli_connect() function is used to create a connection in PHP.

1. resource mysqli_connect (server, username, password)       

More Details...

55) How to create database connection and query in PHP?

Since PHP 4.3, mysql_reate_db() is deprecated. Now you can use the following 2 alternatives.

o mysqli_query()
o PDO::_query()

More details...

56) How can we increase execution time of a PHP script?

By default, the maximum execution time for PHP scripts is set to 30 seconds. If a script takes more than 30 seconds, PHP stops the
script and returns an error.

You can change the script run time by changing the max_execution_time directive in the php.ini file.

When a script is called, set_time_limit function restarts the timeout counter from zero. It means, if default timer is set to 30 sec, and
20 sec is specified in function set_time_limit(), then script will run for 45 seconds. If 0sec is specified in this function, script takes
unlimited time.

57) What are the different types of errors in PHP?

There are 3 types of error in PHP.

1. Notices:These are non-critical errors. These errors are not displayed to the users.
2. Warnings:These are more serious errors, but they do not result in script termination. By default, these errors are displayed
to the user.
3. Fatal Errors:These are the most critical errors. These errors may cause due to immediate termination of script.

58) How to stop the execution of PHP script?

The exit() function is used to stop the execution of PHP script.

59) What are the encryption functions in PHP?

CRYPT() and MD5()

60) What is htaccess in PHP?

The .htaccess is a configuration file on Apache server. You can change configuration settings using directives in Apache
configuration files like .htaccess and httpd.conf.

61) Explain PHP explode() function.

The PHP explode() function breaks a string into an array.

62) Explain PHP split() function.

The PHP split() function splits string into an array by regular expression.

63) How can we get IP address of a client in PHP?

1. $_SERVER["REMOTE_ADDR"];  

64) What is the meaning of a Persistent Cookie?

A persistent cookie is permanently stored in a cookie file on the browser's computer. By default, cookies are temporary and are
erased if we close the browser.
65) What is the use of the function 'imagetypes()'?

imagetypes() gives the image format and types supported by the current version of GD-PHP.

66) What are include() and require() functions?

The Include() function is used to put data of one PHP file into another PHP file. If errors occur, then the include() function produces
a warning but does not stop the execution of the script, and it will continue to execute.

The Require() function is also used to put data of one PHP file to another PHP file. If there are any errors, then the require() function
produces a warning and a fatal error and stops the script.

67) What is Cookies? How to create cookies in PHP?

A cookie is used to identify a user. A cookie is a little record that the server installs on the client's Computer. Each time a similar PC
asks for a page with a program, it will send the cookie as well. With PHP, you can both make and recover cookie value.

Some important points regarding Cookies:

1. Cookies maintain the session id generated at the back end after verifying the user's identity in encrypted form, and it must
reside in the browser of the machine
2. You can store only string values not object because you can't access any object across the website or web apps
3. Scope: - Multiple pages.
4. By default, cookies are temporary and transitory cookie saves in the browser only.
5. By default, cookies are URL particular means Gmail isn't supported in Yahoo and the vice versa.
6. Per site 20 cookies can be created in one website or web app
7. The Initial size of the cookie is 50 bytes.
8. The Maximum size of the cookie is 4096 bytes.

68) What is the Importance of Parser in PHP?

PHP parser parses the PHP developed website from the opening to the closing tag. Tags indicate that from where PHP code is being
started and ended. In other words, opening and closing tags decide the scope of PHP scripting syntax of closing tag in PHP

<?php syntax of opening tag in PHP


?> syntax of closing tag in PHP

69) How can we create a database using PHP and MySQL?

The necessary steps to create a MySQL database using PHP are:


o Establish a connection to MySQL server from your PHP script.
o If the connection is successful, write a SQL query to create a database and store it in a string variable.
o Execute the query.

1) What is SQL?

SQL stands for the Structured Query Language. It is the standard language used to maintain the relational database and perform
many different data manipulation operations on the data. SQL was initially invented in 1970. It is a database language used for
database creation, deletion, fetching and modifying rows, etc. sometimes, it is pronounced as 'sequel.' We can also use it to handle
organized data comprised of entities (variables) and relations between different entities of the data.

2) When SQL appeared?

SQL first appeared in 1974. It is one of the most used languages for maintaining the relational database. In 1986, SQL became the
standard of the American National Standards Institute (ANSI) and ISO (International Organization for Standardization) in 1987.

3) What are the usages of SQL?

SQL is responsible for maintaining the relational data and the data structures present in the database. Some of the common usages
are given below:

Backward Skip 10sPlay VideoForward Skip 10s

o To execute queries against a database


o To retrieve data from a database
o To inserts records in a database
o To updates records in a database
o To delete records from a database
o To create new databases
o To create new tables in a database
o To create views in a database
o To perform complex operations on the database.

4) Does SQL support programming language features?

SQL refers to the Standard Query Language. Therefore, it is true that SQL is a language but does not actually support the
programming language. It is a common language that doesn't have a loop, conditional statements, and logical operations. It cannot
be used for anything other than data manipulation. It is a command language to perform database operations. The primary purpose
of SQL is to retrieve, manipulate, update, delete, and perform complex operations like joins on the data present in the database.
5) What are the subsets of SQL?

The following are the four significant subsets of the SQL:

o Data definition language (DDL): It defines the data structure that consists of commands like CREATE, ALTER, DROP, etc.
o Data manipulation language (DML): It is used to manipulate existing data in the database. The commands in this
category are SELECT, UPDATE, INSERT, etc.
o Data control language (DCL): It controls access to the data stored in the database. The commands in this category
include GRANT and REVOKE.
o Transaction Control Language (TCL): It is used to deal with the transaction operations in the database. The commands
in this category are COMMIT, ROLLBACK, SET TRANSACTION, SAVEPOINT, etc.

6) What is the purpose of DDL Language?

DDL stands for Data definition language. It is the subset of a database that defines the data structure of the database when the
database is created. For example, we can use the DDL commands to add, remove, or modify tables. It consists of the following
commands: CREATE, ALTER and DELETE database objects such as schema, tables, indexes, view, sequence, etc.

Example

1. CREATE TABLE Students  
2. (  
3. Roll_no INT,  
4. Name VARCHAR(45),  
5. Branch VARCHAR(30),  
6. );  

7) What is the purpose of DML Language?

Data manipulation language makes the user able to retrieve and manipulate data in a relational database. The DML commands can
only perform read-only operations on data. We can perform the following operations using DDL language:

o Insert data into the database through the INSERT command.


o Retrieve data from the database through the SELECT command.
o Update data in the database through the UPDATE command.
o Delete data from the database through the DELETE command.

Example

1. INSERT INTO Student VALUES (111, 'George', 'Computer Science')  

8) What is the purpose of DCL Language?


Data control language allows users to control access and permission management to the database. It is the subset of a database,
which decides that what part of the database should be accessed by which user at what point of time. It includes two commands,
GRANT and REVOKE.

GRANT: It enables system administrators to assign privileges and roles to the specific user accounts to perform specific tasks on the
database.

REVOKE: It enables system administrators to revoke privileges and roles from the user accounts so that they cannot use the
previously assigned permission on the database.

Example

1. GRANT * ON mydb.Student TO javatpoint@localhsot;  

9) What are tables and fields in the database?

A table is a set of organized data in the form of rows and columns. It enables users to store and display records in the structure
format. It is similar to worksheets in the spreadsheet application. Here rows refer to the tuples, representing the simple data item,
and columns are the attribute of the data items present in a particular row. Columns can categorize as vertical, and Rows are
horizontal.

Fields are the components to provide the structure for the table. It stores the same category of data in the same data type. A table
contains a fixed number of columns but can have any number of rows known as the record. It is also called a column in the table of
the database. It represents the attribute or characteristics of the entity in the record.

Example

Table: Student

Field: Stud_rollno, Stud_name, Date of Birth, Branch, etc.

10) What is a primary key?

A primary key is a field or the combination of fields that uniquely identify each record in the table. It is one of a special kind of
unique key. If the column contains a primary key, it cannot be null or empty. A table can have duplicate columns, but it cannot have
more than one primary key. It always stores unique values into a column. For example, the ROLL Number can be treated as the
primary key for a student in the university or college.

We can define a primary key into a student table as follows:

1. CREATE TABLE Student (    
2.     roll_number INT PRIMARY KEY,    
3.     name VARCHAR(45),     
4. );    

To read more information, click here.

11) What is a foreign key?

The foreign key is used to link one or more tables together. It is also known as the referencing key. A foreign key is specified as a key
that is related to the primary key of another table. It means a foreign key field in one table refers to the primary key field of the other
table. It identifies each row of another table uniquely that maintains the referential integrity. The primary key-foreign key
relationship is a very crucial relationship as it maintains the ACID properties of the database sometimes. It also prevents actions that
would destroy links between the child and parent tables.

We can define a foreign key into a table as follows:

1. CONSTRAINT constraint_name]    
2.     FOREIGN KEY [foreign_key_name] (col_name, ...)    
3.     REFERENCES parent_tbl_name (col_name,...)    

To read more information, click here.

12) What is a unique key?

A unique key is a single or combination of fields that ensure all values stores in the column will be unique. It means a column cannot
stores duplicate values. This key provides uniqueness for the column or set of columns. For example, the email addresses and roll
numbers of student's tables should be unique. It can accept a null value but only one null value per column. It ensures the integrity
of the column or group of columns to store different values into a table.

We can define a foreign key into a table as follows:

1. CREATE TABLE table_name(    
2.     col1 datatype,    
3.     col2 datatype UNIQUE,    
4.     ...    
5. );  

To read more information, click here.

13) What is the difference between a primary key and a unique key?
The primary key and unique key both are essential constraints of the SQL. The main difference among them is that the primary key
identifies each record in the table. In contrast, the unique key prevents duplicate entries in a column except for a NULL value. The
following comparison chart explains it more clearly:

Primary Key Unique Key

The primary key act as a unique identifier for each The unique key is also a unique identifier for records when the primary
record in the table. key is not present in the table.

We cannot store NULL values in the primary key We can store NULL value in the unique key column, but only one NULL
column. is allowed.

We cannot change or delete the primary key We can modify the unique key column values.
column values.

To read more information, click here.

14) What is a Database?

A database is an organized collection of data that is structured into tables, rows, columns, and indexes. It helps the user to find the
relevant information frequently. It is an electronic system that makes data access, data manipulation, data retrieval, data storing, and
data management very easy. Almost every organization uses the database for storing the data due to its easily accessible and high
operational ease. The database provides perfect access to data and lets us perform required tasks.

The following are the common features of a database:

o Manages large amounts of data


o Accurate
o Easy to update
o Security
o Data integrity
o Easy to research data

15) What is meant by DBMS?

DBMS stands for Database Management System. It is a software program that primarily functions as an interface between the
database and the end-user. It provides us the power such as managing the data, the database engine, and the database schema to
facilitate the organization and manipulation of data using a simple query in almost no time. It is like a File Manager that manages
data in a database rather than saving it in file systems. Without the database management system, it would be far more difficult for
the user to access the database's data.

The following are the components of a DBMS:


o Software
o Data
o Procedures
o Database Languages
o Query Processor
o Database Manager
o Database Engine
o Reporting

16) What are the different types of database management systems?

The database management systems can be categorized into several types. Some of the important lists are given below:

o Hierarchical databases (DBMS)


o Network databases (IDMS)
o Relational databases (RDBMS
o Object-oriented databases
o Document databases (Document DB)
o Graph databases
o ER model databases
o NoSQL databases

17) What is RDBMS?

RDBMS stands for Relational Database Management System. It is a database management system based on a relational model. It
facilitates you to manipulate the data stored in the tables by using relational operators. RDBMS stores the data into the collection of
tables and links those tables using the relational operators easily whenever required. Examples of relational database management
systems are Microsoft Access, MySQL, SQL Server, Oracle database, etc.

18) What is Normalization in a Database?

Normalization is used to minimize redundancy and dependency by organizing fields and table of a database.

There are some rules of database normalization, which is commonly known as Normal From, and they are:

o First normal form(1NF)


o Second normal form(2NF)
o Third normal form(3NF)
o Boyce-Codd normal form(BCNF)

Using these steps, the redundancy, anomalies, inconsistency of the data in the database can be removed.
19) What is the primary use of Normalization?

Normalization is mainly used to add, delete or modify a field that can be made in a single table. The primary use of Normalization is
to remove redundancy and remove the insert, delete and update distractions. Normalization breaks the table into small partitions
and then links them using different relationships to avoid the chances of redundancy.

20) What are the disadvantages of not performing database Normalization?

The major disadvantages are:

The occurrence of redundant terms in the database causes the waste of space in the disk.

Due to redundant terms, inconsistency may also occur. If any change is made in the data of one table but not made in the same data
of another table, then inconsistency will occur. This inconsistency will lead to the maintenance problem and effects the ACID
properties as well.

21) What is an inconsistent dependency?

An Inconsistent dependency refers to the difficulty of getting relevant data due to a missing or broken path to the data. It leads
users to search the data in the wrong table, resulting in an error as an output.

22) What is Denormalization in a Database?

Denormalization is a technique used by database administrators to optimize the efficiency of their database infrastructure. The
denormalization concept is based on Normalization, which is defined as arranging a database into tables correctly for a particular
purpose. This method allows us to add redundant data into a normalized database to alleviate issues with database queries that
merge data from several tables into a single table. It adds redundant terms into the tables to avoid complex joins and many other
complex operations.

Denormalization doesn't mean that normalization will not be done. It is an optimization strategy that takes place after the
normalization process.

23) What are the different types of SQL operators?

Operators are the special keywords or special characters reserved for performing particular operations. They are also used in SQL
queries. We can primarily use these operators within the WHERE clause of SQL commands. It's a part of the command to filters data
based on the specified condition. The SQL operators can be categorized into the following types:

o Arithmetic operators: These operators are used to perform mathematical operations on numerical data. The categories
of this operators are addition (+), subtraction (-), multiplication (*), division (/), remainder/modulus (%), etc.
o Logical operators: These operators evaluate the expressions and return their results in True or False. This operator
includes ALL, AND, ANY, ISNULL, EXISTS, BETWEEN, IN, LIKE, NOT, OR, UNIQUE.
o Comparison operators: These operators are used to perform comparisons of two values and check whether they are the
same or not. It includes equal to (=), not equal to (!= or <>), less than (<), greater than (>), less than or equal to (<=),
greater than or equal to (>=), not less than (!<), not greater than (!>), etc.
o Bitwise operators: It is used to do bit manipulations between two expressions of integer type. It first performs conversion
of integers into binary bits and then applied operators such as AND (& symbol), OR (|, ^), NOT (~), etc.
o Compound operators: These operators perform operations on a variable before setting the variable's result to the
operation's result. It includes Add equals (+=), subtract equals (-=), multiply equals (*=), divide equals (/=), modulo equals
(%=), etc.
o String operators: These operators are primarily used to perform concatenation and pattern matching of strings. It
includes + (String concatenation), += (String concatenation assignment), % (Wildcard), [] (Character(s) matches), [^]
(Character(s) not to match), _ (Wildcard match one character), etc.

24) What is a view in SQL?

A view is a database object that has no values. It is a virtual table that contains a subset of data within a table. It looks like an actual
table containing rows and columns, but it takes less space because it is not present physically. It is operated similarly to the base
table but does not contain any data of its own. Its name is always unique. A view can have data from one or more tables. If any
changes occur in the underlying table, the same changes reflected in the views also.

The primary use of a view is to implement the security mechanism. It is the searchable object where we can use a query to search the
view as we use for the table. It only shows the data returned by the query that was declared when the view was created.

We can create a view by using the following syntax:

1. CREATE VIEW view_name AS  
2. SELECT column_lists FROM table_name  
3. WHERE condition;  

25) What is an Index in SQL?

An index is a disc structure associated with a table or view that speeds up row retrieval. It reduces the cost of the query because the
query's high cost will lead to a fall in its performance. It is used to increase the performance and allow faster retrieval of records from
the table. Indexing reduces the number of data pages we need to visit to find a particular data page. It also has a unique value
meaning that the index cannot be duplicated. An index creates an entry for each value which makes it faster to retrieve data.

For example: Suppose we have a book which carries the details of the countries. If you want to find out information about India,
why will you go through every page of that book? You could directly go to the index. Then from the index, you can go to that
particular page where all the information about India is given.

26) What are the different types of indexes in SQL?

SQL indexes are nothing more than a technique of minimizing the query's cost. The higher the query's cost, the worse the query's
performance. The following are the different types of Indexes supported in SQL:

o Unique Index
o Clustered Index
o Non-Clustered Index
o Bit-Map Index
o Normal Index
o Composite Index
o B-Tree Index
o Function-Based Index

27) What is the unique index?

UNIQUE INDEX is used to enforce the uniqueness of values in single or multiple columns. We can create more than one unique
index in a single table. For creating a unique index, the user has to check the data in the column because the unique indexes are
used when any column of the table has unique values. This indexing does not allow the field to have duplicate values if the column is
unique indexed. A unique index can be applied automatically when a primary key is defined.

We can create it by using the following syntax:

1. CREATE UNIQUE INDEX index_name    
2. ON table_name (index_column1, index_column2,...);  

Example

1. CREATE TABLE Employee(      
2.     ID int AUTO_INCREMENT PRIMARY KEY,       
3.     Name varchar(45),     
4.     Phone varchar(15),    
5.     City varchar(25),   
6. );  

Suppose we want to make a Phone column as a unique index. We can do this like below:

1. CREATE UNIQUE INDEX index_name_phone ON Employee (Phone);    

To read more information, click here.

28) What is clustered index in SQL?

A clustered index is actually a table where the data for the rows are stored. It determines the order of the table data based on the
key values that can sort in only one direction. Each table can have only one clustered index. It is the only index, which has been
automatically created when the primary key is generated. If many data modifications needed to be done in the table, then clustered
indexes are preferred.

To read more information, click here.

29) What is the non-clustered index in SQL?

The indexes other than PRIMARY indexes (clustered indexes) are called non-clustered indexes. We know that clustered indexes are
created automatically when primary keys are generated, and non-clustered indexes are created when multiple joins conditions and
various filters are used in the query. The non-clustered index and table data are both stored in different places. It cannot be able to
alter the physical order of the table and maintains the logical order of data.

The purpose of creating a non-clustered index is for searching the data. Its best example is a book where the content is written in
one place, and the index is at a different place. We can create 0 to 249 non-clustered indexes in each table. The non-clustered
indexing improves the performance of the queries which use keys without assigning the primary key.

30) What are the differences between SQL, MySQL, and SQL Server?

The following comparison chart explains their main differences:

SQL MySQL SQL Server

SQL or Structured Query Language is MySQL is the popular database SQL Server is an RDBMS database
useful for managing our relational management system used for managing system mainly developed for the
databases. It is used to query and the relational database. It is a fast, Windows system to store, retrieve, and
operate the database. scalable, and easy-to-use database. access data requested by the developer.

SQL first appeared in 1974. MySQL first appeared on May 23, 1995. SQL Server first appeared on April 24,
1989.

SQL was developed by IBM MySQL was developed by Oracle SQL Server was developed by Microsoft
Corporation. Corporation. Company.

SQL is a query language for managing MySQL is database software that uses SQL Server is also a software that uses
databases. SQL language to conduct with the SQL language to conduct with the
database. database.

SQL has no variables. MySQL can use variables constraints and SQL Server can use variables constraints
data types. and data types.

SQL is a programming language, so MySQL is software, so it gets frequent SQL Server is also software, so it gets
that it does not get any updates. Its updation. frequent updation.
commands are always fixed and
remain the same.

31) What is the difference between SQL and PL/SQL?

The following comparison chart explains their main differences:

SQL PL/SQL

SQL is a database structured query language used PL/SQL or Procedural Language/Structured Query Language is a
to communicate with relational databases. It was dialect of SQL used to enhance the capabilities of SQL. Oracle
developed by IBM Corporations and first appeared Corporation developed it in the early 90's. It uses SQL as its database
in 1974. language.

SQL is a declarative and data-oriented language. PL/SQL is a procedural and application-oriented language.

SQL has no variables. PL/SQL can use variables constraints and data types.

SQL can execute only a single query at a time. PL/SQL can execute a whole block of code at once.

SQL query can be embedded in PL/SQL. PL/SQL cannot be embedded in SQL as SQL does not support any
programming language and keywords.

SQL can directly interact with the database server. PL/SQL cannot directly interact with the database server.

SQL is like the source of data that we need to PL/SQL provides a platform where SQL data will be shown.
display.
32) Is it possible to sort a column using a column alias?

Yes. We can use the alias method in the ORDER BY instead of the WHERE clause for sorting a column.

33) What is the difference between clustered and non-clustered indexes in SQL?

Indexing is a method to get the requested data very fast. There are mainly two types of indexes in SQL, clustered index and non-
clustered index. The differences between these two indexes are very important from an SQL performance perspective. The following
comparison chart explains their main differences:

Clustered Index Non-Clustered Index

A clustered index is a table or view where the data for the The indexes other than PRIMARY indexes (clustered indexes)
rows are stored. In a relational database, if the table column are called non-clustered indexes. It has a structure separate
contains a primary key, MySQL automatically creates a from the data row. The non-clustered indexes are also
clustered index named PRIMARY. known as secondary indexes.

Clustered indexes store the data information and the data Non-clustered indexes stores only the information, and then
itself. it will refer you to the data stored in clustered data.

There can only be one clustered index per table. There can be one or more non-clustered indexes in a table.

A clustered index determines how data is stored physically in It creates a logical ordering of data rows and uses pointers
the table. Therefore, reading from a clustered index is faster. for accessing the physical data files. Therefore, reading from
a clustered index is slower.

A clustered index always contains an index id of 0. A non-clustered index always contains an index id>0.

To read more information, click here.

34) What is the SQL query to display the current date?

There is a built-in function in SQL called GetDate(), which is used to return the current timestamp.

35) Which are joins in SQL? Name the most commonly used SQL joins?

SQL joins are used to retrieve data from multiple tables into a meaningful result set. It is performed whenever you need to fetch
records from two or more tables. They are used with SELECT statement and join conditions.

The following are the most commonly used joins in SQL:


o INNER JOIN
o LEFT OUTER JOIN
o RIGHT OUTER JOIN

36) What are the different types of joins in SQL?

Joins are used to merge two tables or retrieve data from tables. It depends on the relationship between tables. According to the
ANSI standard, the following are the different types of joins used in SQL:

o INNER JOIN
o SELF JOIN
o LEFT OUTER JOIN
o RIGHT OUTER JOIN
o FULL OUTER JOIN
o CROSS JOIN

To read more information, click here.

37) What is INNER JOIN in SQL?

Inner join returns only those records from the tables that match the specified condition and hides other rows and columns. In simple
words, it fetches rows when there is at least one match of rows between the tables is found. INNER JOIN keyword joins the matching
records from two tables. It is assumed as a default join, so it is optional to use the INNER keyword with the query.

The below visual representation explain this join more clearly:


The following syntax illustrates the INNER JOIN:

1. SELECT column_lists  
2. FROM table1    
3. INNER JOIN table2 ON join_condition1    
4. INNER JOIN table3 ON join_condition2    
5. ...;    

To read more information, click here.

38) What is the Right JOIN in SQL?

The Right join is used to retrieve all rows from the right-hand table and only those rows from the other table that fulfilled the join
condition. It returns all the rows from the right-hand side table even though there are no matches in the left-hand side table. If it
finds unmatched records from the left side table, it returns a Null value. This join is also known as Right Outer Join.

The below visual representation explain this join more clearly:


The following syntax illustrates the RIGHT JOIN:

1. SELECT colum_lists    
2. FROM table1     
3. RIGHT JOIN table2    
4. ON join_condition;  

To read more information, click here.

39) What is Left Join in SQL?

The Left Join is used to fetch all rows from the left-hand table and common records between the specified tables. It returns all the
rows from the left-hand side table even though there are no matches on the right-hand side table. If it will not find any matching
record from the right side table, then it returns null. This join can also be called a Left Outer Join.

The following visual representation explains it more clearly:


The following syntax illustrates the RIGHT JOIN:

1. SELECT colum_lists    
2. FROM table1     
3. LEFT JOIN table2    
4. ON join_condition;  

To read more information, click here.

40) What is Full Join in SQL?

The Full Join results from a combination of both left and right join that contains all the records from both tables. It fetches rows
when there are matching rows in any one of the tables. This means it returns all the rows from the left-hand side table and all the
rows from the right-hand side tables. If a match is not found, it puts NULL value. It is also known as FULL OUTER JOIN.

The following visual representation explains it more clearly:


The following syntax illustrates the FULL JOIN:

1. SELECT * FROM table1     
2. FULL OUTER JOIN table2    
3. ON join_condition;  

To read more information, click here.

41) What is a "TRIGGER" in SQL?

A trigger is a set of SQL statements that reside in a system catalog. It is a special type of stored procedure that is invoked
automatically in response to an event. It allows us to execute a batch of code when an insert, update or delete command is run
against a specific table because the trigger is the set of activated actions whenever DML commands are given to the system.

SQL triggers have two main components one is action, and another is an event. When certain actions are taken, an event occurs as a
result of those actions.

We use the CREATE TRIGGER statement for creating a trigger in SQL. Here is the syntax:

1. CREATE TRIGGER trigger_name      
2.     (AFTER | BEFORE) (INSERT | UPDATE | DELETE)    
3.          ON table_name FOR EACH ROW      
4.          BEGIN      
5.         --variable declarations      
6.         --trigger code      
7.         END;  

To read more information, click here.


42) What is self-join and what is the requirement of self-join?

A SELF JOIN is used to join a table with itself. This join can be performed using table aliases, which allow us to avoid repeating the
same table name in a single sentence. It will throw an error if we use the same table name more than once in a single query without
using table aliases.

A SELF JOIN is required when we want to combine data with other data in the same table itself. It is often very useful to convert a
hierarchical structure to a flat structure.

The following syntax illustrates the SELF JOIN:

1. SELECT column_lists    
2. FROM table1 AS T1, table1 AS T2    
3. WHERE join_conditions;    

Example

Suppose we have a table 'Student' having the following data:

If we want to get retrieve the student_id and name from the table where student_id is equal, and course_id is not equal, it can be
done by using the self-join:

1. SELECT  s1.student_id, s1.name    
2. FROM student AS s1, student s2    
3. WHERE s1.student_id=s2.student_id    
4. AND s1.course_id<>s2.course_id;    

Here is the result:

To read more information, click here.

43) What are the set operators in SQL?

We use the set operators to merge data from one or more tables of the same kind. Although the set operators are like SQL joins,
there is a significant distinction. SQL joins combine columns from separate tables, whereas SQL set operators combine rows from
different queries. SQL queries that contain set operations are called compound queries. The set operators in SQL are categories into
four different types:

A. UNION: It combines two or more results from multiple SELECT queries into a single result set. It has a default feature to remove
the duplicate rows from the tables. The following syntax illustrates the Union operator:

1. SELECT columns FROM table1    
2. UNION    
3. SELECT columns FROM table2;    

B. UNION ALL: This operator is similar to the Union operator, but it does not remove the duplicate rows from the output of the
SELECT statements. The following syntax illustrates the UNION ALL operator:

1. SELECT columns FROM table1    
2. UNION  ALL  
3. SELECT columns FROM table2;    

C. INTERSECT: This operator returns the common records from two or more SELECT statements. It always retrieves unique records
and arranges them in ascending order by default. Here, the number of columns and data types should be the same. The following
syntax illustrates the INTERSECT operator:

1. SELECT columns FROM table1    
2. INTERSECT  
3. SELECT columns FROM table2;    

D. MINUS: This operator returns the records from the first query, which is not found in the second query. It does not return
duplicate values. The following syntax illustrates the MINUS operator:

1. SELECT columns FROM table1    
2. MINUS  
3. SELECT columns FROM table2;    

To read more information, click here.


44) What is the difference between IN and BETWEEN operators?

The following comparison chart explains their main differences:

BETWEEN Operator IN Operator

This operator is used to selects the range of data It is a logical operator to determine whether or not a specific value
between two values. The values can be numbers, exists within a set of values. This operator reduces the use of multiple
text, and dates as well. OR conditions with the query.

It returns records whose column value lies in It compares the specified column's value and returns the records
between the defined range. when the match exists in the set of values.

The following syntax illustrates this operator: The following syntax illustrates this operator:
SELECT * FROM table_name SELECT * FROM table_name
WHERE column_name BETWEEN 'value1' AND WHERE column_name IN ('value1','value 2');
'value2';

45) What is a constraint? Tell me about its various levels.

The constraint is used to specify the rule and regulations that allows or restricts what values/data will be stored in the table. It
ensures data accuracy and integrity inside the table. It enforces us to store valid data and prevents us from storing irrelevant data. If
any interruption occurs between the constraint and data action, the action is failed. Some of the most commonly used constraints
are NOT NULL, PRIMARY KEY, FOREIGN KEY, AUTO_INCREMENT, UNIQUE KEY, etc.

The following syntax illustrates us to create a constraint for a table:

1. CREATE TABLE table_name (    
2.     column1 datatype constraint,    
3.     column2 datatype constraint,   
4.     .........    
5. );    

SQL categories the constraints into two levels:

Column Level Constraints: These constraints are only applied to a single column and limit the type of data that can be stored in
that column.

Table Level Constraints: These constraints are applied to the entire table and limit the type of data that can be entered.

To read more information, click here.


46) How to write an SQL query to find students' names start with 'A'?

We can write the following query to get the student details whose name starts with A:

1. SELECT * FROM student WHERE stud_name like 'A%';  

Here is the demo example where we have a table named student that contains two names starting with the 'A' character.

47) Write the SQL query to get the third maximum salary of an employee from a table named
employees.

The following query is the simplest way to get the third maximum salary of an employee:

1. SELECT * FROM `employees` ORDER BY `salary` DESC LIMIT 1 OFFSET 2  

Here is the demo example that shows how to get the third maximum salary of an employee.
The following are the alternative way to get the third-highest salary of an employee:

A. Using LIMIT Keyword

1. SELECT salary FROM employees   
2. ORDER BY salary DESC   
3. LIMIT 2, 1;  

B. Using Subquery

1. SELECT salary    
2. FROM   
3.     (SELECT salary   
4.      FROM employees   
5.      ORDER BY salary DESC   
6.      LIMIT 3) AS Temp   
7. ORDER BY salary LIMIT 1;  

C. Using TOP Keyword

1. SELECT TOP 1 salary   
2. FROM   
3.     (SELECT DISTINCT TOP 3 salary   
4.      FROM employees   
5.      ORDER BY salary DESC) AS Temp   
6. ORDER BY salary ASC;  

48) What is the difference between DELETE and TRUNCATE statements in SQL?

The main difference between them is that the delete statement deletes data without resetting a table's identity, whereas the truncate
command resets a particular table's identity. The following comparison chart explains it more clearly:

No. DELETE TRUNCATE

1) The delete statement removes single or multiple rows The truncate command deletes the whole contents of an
from an existing table depending on the specified existing table without the table itself. It preserves the table
condition. structure or schema.

2) DELETE is a DML command. TRUNCATE is a DML command.

3) We can use the WHERE clause in the DELETE We cannot use the WHERE clause with TRUNCATE.
command.

4) DELETE statement is used to delete a row from a TRUNCATE statement is used to remove all the rows from a
table. table.

5) DELETE is slower because it maintained the log. TRUNCATE statement is faster than DELETE statement as it
deletes entire data at a time without maintaining transaction
logs.

6) You can roll back data after using the DELETE It is not possible to roll back after using the TRUNCATE
statement. statement.

7) DELETE query takes more space. TRUNCATE query occupies less space.

To read more information, click here.

49) What is the ACID property in a database?

The ACID properties are meant for the transaction that goes through a different group of tasks. A transaction is a single logical order
of data. It provides properties to maintain consistency before and after the transaction in a database. It also ensures that the data
transactions are processed reliably in a database system.

The ACID property is an acronym for Atomicity, Consistency, Isolation, and Durability.

Atomicity: It ensures that all statements or operations within the transaction unit must be executed successfully. If one part of the
transaction fails, the entire transaction fails, and the database state is left unchanged. Its main features are COMMIT, ROLLBACK, and
AUTO-COMMIT.
Consistency: This property ensures that the data must meet all validation rules. In simple words, we can say that the database
changes state only when a transaction will be committed successfully. It also protects data from crashes.

Isolation: This property guarantees that the concurrent property of execution in the transaction unit must be operated
independently. It also ensures that statements are transparent to each other. The main goal of providing isolation is to control
concurrency in a database.

Durability: This property guarantees that once a transaction has been committed, it persists permanently even if the system crashes,
power loss, or failed.

To read more information, click here.

50) Is a blank space or zero the same as a NULL value?

No. The NULL value is not the same as zero or a blank space. The following points explain their main differences:

o A NULL value is a value, which is 'unavailable, unassigned, unknown or not applicable.' It would be used in the absence of
any value. We can perform arithmetic operations on it. On the other hand, zero is a number, and a blank space is treated
as a character.
o The NULL value can be treated as an unknown and missing value, but zero and blank spaces differ from the NULL value.
o We can compare a blank space or a zero to another blank space or a zero. On the other hand, one NULL may not be the
same as another NULL. NULL indicates that no data has been provided or that no data exists.

51) What are functions and their usage in SQL?

SQL functions are simple code snippets that are frequently used and re-used in database systems for data processing and
manipulation. Functions are the measured values. It always performs a specific task. The following rules should be remembered while
creating functions:

o A function should have a name, and the name cannot begin with a special character such as @, $, #, or other similar
characters.
o Functions can only work with the SELECT statements.
o Every time a function is called, it compiles.
o Functions must return value or result.
o Functions are always used with input parameters.

SQL categories the functions into two types:

o User-Defined Function: Functions created by a user based on their needs are termed user-defined functions.
o System Defined Function: Functions whose definition is defined by the system are termed system-defined functions.
They are built-in database functions.

SQL functions are used for the following purposes:

o To perform calculations on data


o To modify individual data items
o To manipulate the output
o To format dates and numbers
o To convert data types

52) What is meant by case manipulation functions? Explains its different types in SQL.

Case manipulation functions are part of the character functions. It converts the data from the state in which it is already stored in the
table to upper, lower, or mixed case. The conversion performed by this function can be used to format the output. We can use it in
almost every part of the SQL statement. Case manipulation functions are mostly used when you need to search for data, and you
don't have any idea that the data you are looking for is in lower case or upper case.

There are three case manipulation functions in SQL:

LOWER: This function is used to converts a given character into lowercase. The following example will return the 'STEPHEN' as
'stephen':

1. SELECT LOWER ('STEPHEN') AS Case_Reault FROM dual;  

NOTE: Here, 'dual' is a dummy table.

UPPER: This function is used to converts a given character into uppercase. The following example will return the 'stephen' as
'STEPHEN':

1. SELECT UPPER ('stephen') AS Case_Reault FROM dual;  

INITCAP: This function is used to converts given character values to uppercase for the initials of each word. It means every first letter
of the word is converted into uppercase, and the rest is in lower case. The following example will return the 'hello stephen' as 'Hello
Stephen':

1. SELECT INITCAP ('hello stephen') AS Case_Reault FROM dual;  

53) Explain character-manipulation functions? Explains its different types in SQL.

Character-manipulation functions are used to change, extract, and alter the character string. When one or more characters and
words are passed into the function, the function will perform its operation on those input strings and return the result.

The following are the character manipulation functions in SQL:

A) CONCAT: This function is used to join two or more values together. It always appends the second string into the end of the first
string. For example:

Input: SELECT CONCAT ('Information-', 'technology') FROM DUAL;

Output: Information-technology

B) SUBSTR: It is used to return the portion of the string from a specified start point to an endpoint. For example:
Input: SELECT SUBSTR ('Database Management System', 9, 11) FROM DUAL;

Output: Management

C) LENGTH: This function returns the string's length in numerical value, including the blank spaces. For example:

Input: SELECT LENGTH ('Hello Javatpoint') FROM DUAL;

Output: 16

D) INSTR: This function finds the exact numeric position of a specified character or word in a given string. For example:

Input: SELECT INSTR ('Hello Javatpoint', 'Javatpoint');

Output: 7

E) LPAD: It returns the padding of the left-side character value for right-justified value. For example:

Input: SELECT LPAD ('200', 6,'*');

Output: ***200

F) RPAD: It returns the padding of the right-side character value for left-justified value. For example:

Input: SELECT RPAD ('200', 6,'*');

Output: 200***

G) TRIM: This function is used to remove all the defined characters from the beginning, end, or both. It also trimmed extra spaces.
For example:

Input: SELECT TRIM ('A' FROM 'ABCDCBA');

Output: BCDCB

H) REPLACE: This function is used to replace all occurrences of a word or portion of the string (substring) with the other specified
string value. For example:

Input: SELECT REPLACE ( 'It is the best coffee at the famous coffee shop.', 'coffee', 'tea');

Output: It is the best tea at the famous tea shop.

54) What is the usage of the NVL() function?

The NVL() function is used to convert the NULL value to the other value. The function returns the value of the second parameter if
the first parameter is NULL. If the first parameter is anything other than NULL, it is left unchanged. This function is used in Oracle, not
in SQL and MySQL. Instead of NVL() function, MySQL have IFNULL() and SQL Server have ISNULL() function.
55) Which function is used to return remainder in a division operator in SQL?

The MOD function returns the remainder in a division operation.

56) What are the syntax and use of the COALESCE function?

The COALESCE() function evaluates the arguments in sequence and returns the first NON-NULL value in a specified number of
expressions. If it evaluates arguments as NULL or not found any NON-NULL value, it returns the NULL result.

The syntax of COALESCE function is given below:

1. COALESCE (exp1, exp2, .... expn)   

Example:

1. SELECT COALESCE(NULL, 'Hello', 'Javatpoint', NULL) AS Result;  

This statement will return the following output:

57) How do we use the DISTINCT statement? What is its use?

The DISTINCT keyword is used to ensure that the fetched value always has unique values. It does not allow to have duplicate values.
The DISTINCT keyword is used with the SELECT statement and retrieves different values from the table's column. We can use it with
the help of the following syntax:

1. SELECT DISTINCT column_lists FROM table_name WHERE [condition];  

Suppose we have a table 'customer' containing eight records in which the name column has some duplicate values.
If we want to get the name column without any duplicate values, the DISTINCT keyword is required. Executing the below command
will return a name column with unique values.

58) What is the default ordering of data using the ORDER BY clause? How could it be changed?

The ORDER BY clause is used to sort the table data either in ascending or descending order. By default, it will sort the table in
ascending order. If we want to change its default behavior, we need to use the DESC keyword after the column name in the ORDER
BY clause.

The syntax to do this is given below:

1. SELECT expressions FROM tables    
2. WHERE conditions    
3. ORDER BY expression [ASC | DESC];    

We have taken a customer table in the previous example. Now, we will demonstrate the ORDER BY clause on them as well.

In the below output, we can see that the first query will sort the table data in ascending order based on the name column. However,
if we run the second query by specifying the DESC keyword, the table's order is changed in descending order.
59) Is the following query returns the output?

1. SELECT subject_code, AVG (marks)  
2. FROM Students  
3. WHERE AVG(marks) > 70  
4. GROUP BY subject_code;  

Answer: No. The above query does not return the output because we cannot use the WHERE clause to restrict the groups. We need
to use the HAVING clause instead of the WHERE clause to get the correct output.

60) What is the difference between the WHERE and HAVING clauses?

The main difference is that the WHERE clause is used to filter records before any groupings are established, whereas the HAVING
clause is used to filter values from a group. The below comparison chart explains the most common differences:
WHERE HAVING

This clause is implemented in row operations. This clause is implemented in column operations.

It does not allow to work with aggregate functions. It can work with aggregate functions.

This clause can be used with the SELECT, UPDATE, and DELETE This clause can only be used with the SELECT
statements. statement.

To know more differences, click here.

61) How many Aggregate functions are available in SQL?

The aggregate function is used to determine and calculate several values in a table and return the result as a single number. For
example, the average of all values, the sum of all values, and the maximum and minimum value among particular groupings of
values.

The following syntax illustrates how to use aggregate functions:

1. function_name (DISTINCT | ALL expression)    

SQL provides seven (7) aggregate functions, which are given below:

o AVG(): This function is used to returns the average value from specified columns.
o COUNT(): This function is used to returns the number of table rows, including rows with null values.
o MAX(): This function is used to returns the largest value among the group.
o MIN(): This function is used to returns the smallest value among the group.
o SUM(): This function is used to returns the total summed values(non-null) of the specified column.
o FIRST(): This function is used to returns the first value of an expression.
o LAST(): This function is used to returns the last value of an expression.

62) What is SQL Injection?

SQL injection is a type of vulnerability in website and web app code that allows attackers to control back-end operations and access,
retrieve, and destroy sensitive data from databases. In this technique, malicious SQL statements are inserted into a database entry
field, and once they are performed, the database becomes vulnerable to an attacker. This technique is commonly used to access
sensitive data and perform administrative activities on databases by exploiting data-driven applications. It is also known as  SQLi
attack.

Some common examples of SQL injection are:

o Accessing confidential data to modify an SQL query to get desired results.


o UNION attacks to steal data from different database tables.
o Examine the database to extract information regarding the version and structure of the database.

63) What is the difference between the RANK() and DENSE_RANK() functions?

The RANK function determines the rank for each row within your ordered partition in the result set. If the two rows are assigned the
same rank, then the next number in the ranking will be its previous rank plus a number of duplicate numbers. For example, if we
have three records at rank 4, the next rank listed would be ranked 7.

The DENSE_RANK function assigns a unique rank for each row within a partition as per the specified column value without any gaps.
It always specifies ranking in consecutive order. If the two rows are assigned the same rank, this function will assign it with the same
rank, and the next rank being the next sequential number. For example, if we have 3 records at rank 4, the next rank listed would be
ranked 5.

64) Is it possible to implicitly insert a row for the identity column?

Yes. We can implicitly insert a row for the identity column. Here is an example of doing this:

1. SET IDENTITY_INSERT TABLE1 ON  
2. INSERT INTO demo_table1 (id, name, branch)  
3. SELECT id, name, branch FROM demo_table2  
4. SET IDENTITY_INSERT OFF  

65) What are SQL comments?

Comments are explanations or annotations in SQL queries that are readable by programmers. It's used to make SQL statements
easier to understand for humans. During the parsing of SQL code, it will be ignored. Comments can be written on a single line or
across several lines.

o Single Line Comments: It starts with two consecutive hyphens (--).


o Multi-line Comments: It starts with /* and ends with */.

You might also like