11/15/16

SQL Interview Questions & Answers


Q. What is SQL?
 
Structured Query Language, an ANSI (American National Standards Institute) standard language for accessing databases.

Using SQL we can Access Oracle, Sybase, DB2, SQL Server, MySQL, DB/400 and other Database Management Systems
 

Q. When SQL was appeared?

Structured Query Language was first appeared by IBM in 1974 and it is Free Software(any body can use with free of cost).


Q. Who should learn SQL?

• Database Developers

• Database Testers

• Database Administrators



Q. What are the Usages of SQL?

•    Creating new databases
•    Creating new tables in a database
•    Inserting records in a database
•    Updating records in a database
•    Deleting records from a database
•    Retrieving data from a database
•    Executing queries against a database
•    Creating stored procedures in a database
•    Creating views in a database
•    Setting permissions on tables, procedures, and views
Etc…
 

Q) What are important SQL Language Elements?


Identifiers: Names of Database objects such as tables, views, columns, and databases etc...

Data Types: Define the type of data that is contained by a column. 

Constants: Symbols that represent specific data types.

Operators: Perform Arithmetic, Comparison, and Logical Operations.

Functions: Built-in Functions to perform specific operations.

Clauses: Constituent components of statements and queries. 

Expressions: Produce either scalar values, or tables consisting of columns and rows of data.

Queries: Retrieve the data based on specific criteria. This is an important element of SQL.
Statements: 

Q. What is SQL Process?

When we are executing an SQL command for any RDBMS, the system determines the best way to carry out our request and SQL engine figures out how to interpret the task.
There are various components included in the process. These components are Query Dispatcher, Optimization engines, Classic Query Engine and SQL query engine etc. Classic query engine handles all non-SQL queries but SQL query engine won't handle logical files.
 

Q. Is SQL supports Programming?
 

No, SQL doesn’t have Conditional and Loop statements, using SQL Commands we can access databases. 

Q. What are the sub sets of SQL?
 

•    Data Definition Language
•    Data Manipulation Language
•    Data Control Language
 

Q. What is Data Definition Language?
 

Data Definition Language (DDL) allows us to create, alter, and delete database objects such as schemas, tables, views, sequences, catalogs, indexes, and aliases.

Q. What is Data Manipulation Language?
 

DML is a language which enables users to access and manipulate data. 

Data Manipulation Language is used to Perform below Operations:
•    Insertion of data into the database 
•    Retrieval of data from the database 
•    Updating data in the database 
•    Deletion of data in the database
 


Q. What is Data Control Language?
 

Data Control Language (DCL) allows us to control access to the database. 'DCL' commands include- 
'GRANT' to allow specific users to perform specified tasks 
'REVOKE' to cancel previously denied or granted permissions


Q. What is Database?

A database is a systematic collection of data, Databases support storage and manipulation of data, and Databases make data management easy.

Q. What is Table?

A Table in a Relational Database is a predefined format of rows and columns that define an entity. 
Each column contains a different type of attribute and each row corresponds to a single record. 
Each table is provided with a name. 

Q. What is DBMS?

> A database management system, or DBMS, is software designed to assist in maintaining and utilizing large collection of data. 

> The alternative to using a DBMS is to store the data in files and write application-specific code to manage it.

Using a DBMS to manage data has many advantages like:

•    Data independence
•    Efficient data access
•    Data integrity and security
•    Data administration
•    Concurrent access and data recovery 

Q. What is MS Access?
 

MS Access was launched in 1992 by Microsoft Corporation as part of MS Office.
Microsoft Access is entry-level database management software. It is not only an inexpensive but also powerful database for small-scale projects.
MS Access uses the Jet database engine which utilizes a specific SQL language dialect (sometimes referred to as Jet SQL).
MS Access comes with the professional edition of MS Office package. MS Access is user friendly database management system.
 

Q. What is Oracle?

Oracle is a relational database management system developed by 'Oracle Corporation and launched in 1977.
Oracle supports all major Operating systems includes, MS Windows. NetWare, UnixWare, OS/2 and most UNIX flavors.
 

Q. What is MS SQL Server?
 

MS SQL Server is a Relational Database Management System developed by Microsoft Inc. Its primary query languages are T-SQL and ANSI SQL. 

Q. What is Sybase?

Sybase is a computer software company , their primary product is Sybase DBMS, which is a relational database management system based upon structured query language.
 

Q. What is MySQL?
 

MySQL is open source Database Management System, developed by Swedish company MySQL AB. 
MySQL Supports many different platforms including Microsoft Windows, the major Linux distributions, UNIX, and Mac OS X.
MySQL has free and paid versions, depending on its usage (non-commercial/commercial) and features. MySQL comes with a very fast, multi-threaded, multi-user, and robust SQL database server.


Q. What is DB2? 

DB2 is the short name used for DATABASE 2. It is relational database product developed by IBM. in 1983 

Q. What is DB/400?

It is one of the flavors of IBM DB2
 

Q. What are the categories of operators available in SQL?
 

•    Arithmetic operators
•    Comparison operators
•    Logical operators
 
Q. What are Arithmetic operators in SQL? 

Operator
Description
+ (Addition )
Adds values
- (Subtraction)
Subtracts Right side value from Left side value
* (Multiplication)
Multiplies values on either side of the operator
/ (Division)
Divides left hand operand by right hand operand
% (Modulus)
Divides left hand operand by right hand operand and returns remainder



Q. What are Comparison operators in SQL?

For example x = 1, y= 2

Operator    Example
=             (x = y) is False
!=            (x != y) is True. 
<>           (x <> y) is true. 
>             (x > y) is False
<             (x < y) is True        
>=           (x >= y) is False
<=           (x <= y) is True
!<            (x !< y) is False
!>            (x !> y) is True. 

Note: Comparison Operators return Logical Results

Q. What are Logical operators in SQL?  

Operator    Description 
--------        -----------

NOT           Returns TRUE if the following condition is FALSE. Returns FALSE if  it is TRUE.  
AND           Returns TRUE if both component conditions are TRUE. Returns FALSE if either is FALSE 
OR            Returns TRUE if either component condition is TRUE. Returns FALSE if both are FALSE.


Q. What is a Data Relationship and What are they?

Database Relationship is the connection between the tables in a database. There are 4 types of relationships, and they are:

•    One to One Relationship
•    One to Many Relationship
•    Many to One Relationship
•    Many to Many Relationship


Q. What are Important Data Types in SQL?



Data Type
Syntax
character
char(x)
integer
integer
numeric
numeric(p,s)
decimal
decimal(p,s)
float
float(p)
date
date
time
time
character varying
varchar2(x)
bit
bit(x)
real
real
smallint
smallint


Q. How to Create a Database?

The SQL CREATE DATABASE statement is used to create new SQL database.

Syntax:

CREATE DATABASE DatabaseName;

Example: 

SQL> CREATE DATABASE TestData;

Q. How to delete a Database?

Using DROP DATABASE statement we can delete any existing Database

Syntax:

DROP DATABASE DatabaseName;

Example:

SQL> DROP DATABASE TestData;


Q. How to Select a Database?

USE statement is used to select any existing database in SQL

Syntax:

USE DatabaseName;

Example:

SQL> USE TestData;

Q. How to view all existing Databases list?

SQL> SHOW DATABASES;

Q. How to create a Table?


CREATE TABLE table_name(
   column1 datatype,
   column2 datatype,
   column3 datatype,
   .....
   columnN datatype,
   PRIMARY KEY( one or more columns )
);

Q. How to delete a Table?

Using Drop Table we can delete a Table

Syntax:

DROP TABLE table_name;

Q. How to add new record into a Table?

Using INSERT INTO statement, we can insert new rows

Syntax:

INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)
VALUES (value1, value2, value3,...valueN)

Q. How to fetch data from a Database Table?
 

Using SELECT Statement, we can fetch data from a Database Table

Syntax:

SELECT column1, column2, columnN FROM table_name;

Or

SELECT * FROM table_name;


Q. Explain about IN Operator?

The IN operator implements comparison to a list of values, that is, it tests whether a value matches any value in a list of values. IN comparisons have the following general format:
value-1 [NOT] IN ( value-2 [, value-3] ... )
This comparison tests if value-1 matches value-2 or matches value-3, and so on. It is equivalent to the following logical predicate:
value-1 = value-2 [ OR value-1 = value-3 ] ...

Q. Explain about FROM Clause in SQL?

The FROM clause always follows the SELECT clause. It lists the tables accessed by the query. For example,
SELECT * FROM s
When the From List contains multiple tables, commas separate the table names. For example,
SELECT sp.*, city
FROM sp, s
WHERE sp.sno=s.sno
When the From List has multiple tables, they must be joined together.

Q. What is the parameter substitution symbol used with INSERT INTO command?


The parameter substitution symbol used with INSERT INTO command is &.

Q. What are the various uses of database triggers?

Database triggers can be used to enforce business rules, to maintain derived values and perform value-based auditing. 


Q. What is a event handler in sql?

An event handler is a routine that is written to respond to a particular event.

Q. What are two methods of retrieving SQL?

The two methods of retrieving SQL are 
1-Select
2-using Cursor.

Q. What is a synonym? How is it used?

A synonym is used to reference a table or view by another name. The other name can then be written in the application code pointing to test tables in the development stage and to production entities when the code is migrated. The synonym is linked to the AUTHID that created it. 


Q. What is referential integrity?
 

Referential integrity refers to the consistency that must be maintained between primary and foreign keys, i.e. every foreign key value must have a corresponding primary key value.

Q. Explain the EXPLAIN statement?
 

The explain statement provides information about the optimizer's choice of access path of the SQL.

Q. How is the SUBSTR keyword used in SQL?

 

SUBSTR is used for string manipulation with column name, first position and string length used as arguments. E.g. SUBSTR (NAME, 1 3) refers to the first three characters in the column NAME.

Q. What is the difference between group by and order by?
 

Group by controls the presentation of the rows, order by controls the presentation of the columns for the results of the SELECT statement.

Q. What is a subselect? Is it different from a nested select?
 

A subselect is a select which works in conjunction with another select. A nested select is a kind of subselect where the inner select passes to the where criteria for the outer select.

Q. What is the use of CASCADE CONSTRAINTS?
 

When this clause is used with the DROP command, a parent table can be dropped even when a child table exists.

Q. How do you prevent output from coming to the screen?
 

The SET option TERMOUT controls output to the screen. Setting TERMOUT OFF turns off screen output. This option can be shortened to TERM.
 

Q. Can Primary key is a Foreign Key on the same table?

Yes, Primary key is a Foreign Key on the same table.

Q. How do you execute a host operating system command from within SQL?
 

By use of the exclamation point “!” (in UNIX and some other OS) or the HOST (HO) command.

Q. What is a Cartesian product?
 

A Cartesian product is the result of an unrestricted join of two or more tables. The result set of a three table Cartesian product will have x * y * z number of rows where x, y, z correspond to the number of rows in each table involved in the join.

Q. How can variables be passed to a SQL routine?

 

By use of the & symbol. For passing in variables the numbers 1-8 can be used (&1, &2,...,&8) to pass the values after the command into the SQL PLUS session. To be prompted for a specific variable, place the ampersanded variable in the code itself: “select * from dba_tables where owner=&owner_name;” . Use of double ampersands tells SQLPLUS to resubstitute the value for each subsequent use of the variable, a single ampersand will cause a reprompt for the value unless an ACCEPT statement is used to get the value from the user.

Q. What command is used to get back the privileges offered by the GRANT command?
 

Revoke command is used to get back the privileges offered by the GRANT command.

Q. What are the advantages of procedures?

Advantages of procedures:

• Loaded once and used many times.
• Performance better coz all SQL statements are sent in one go from the application to the database.
• Security (no object privileges are given directly).
• Invoker's rights possible.
• Data integrity, productivity.

Q. What is Parsing?
 

Parsing checks syntax, checks privileges, and allocating Private SQL Area.

Q. What is Cursor?

Name or handle to a private SQL area where Oracle parses and fetches query results.


Q) Is SQL supports Conditional and Loop Statements?

No Basically SQL is a Command based Language, not a procedural  language, but it has Operators and built-in Functions.


1) What are most important DDL Commands in SQL?

CREATE TABLE - creates a new database table
ALTER TABLE - alters (changes) a database table
DROP TABLE - deletes a database table
CREATE INDEX - creates an index (search key)
DROP INDEX - deletes an index 

2) What are the Operators used in SELECT statements?

= Equal

<> or != Not equal

> Greater than

< Less than

>= Greater than or equal

<= Less than or equal

BETWEEN Between an inclusive range LIKE Search for a pattern


3) How to  INSERT Values into Tables?

INSERT INTO table_name VALUES (value1, value2,....)

INSERT INTO table_name (column1, column2,...) VALUES (value1, value2,....)

4) How to Update a Column Name?

UPDATE table_name SET column_name = new_value WHERE column_name = some_value

5) How to Delete Columns, Rows?

Delete a particular column:

DELETE FROM table_name WHERE column_name = some_value

Delete All Rows:

DELETE FROM table_name or DELETE * FROM table_name


6) Give an usage for BETWEEN ... AND?

SELECT column_name FROM table_name WHERE column_name BETWEEN value1 AND value2 The values can be numbers, text, or dates.

7) What is the use of CASCADE CONSTRAINTS?

When this clause is used with the DROP command, a parent table can be dropped even when a child table exists.

8) Why does the following command give a compilation error?

DROP TABLE &TABLE NAME;

Variable names should start with an alphabet. Here the table name starts with an '&' symbol.

9) Which system tables contain information on privileges granted and privileges obtained?

USER_TAB_PRIVS_MADE, USER_TAB_PRIVS_RECD 

10) Which system table contains information on constraints on all the tables created?obtained?

USER_CONSTRAINTS. 


11) State true or false. EXISTS, SOME, ANY are operators in SQL?

True.


12) What does the following query do?

SELECT SAL + NVL(COMM,0) FROM EMP;?

This displays the total salary of all employees. The null values in the commission column will be replaced by 0 and added to salary.

13) What is the advantage of specifying WITH GRANT OPTION in the GRANT command?

The privilege receiver can further grant the privileges he/she has obtained from the owner to any other user.

14) Which command executes the contents of a specified file?

START or @. 

15) Which command displays the SQL command in the SQL buffer, and then executes it?

RUN. 

16) What command is used to get back the privileges offered by the GRANT command?

REVOKE. 

17) Which date function is used to find the difference between two dates?

MONTHS_BETWEEN. 

18) What operator performs pattern matching?

LIKE operator. 

19) What is the use of the DROP option in the ALTER TABLE command?

It is used to drop constraints specified on the table. 

20) What operator tests column for the absence of data?

IS NULL operator. 

21) What are the privileges that can be granted on a table by a user to others?

Insert, update, delete, select, references, index, execute, alter, all. 

22) Which function is used to find the largest integer less than or equal to a specific value?

FLOOR. 

23) Which is the subset of SQL commands used to manipulate Oracle Database structures, including tables?

Data Definition Language (DDL).

24) What is the use of DESC in SQL?

DESC has two purposes. It is used to describe a schema as well as to retrieve rows from table in descending order.

Explanation :

The query SELECT * FROM EMP ORDER BY ENAME DESC will display the output sorted on ENAME in descending order.

25) What command is used to create a table by copying the structure of another table?

CREATE TABLE .. AS SELECTcommand

Explanation:

To copy only the structure, the WHERE clause of the SELECT command should contain a FALSE statement as in the following.

CREATE TABLE NEWTABLE AS SELECT * FROM EXISTINGTABLE WHERE 1=2;

If the WHERE condition is true, then all the rows or rows satisfying the condition will be copied to the new table.


26) What is the output of the following query SELECT TRUNC(1234.5678,-2) FROM DUAL;?

1200. 

27) What are the wildcards used for pattern matching.?

_ for single character substitution
% for multi-character substitution.


28) What's an SQL injection?

SQL Injection is when form data contains an SQL escape sequence and injects a new SQL query to be run.

29) What is difference between TRUNCATE & DELETE?

TRUNCATE commits after deleting entire table i.e., cannot be rolled back. Database triggers do not fire on TRUNCATE

DELETE allows the filtered deletion. Deleted records can be rolled back or committed. Database triggers fire on DELETE.

30) What is a join? Explain the different types of joins?

Join is a query, which retrieves related columns or rows from multiple tables.


Self Join - Joining the table with itself.

Equi Join - Joining two tables by equating two common columns. Non-Equi Join - Joining two tables by equating two common columns.

Outer Join - Joining two tables in such a way that query can also retrieve rows that do not have corresponding join value in the other table.

31) What is the sub-query?

Sub-query is a query whose return values are used in filtering conditions of the main query.

32) What is correlated sub-query?

Correlated sub-query is a sub-query, which has reference to the main query.

33) Explain CONNECT BY PRIOR?

Retrieves rows in hierarchical order eg. select empno, ename from emp where. 

34) Difference between SUBSTR and INSTR?

INSTR (String1, String2 (n, (m)), 

INSTR returns the position of the m-th occurrence of the string 2 in string1. The search begins from nth position of string1. 

SUBSTR (String1 n, m) 

SUBSTR returns a character string of size m in string1, starting from n-th position of string1. 

35) Explain UNION, MINUS, UNION ALL and INTERSECT?

INTERSECT - returns all distinct rows selected by both queries.

MINUS - returns all distinct rows selected by the first query but not by the second.

UNION - returns all distinct rows selected by either query

UNION ALL - returns all rows selected by either query,including all duplicates.

36) What is ROWID?

ROWID is a pseudo column attached to each row of a table. It is 18 characters long, blockno, rownumber are the components of ROWID.

37) What is the fastest way of accessing a row in a table?

Using ROWID. CONSTRAINTS 

38) What is an integrity constraint?

Integrity constraint is a rule that restricts values to a column in a table.

39) What is referential integrity constraint?

Maintaining data integrity through a set of rules that restrict the values of one or more columns of the tables based on the values of primary key or unique key of the referenced table.

Google Q&A Forum