Google News
logo
SQL Interview Questions
SQL stands for Structured Query Language , and it is used to communicate with the Database. SQL initially was invented in 1970. It is a database language used for creation, deletion, fetching rows and modifying rows from a database etc,. 
 
Standard SQL Commands are Select.
Database is nothing but an organized form of data for easy access, storing, retrieval and managing of data. This is also known as structured form of data which can be accessed in many ways. Where databases are more complex they are often developed using formal design and modeling techniques.
 
Example: Hospital Management System Database, School Management Database, Bank Management Database, etc,.
DBMS stands for Database Management System. DBMS is a system software responsible for the creation, retrieval, updation and management of the database. It ensures that our data is consistent, organized and is easily accessible by serving as an interface between the database and its end users or application softwares.
It appeared in 1974. SQL is one of the often used languages for maintaining the relational database. SQL. In 1986 SQL become the standard of American National Standards Institute (ANSI) and ISO(International Organization for Standardization) in 1987.
SQL is responsible for maintaining the relational data and the data structures present in the database.

* To execute queries against a database
* To retrieve data from a database
* To inserts records in a database
* To updates records in a database
* To delete records from a database
* To create new databases
* To create new tables in a database
* To create views in a database
* To perform complex operations on the database.
DBMSs are software applications that help you build and maintain databases. RDBMS is a subset of DBMS, and it is a database management system based on the relational model of the DBMS.
SQL
* It is more scalable and secure than Oracle
* It widely supports procedural extensions
 
Oracle
* Oracle too is secure and scalable but not up to the extent SQL
* The support to the same is limited
Constraints are used to set the rules for all records in the table. If any constraints get violated then it can abort the action that caused it.
 
Constraints are defined while creating the database itself with the CREATE TABLE statement or even after the table is created once with the ALTER TABLE statement.
 
There are 5 major constraints are used in SQL, such as
 
NOT NULL : That indicates that the column must have some value and cannot be left NULL.
UNIQUE : This constraint is used to ensure that each row and column has a unique value and no value is being repeated in any other row or column.
PRIMARY KEY : This constraint is used in association with NOT NULL and UNIQUE constraints such as on one or the combination of more than one column to identify the particular record with a unique identity.
FOREIGN KEY : It is used to ensure the referential integrity of data in the table. It matches the value in one table with another using the PRIMARY KEY.
CHECK : It ensures whether the value in columns fulfills the specified condition.
This is a keyword used to query data from more tables based on the relationship between the fields of the tables. Keys play a major role when JOINs are used.
There are various types of join which can be used to retrieve data and it depends on the relationship between tables.
 
Inner Join : Inner join return rows when there is at least one match of rows between the tables.
 
Right Join : Right join return rows which are common between the tables and all rows of Right hand side table. Simply, it returns all the rows from the right hand side table even though there are no matches in the left hand side table.
 
Left Join : Left join return rows which are common between the tables and all rows of Left hand side table. Simply, it returns all the rows from Left hand side table even though there are no matches in the Right hand side table.
 
Full Join : Full join return 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 table.
SQL is a standard language for retrieving and manipulating structured databases.

MySQL is a relational database management system, like SQL Server, Oracle or IBM DB2, that is used to manage SQL databases.
Data Integrity is the assurance of accuracy and consistency of data over its entire life-cycle, and is a critical aspect to the design, implementation and usage of any system which stores, processes, or retrieves data. It also defines integrity constraints to enforce business rules on the data when it is entered into an application or a database.
A query is a request for data or information from a database table or combination of tables. A database query can be either a select query or an action query.
SELECT fname, lname 		 /* select query */
FROM myDb.students
WHERE student_id = 1;

UPDATE myDB.students 		 /* action query */
SET fname = 'Free Time', lname = 'Learning'
WHERE student_id = 1;
A subquery is a query within another query, also known as nested query or inner query . It is used to restrict or enhance the data to be queried by the main query, thus restricting or enhancing the output of the main query respectively. For example, here we fetch the contact information for students who have enrolled for the maths subject:

SELECT name, email, mob, address
FROM myDb.contacts
WHERE roll_no IN (
	 SELECT roll_no
	 FROM myDb.students
	 WHERE subject = 'Maths');

There are two types of subquery - Correlated and Non-Correlated.
 
* A correlated subquery cannot be considered as an independent query, but it can refer the column in a table listed in the FROM of the main query.

* A non-correlated subquery can be considered as an independent query and the output of subquery is substituted in the main query.
SELECT operator in SQL is used to select data from a database. The data returned is stored in a result table, called the result-set.
 
SELECT * FROM myDB.students;
Operators are the special keywords or special characters reserved for performing particular operations and are used in the SQL queries. There is three type of operators used in SQL:
 
* Arithmetic operators: addition (+), subtraction (-), multiplication (*), division (/), etc.

* Logical operators: ALL, AND, ANY, ISNULL, EXISTS, BETWEEN, IN, LIKE, NOT, OR, UNIQUE.

* Comparison operator: =, !=, <>, <, >, <=, >=, !<, !>
SQL or Structured Query Language is a language which is used to communicate with a relational database. It provides a way to manipulate and create databases. On the other hand, PL/SQL is a dialect of SQL which is used to enhance the capabilities of SQL. It was developed by Oracle Corporation in the early 90's. It adds procedural features of programming languages in SQL.
 
In SQL single query is being executed at once whereas in PL/SQL a whole block of code is executed at once.
 
SQL is like the source of data that we need to display on the other hand PL/SQL provides a platform where the SQL the SQL data will be shown.
 
SQL statement can be embedded in PL/SQL, but PL/SQL statement cannot be embedded in SQL as SQL do not support any programming language and keywords.
There is a built-in function in SQL called GetDate() which is used to return the current timestamp.
* A trigger allows you to execute a batch of SQL code when an insert, update or delete command is run against a specific table as TRIGGER is said to be the set of actions that are performed whenever commands like insert, update or delete are given through queries.

* The trigger is said to be activated when these commands are given to the system.

* Triggers are the particular type of stored procedures that are defined to execute automatically in place or after data modifications.

* Triggers are generated using CREATE TRIGGER statement.
SQL queries which contain set operations are called compound queries.
 
Union, Union All, Intersect or Minus operators are the set operators used in the SQL.
There are three case manipulation functions in SQL:
 
LOWER : converts character into Lowercase.
UPPER : converts character into uppercase.
INITCAP : converts character values to uppercase for the initials of each word.
CONCAT : join two or more values together.
SUBSTR : used to extract the string of specific length.
LENGTH : return the length of the string in numerical value.
INSTR : find the exact numeric position of a specified character.
LPAD : padding of the left-side character value for right-justified value.
RPAD : padding of right-side character value for left-justified value.
TRIM : remove all the defined character from the beginning, end or both beginning and end.
REPLACE : replace a specific sequence of character with other sequences of character.
The normal forms can be divided into some forms, and they are explained below :
 
First Normal Form (1NF): This should remove all the duplicate columns from the table. Creation of tables for the related data and identification of unique columns.
 
Second Normal Form (2NF): Meeting all requirements of the first normal form. Placing the subsets of data in separate tables and Creation of relationships between the tables using primary keys.
 
Third Normal Form (3NF): This should meet all requirements of 2NF. Removing the columns which are not dependent on primary key constraints.
 
Fourth Normal Form (4NF):Meeting all the requirements of third normal form and it should not have multi- valued dependencies.
Datawarehouse is a central repository of data from multiple sources of information. Those data are consolidated, transformed and made available for the mining and online processing. Warehouse data have a subset of data called Data Marts.
SQL Aggregate functions determine and calculate values from multiple columns in a table and return a single value.
 
There are 7 aggregate functions in SQL :
 
AVG() : Returns the average value from specified columns.
COUNT() : Returns number of table rows.
MAX() : Returns the largest value among the records.
MIN() : Returns smallest value among the records.
SUM() : Returns the sum of specified column values.
FIRST() : Returns the first value.
LAST() : Returns last value.
Scalar functions are used to return a single value based on the input values.
 
Scalar Functions are as follows:
 
UCASE() : Converts the specified field in the upper case.
LCASE() : Converts the specified field in lower case.
MID() : Extracts and returns character from the text field.
FORMAT() : Specifies the display format.
LEN() : Specifies the length of the text field.
ROUND() : Rounds up the decimal field value to a number.
A View can be defined as a virtual table that contains rows and columns with fields from one or more tables.
 
Syntax:
CREATE VIEW view_name AS
SELECT column_name(s) 
FROM table_name 
WHERE condition
SQL CREATE and REPLACE can be used for updating the view.
 
Execute the below query to update the created view.
 
Syntax:
CREATE OR REPLACE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
There are two types of privileges used in SQL, such as
 
System privilege : System privilege deals with the object of a particular type and provides users the right to perform one or more actions on it. These actions include performing administrative tasks, ALTER ANY INDEX, ALTER ANY CACHE GROUP CREATE/ALTER/DELETE TABLE, CREATE/ALTER/DELETE VIEW etc.

Object privilege : This allows to perform actions on an object or object of another user(s) viz. table, view, indexes etc. Some of the object privileges are EXECUTE, INSERT, UPDATE, DELETE, SELECT, FLUSH, LOAD, INDEX, REFERENCES etc.
SQL Injection is a type of database attack technique where malicious SQL statements are inserted into an entry field of database in a way that once it is executed, the database is exposed to an attacker for the attack. This technique is usually used for attacking data-driven applications to have access to sensitive data and perform administrative tasks on databases.
 
For Example,
SELECT column_name(s) FROM table_name WHERE condition;
NVL function is used to convert the null value to its actual value.
The differences are:
 
The basic difference in both is DELETE command is DML command and the TRUNCATE command is DDL.

DELETE command is used to delete a specific row from the table whereas the TRUNCATE command is used to remove all rows from the table.

We can use the DELETE command with WHERE clause but cannot use the TRUNCATE command with it.
A SAVEPOINT is a point in a transaction when you can roll the transaction back to a certain point without rolling back the entire transaction.
SQL> SAVEPOINT A
SQL> INSERT INTO TEST VALUES (1,'Savepoint A');
1 row inserted.
SQL> SAVEPOINT B
SQL> INSERT INTO TEST VALUES (2,'Savepoint B');
1 row inserted.
SQL> ROLLBACK TO B;
Rollback complete.
SQL> SELECT * FROM TEST;
ID MSG
-------- -----------
1  Savepoint A
Cursors operate on individual rows, and in case of a set, it works on a resultant set of data, which could be a table/view or a join of both. The resultant set is an output of a SQL query.
They are generally preferred when it comes to defining or changing the structure of a specific database in the shortest possible times due to security and other concerns. Some of the commands that can be applied and considered directly for this are as follows.
 
* Create
* Alter
* Drop
* Rename
* Truncate
* copy
It is basically a field which doesn’t have any value in SQL. It is totally different from that of a zero value and must not be put equal or confused with the same. These fields are left blank during the creation of the records.
* All Commands of SQL are Typed at the SQL prompt.
* Only One SQL Statements is Managed in The SQL Buffer.
* The Current SQL Statement Replaces the Previous SQL Statement in the Buffer.
* The SQL Statement Can be Divided Into Different Lines Within The SQL Buffer.
* Only One Line i.e., The Current Line Can be Active at a Time in the SQL Buffer.
* At SQL Prompt, Editing is Possible Only in The Current SQL Buffer Line.
* Every Statement of SQL should be terminated Using Semi-Colon ”;”
One SQL Statement can Contain Only One Semo Colon.
* To Run the Previous OR Current SQL Statement in the Buffer Type “/” at SQL Prompt.
* To Open The SQL Editor Type “ED” at SQL Prompt.
Goto -> Start -> All Programms -> Microsoft SQL Server 2008 R2 -> SQL Server management Studio.
It is a mechanism of getting secure data from the database.
 
SQL Injection Attacks:
 
* By providing proper validations for input fields.
* By using parameterized queries.
* By using stored procedures
* By using frequent code reviews
* We must not display database error messages in frontend
* An SQL injection is a code injection technique, used to attack data-driven applications.
* A query is a statement requesting the retrieval of information. 

* The portion of dimly that involves information retrieval is called a query language.
It is the situation where two transactions are waiting for other to release a lock on an item.
SQL Loader is a utility program which is used to transfer data from flat into oracle database. SQL Loader always executes control file based on the type of flat file we are creating control file and then submit control file to SQL loader then only SQL loader transfer file into flat file into oracle Data Base during this file some other files also created.
 
* Logfile
* Bad file
* Discard file
In this method, a single variable can represent all different datatype into a single unit. This variable is also called a record type variable.
 
Row Level Attribute is represented by using %rowtype.
 
Syntax:
 
variable_name table_name%rowtype;
A column or a combination of columns which uniquely identify a record in a table is called a Super Key.
In all databases generating primary key value automatically is called auto-increment concept. In Oracle, we are implementing the auto-increment concept by using row-level triggers, sequences. i.e here we creating sequence in SQL and use this sequence in PL/SQL row-level trigger.
SQL> create table test (sno number(10), primary key, name varchar2(10));
An alias is a feature of SQL that is supported by most, if not all, RDBMSs. It is a temporary name assigned to the table or table column for the purpose of a particular SQL query. In addition, aliasing can be employed as an obfuscation technique to secure the real names of database fields. A table alias is also called a correlation name .
 
An alias is represented explicitly by the AS keyword but in some cases the same can be performed without it as well. Nevertheless, using the AS keyword is always a good practice.
 
SELECT A.emp_name AS "Employee" 	/* Alias using AS keyword */
B.emp_name AS "Supervisor"
FROM employee A, employee B 		/* Alias without AS keyword */
WHERE A.emp_sup = B.emp_id;
Normalization represents the way of organizing structured data in the database efficiently. It includes creation of tables, establishing relationships between them, and defining rules for those relationships. Inconsistency and redundancy can be kept in check based on these rules, hence, adding flexibility to the database.
Denormalization is the inverse process of normalization, where the normalized schema is converted into a schema which has redundant information. The performance is improved by using redundancy and keeping the redundant data consistent. The reason for performing denormalization is the overheads produced in query processor by an over-normalized structure.
DELETE statement is used to delete rows from a table.
DELETE FROM Candidates
WHERE CandidateId > 1000;

TRUNCATE command is used to delete all the rows from the table and free the space containing the table.
TRUNCATE TABLE Candidates;

DROP command is used to remove an object from the database. If you drop a table, all the rows in the table is deleted and the table structure is removed from the database.
DROP TABLE Candidates;
SQL clause is defined to limit the result set by providing condition to the query. This usually filters some rows from the whole set of records.
 
Example : Query that has WHERE condition
 
Query that has HAVING condition.
Following MySQL query will return the top n records using the LIMIT method:
SELECT * FROM Worker ORDER BY Salary DESC LIMIT 10;​
 
Following SQL Server query will return the top n records using the TOP command:
SELECT TOP 10 * FROM Worker ORDER BY Salary DESC;​
Following Oracle query will return the top n records with the help of ROWNUM:
SELECT * FROM (SELECT * FROM Worker ORDER BY Salary DESC)
WHERE ROWNUM <= 10;
The following MySQL query returns the nth highest salary:
SELECT Salary FROM Worker ORDER BY Salary DESC LIMIT n-1,1;

The following SQL Server query returns the nth highest salary:
SELECT TOP 1 Salary
FROM (
 SELECT DISTINCT TOP n Salary
 FROM Worker 
 ORDER BY Salary DESC
 )
ORDER BY Salary ASC;
The required query is:
Select distinct W.WORKER_ID, W.FIRST_NAME, W.Salary 
from Worker W, Worker W1 
where W.Salary = W1.Salary 
and W.WORKER_ID != W1.WORKER_ID;
The required query is:
(SELECT * FROM Worker)
INTERSECT
(SELECT * FROM WorkerClone);
The required query is:
SELECT * FROM WORKER
WHERE WORKER_ID <= (SELECT count(WORKER_ID)/2 from Worker);
The following query will return the last record from the Worker table:
Select * from Worker where 
WORKER_ID = (SELECT max(WORKER_ID) from Worker);
The required query is:
 
SELECT DEPARTMENT, sum(Salary) from worker group by DEPARTMENT;