Вы находитесь на странице: 1из 561

SQL Concepts

Structured Query Language (SQL)


Structured Query Language is a standard Database language which is used to
create, maintain and retrieve the relational database.

What is Relational Database?


Relational database means the data is stored as well as retrieved in the form of
relations (tables). Table 1 shows the relational database with only one relation
called STUDENT which stores ROLL_NO, NAME, ADDRESS, PHONE and AGE of
students.

STUDENT

ROLL_NO NAME ADDRESS PHONE AGE

1 RAM DELHI 9455123451 18

2 RAMESH GURGAON 9652431543 18

3 SUJIT ROHTAK 9156253131 20

4 SURESH DELHI 9156768971 18

TABLE 1
These are some important terminologies that are used in terms of relation.

Attribute: Attributes are the properties that define a relation.


e.g.; ROLL_NO, NAME etc.

Tuple: Each row in the relation is known as tuple. The above relation contains 4
tuples, one of which is shown as:
1 RAM DELHI 9455123451 18

Degree: The number of attributes in the relation is known as degree of the relation.
The STUDENT relation defined above has degree 5.
Cardinality: The number of tuples in a relation is known as cardinality.
The STUDENT relation defined above has cardinality 4.
Column: Column represents the set of values for a particular attribute. The
column ROLL_NO is extracted from relation STUDENT.

ROLL_NO

The queries to deal with relational database can be categories as:

Data Definition Language: It is used to define the structure of the database. e.g;
CREATE TABLE, ADD COLUMN, DROP COLUMN and so on.
Data Manipulation Language: It is used to manipulate data in the relations. e.g.;
INSERT, DELETE, UPDATE and so on.
Data Query Language: It is used to extract the data from the relations. e.g.; SELECT
So first we will consider the Data Query Language. A generic query to retrieve from
a relational database is:

1. SELECT [DISTINCT] Attribute_List FROM R1,R2….RM


2. [WHERE condition]
3. [GROUP BY (Attributes)[HAVING condition]]
4. [ORDER BY(Attributes)[DESC]];
Part of the query represented by statement 1 is compulsory if you want to retrieve
from a relational database. The statements written inside [] are optional. We will
look at the possible query combination on relation shown in Table 1.

Case 1: If we want to retrieve attributes ROLL_NO and NAME of all students, the
query will be:

SELECT ROLL_NO, NAME FROM STUDENT;

ROLL_NO NAME

1 RAM

2 RAMESH

3 SUJIT

4 SURESH

Case 2: If we want to retrieve ROLL_NO and NAME of the students


whose ROLL_NO is greater than 2, the query will be:

SELECT ROLL_NO, NAME FROM STUDENT


WHERE ROLL_NO>2;

ROLL_NO NAME

3 SUJIT

4 SURESH

CASE 3: If we want to retrieve all attributes of students, we can write * in place of


writing all attributes as:
SELECT * FROM STUDENT
WHERE ROLL_NO>2;

ROLL_NO NAME ADDRESS PHONE AGE

3 SUJIT ROHTAK 9156253131 20

4 SURESH DELHI 9156768971 18

CASE 4: If we want to represent the relation in ascending order by AGE, we can use
ORDER BY clause as:

SELECT * FROM STUDENT ORDER BY AGE;

ROLL_NO NAME ADDRESS PHONE AGE

1 RAM DELHI 9455123451 18

2 RAMESH GURGAON 9652431543 18

4 SURESH DELHI 9156768971 18

3 SUJIT ROHTAK 9156253131 20

Note: ORDER BY AGE is equivalent to ORDER BY AGE ASC. If we want to retrieve the
results in descending order of AGE, we can use ORDER BY AGE DESC.
CASE 5: If we want to retrieve distinct values of an attribute or group of attribute,
DISTINCT is used as in:

SELECT DISTINCT ADDRESS FROM STUDENT;


ADDRESS

DELHI

GURGAON

ROHTAK

If DISTINCT is not used, DELHI will be repeated twice in result set. Before
understanding GROUP BY and HAVING, we need to understand aggregations
functions in SQL.

AGGRATION FUNCTIONS: Aggregation functions are used to perform mathematical


operations on data values of a relation. Some of the common aggregation functions
used in SQL are:
 COUNT: Count function is used to count the number of rows in a relation.
e.g;

SELECT COUNT (PHONE) FROM STUDENT;

COUNT(PHONE)

 SUM: SUM function is used to add the values of an attribute in a relation. e.g;
SELECT SUM (AGE) FROM STUDENT;

SUM(AGE)

74

In the same way, MIN, MAX and AVG can be used. As we have seen above, all
aggregation functions return only 1 row.
GROUP BY: Group by is used to group the tuples of a relation based on an attribute
or group of attribute. It is always combined with aggregation function which is
computed on group. e.g.;

SELECT ADDRESS, SUM(AGE) FROM STUDENT


GROUP BY (ADDRESS);

In this query, SUM(AGE) will be computed but not for entire table but for each
address. i.e.; sum of AGE for address DELHI(18+18=36) and similarly for other
address as well. The output is:

ADDRESS SUM(AGE)

DELHI 36

GURGAON 18

ROHTAK 20

If we try to execute the query given below, it will result in error because we have
computed SUM(AGE) for each address and there can be more than 1 student for
each address. So it can’t be displayed in result set.

SELECT ROLL_NO, ADDRESS, SUM(AGE) FROM STUDENT


GROUP BY (ADDRESS);

NOTE: An attribute which is not a part of GROUP BY clause can’t be used for
selection. Any attribute which is part of GROUP BY CLAUSE can be used for
selection but it is not mandatory.
SQL | Datatypes
Like in other programming languages, SQL also has certain datatypes available. A
brief idea of all the datatypes are discussed below.

1. Binary Datatypes :
There are four subtypes of this datatype which are given below :

2. Exact Numeric Datatype :


There are nine subtypes which are given below in table. The table contains the
range of data in a particular type.
3. Approximate Numeric Datatype :
The subtypes of this datatype are given in table with the range.

4. Character String Datatype :


The subtypes are given in below table –
5. Unicode Character String Datatype :
The details are given in below table –

6. Date and Time Datatype :


The details are given in below table.
SQL | DDL, DML, TCL and DCL
In this article, we’ll be discussing about Data Definition Language, Data
Manipulation Language, Transaction Control Language and Data Control Language.

DDL (Data Definition Language) :

Data Definition Language is used to define database structure or schema. DDL is


also used to specify additional properties of the data. The storage structure and
access methods used by the database system by a set of statements in a special
type of DDL called a data storage and definition language. These statements
defines the implementation details of the database schema, which are usually
hidden from the users. The data values stored in the database must satisfy certain
consistency constraints.
For example, suppose the university requires that the account balance of a
department must never be negative. The DDL provides facilities to specify such
constraints. The database system checks these constraints every time the database
is updated. In general, a constraint can be arbitrary predicate pertaining to the
database. However, arbitrary predicates may be costly to the test. Thus, database
system implements integrity constraints that can be tested with minimal overhead.

1. Domain Constraints : A domain of possible values must be associated with


every attribute (for example, integer types, character types, date/time types).
Declaring an attribute to be of a particular domain acts as the constraints on
the values that it can take.
2. Referential Integrity : There are cases where we wish to ensure that a value
appears in one relation for a given set of attributes also appear in a certain
set of attributes in another relation i.e. Referential Integrity. For example, the
department listed for each course must be one that actually exists.
3. Assertions : An assertion is any condition that the database must always
satisfy. Domain constraints and Integrity constraints are special form of
assertions.
4. Authorization : We may want to differentiate among the users as far as the
type of access they are permitted on various data values in database. These
differentiation are expressed in terms of Authorization. The most common
being :
read authorization – which allows reading but not modification of data ;
insert authorization – which allow insertion of new data but not modification
of existing data
update authorization – which allows modification, but not deletion.
Some Commands:

CREATE : to create objects in database

ALTER : alters the structure of database

DROP : delete objects from database

RENAME : rename an objects

Following SQL DDL-statement defines the department table :

create table department

(dept_name char(20),

building char(15),

budget numeric(12,2));
Execution of the above DDL statement creates the department table with three
columns – dept_name, building and budget; each of which has a specific datatype
associated with it.

DML (Data Manipulation Language) :

DML statements are used for managing data with in schema objects.
DML are of two types –

1. Procedural DMLs : require a user to specify what data are needed and how
to get those data.
2. Declerative DMLs (also referred as Non-procedural DMLs) : require a user to
specify what data are needed without specifying how to get those data.
Declerative DMLs are usually easier to learn and use than are procedural
DMLs. However, since a user does not have to specify how to get the data,
the database system has to figure out an efficient means of accessing data.

Some Commands :

SELECT : retrieve data from the database

INSERT : insert data into a table

UPDATE : update existing data within a table

DELETE : deletes all records from a table , space for the records remain

Example of SQL query that finds the names of all instructors in History department
:

select instructor.name

from instructor

where instructor.dept_name = 'History';


The query specifies that those rows from the table instructor where the dept_name
is History must be retrieved and the name attributes of these rows must be
displayed.

TCL (Transaction Control Language) :

Transaction Control Language commands are used to manage transactions in


database. These are used to manage the changes made by DML-statements. It also
allows statements to be grouped together into logical transactions.

Examples of TCL commands –

COMMIT : Commit command is used to permanently save any transaction

into database.

ROLLBACK : This command restores the database to last committed state.

It is also use with savepoint command to jump to a savepoint

in a transaction.

SAVEPOINT : Savepoint command is used to temporarily save a transaction so

that you can rollback to that point whenever necessary.

DCL (Data Control Language) :

A Data Control Language is a syntax similar to a computer programming language


used to control access to data stored in a database (Authorization). In particular, it
is a component of Structured Query Language (SQL).

Examples of DCL commands :

GRANT : allow specified users to perform specified tasks.

REVOKE : cancel previously granted or denied permissions.


The operations for which privileges may be granted to or revoked from a user or
role apply to both the Data definition language (DDL) and the Data manipulation
language (DML), and may include CONNECT, SELECT, INSERT, UPDATE, DELETE,
EXECUTE and USAGE.

In the Oracle database, executing a DCL command issues an implicit commit.


Hence, you cannot roll back the command.
SQL | TRANSACTIONS
What are Transactions?
Transactions group a set of tasks into a single execution unit. Each transaction
begins with a specific task and ends when all the tasks in the group successfully
complete. If any of the tasks fail, the transaction fails. Therefore, a transaction has
only two results: success or failure.
Incomplete steps result in the failure of the transaction. A database transaction, by
definition, must be atomic, consistent, isolated and durable. These are popularly
known as
ACID properties.

How to implement Transactions using SQL?

Following commands are used to control transactions.It is imortant to note that


these statements cannot be used while creating tables and are only used with the
DML Commands such as – INSERT, UPDATE and DELETE.

1. SET TRANSACTION: Places a name on a transaction.


Syntax:

2. SET TRANSACTION [ READ WRITE | READ ONLY ];

3. COMMIT: If everything is in order with all statements within a single


transaction, all changes are recorded together in the database is
called committed. The COMMIT command saves all the transactions to the
database since the last COMMIT or ROLLBACK command.
Syntax:

COMMIT;

Example: Sample table 1


Following is an example which would delete those records from the table
which have age = 20 and then COMMIT the changes in the database.
Queries:

DELETE FROM Student WHERE AGE = 20;

COMMIT;

Output:
Thus, two rows from the table would be deleted and the SELECT statement
would look like,

4. ROLLBACK: If any error occurs with any of the SQL grouped statements, all
changes need to be aborted. The process of reversing changes is
called rollback. This command can only be used to undo transactions since
the last COMMIT or ROLLBACK command was issued.
Syntax:

5. ROLLBACK;

Example:
From the above example Sample table1,
Delete those records from the table which have age = 20 and then ROLLBACK
the changes in the database.
Queries:

DELETE FROM Student WHERE AGE = 20;

ROLLBACK;

Output:

6. SAVEPOINT: creates points within the groups of transactions in which to


ROLLBACK.
A SAVEPOINT is a point in a transaction in which you can roll the transaction
back to a certain point without rolling back the entire transaction.
Syntax for Savepoint command:

7. SAVEPOINT SAVEPOINT_NAME;

This command is used only in the creation of SAVEPOINT among all the
transactions.
In general ROLLBACK is used to undo a group of transactions.
Syntax for rolling back to Savepoint command:

ROLLBACK TO SAVEPOINT_NAME;

you can ROLLBACK to any SAVEPOINT at any time to return the appropriate
data to its original state.
Example:
From the above example Sample table1,
Delete those records from the table which have age = 20 and then ROLLBACK
the changes in the database by keeping Savepoints.
Queries:
SAVEPOINT SP1;

//Savepoint created.

DELETE FROM Student WHERE AGE = 20;

//deleted

SAVEPOINT SP2;

//Savepoint created.

Here SP1 is first SAVEPOINT created before deletion.In this example one
deletion have taken place.
After deletion again SAVEPOINT SP2 is created.
Output:

Deletion have been taken place, let us assume that you have changed your
mind and decided to ROLLBACK to the SAVEPOINT that you identified as SP1
which is before deletion.
deletion is undone by this statement ,

ROLLBACK TO SP1;

//Rollback completed.
Notice that first deletion took place even though you rolled back to SP1 which is
first SAVEPOINT.

8. RELEASE SAVEPOINT:- This command is used to remove a SAVEPOINT that


you have created.
Syntax:

9. RELEASE SAVEPOINT SAVEPOINT_NAME

Once a SAVEPOINT has been released, you can no longer use the ROLLBACK
command to undo transactions performed since the last SAVEPOINT.

It is used to initiate a database transaction and used to specify characteristics of the


transaction that follows.
SQL | Views
Views in SQL are kind of virtual tables. A view also has rows and columns as they
are in a real table in the database. We can create a view by selecting fields from one
or more tables present in the database. A View can either have all the rows of a
table or specific rows based on certain condition.

In this article we will learn about creating , deleting and updating Views.
Sample Tables:
StudentDetails

StudentMarks

CREATING VIEWS

We can create View using CREATE VIEW statement. A View can be created from a
single table or multiple tables.
Syntax:

CREATE VIEW view_name AS

SELECT column1, column2.....

FROM table_name

WHERE condition;
view_name: Name for the View
table_name: Name of the table
condition: Condition to select rows

Examples:
 Creating View from a single table:
 In this example we will create a View named DetailsView from the table
StudentDetails.
Query:

 CREATE VIEW DetailsView AS

 SELECT NAME, ADDRESS

 FROM StudentDetails

 WHERE S_ID < 5;

To see the data in the View, we can query the view in the same manner
as we query a table.

SELECT * FROM DetailsView;

Output:

 In this example, we will create a view named StudentNames from the


table StudentDetails.
Query:

 CREATE VIEW StudentNames AS

 SELECT S_ID, NAME

 FROM StudentDetails
 ORDER BY NAME;

If we now query the view as,

SELECT * FROM StudentNames;

Output:

 Creating View from multiple tables: In this example we will create a View
named MarksView from two tables StudentDetails and StudentMarks. To
create a View from multiple tables we can simply include multiple tables in the
SELECT statement. Query:

 CREATE VIEW MarksView AS

 SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS

 FROM StudentDetails, StudentMarks

 WHERE StudentDetails.NAME = StudentMarks.NAME;

To display data of View MarksView:

SELECT * FROM MarksView;

Output:

DELETING VIEWS
We have learned about creating a View, but what if a created View is not needed
any more? Obviously we will want to delete it. SQL allows us to delete an existing
View. We can delete or drop a View using the DROP statement.
Syntax:

DROP VIEW view_name;

view_name: Name of the View which we want to delete.

For example, if we want to delete the View MarksView, we can do this as:

DROP VIEW MarksView;

UPDATING VIEWS
There are certain conditions needed to be satisfied to update a view. If any one of
these conditions is notmet, then we will not be allowed to update the view.
1. The SELECT statement which is used to create the view should not include
GROUP BY clause or ORDER BY clause.
2. The SELECT statement should not have the DISTINCT keyword.
3. The View should have all NOT NULL values.
4. The view should not be created using nested queries or complex queries.
5. The view should be created from a single table. If the view is created using
multiple tables then we will not be allowed to update the view.
 We can use the CREATE OR REPLACE VIEW statement to add or remove fields
from a view.
Syntax:

 CREATE OR REPLACE VIEW view_name AS

 SELECT column1,coulmn2,..

 FROM table_name

 WHERE condition;

For example, if we want to update the view MarksView and add the field AGE
to this View from StudentMarks Table, we can do this as:

CREATE OR REPLACE VIEW MarksView AS

SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS,


StudentMarks.AGE

FROM StudentDetails, StudentMarks


WHERE StudentDetails.NAME = StudentMarks.NAME;

If we fetch all the data from MarksView now as:

SELECT * FROM MarksView;

Output:

 Inserting a row in a view:


We can insert a row in a View in a same way as we do in a table. We can use
the INSERT INTO statement of SQL to insert a row in a View.Syntax:

 INSERT view_name(column1, column2 , column3,..)

 VALUES(value1, value2, value3..);

 view_name: Name of the View

Example:
In the below example we will insert a new row in the View DetailsView which
we have created above in the example of “creating views from a single table”.

INSERT INTO DetailsView(NAME, ADDRESS)

VALUES("Suresh","Gurgaon");

If we fetch all the data from DetailsView now as,

SELECT * FROM DetailsView;


Output:

 Deleting a row from a View:


Deleting rows from a view is also as simple as deleting rows from a table. We
can use the DELETE statement of SQL to delete rows from a view. Also
deleting a row from a view first delete the row from the actual table and the
change is then reflected in the view.Syntax:

 DELETE FROM view_name

 WHERE condition;

 view_name:Name of view from where we want to delete rows


 condition: Condition to select rows

Example:
In this example we will delete the last row from the view DetailsView which we
just added in the above example of inserting rows.

DELETE FROM DetailsView

WHERE NAME="Suresh";

If we fetch all the data from DetailsView now as,

SELECT * FROM DetailsView;


Output:

WITH CHECK OPTION


The WITH CHECK OPTION clause in SQL is a very useful clause for views. It is
applicable to a updatable view. If the view is not updatable, then there is no
meaning of including this clause in the CREATE VIEW statement.

 The WITH CHECK OPTION clause is used to prevent the insertion of rows in
the view where the condition in the WHERE clause in CREATE VIEW statement
is not satisfied.
 If we have used the WITH CHECK OPTION clause in the CREATE VIEW
statement, and if the UPDATE or INSERT clause does not satisfy the conditions
then they will return an error.
Example:
In the below example we are creating a View SampleView from StudentDetails
Table with WITH CHECK OPTION clause.

CREATE VIEW SampleView AS

SELECT S_ID, NAME

FROM StudentDetails

WHERE NAME IS NOT NULL

WITH CHECK OPTION;

In this View if we now try to insert a new row with null value in the NAME column
then it will give an error because the view is created with the condition for NAME
column as NOT NULL.
For example,though the View is updatable but then also the below query for this
View is not valid:

INSERT INTO SampleView(S_ID)


VALUES(6);

NOTE: The default value of NAME column is null.


SQL | Comments
As is any programming languages comments matter a lot in SQL also. In this set we
will learn about writing comments in any SQL snippet.

Comments can be written in the following three formats:

1. Single line comments.


2. Multi line comments
3. In line comments
 Single line comments: Comments starting and ending in a single line are
considered as single line comments.
Line starting with ‘–‘ is a comment and will not be executed.
Syntax:

 --single line comment

 --another comment

 SELECT * FROM Customers;

 Multi line comments: Comments starting in one line and ending in different
line are considered as multi line comments. Line starting with ‘/*’ is
considered as starting point of comment and are terminated when ‘*/’ is
encountered.
Syntax:

/* multi line comment

another comment */

SELECT * FROM Customers;

 In line comments: In line comments are an extension of multi line comments,


comments can be stated in between the statements and are enclosed in
between ‘/*’ and ‘*/’.
Syntax:
 SELECT * FROM /* Customers; */

More examples:

Multi line comment ->

/* SELECT * FROM Students;

SELECT * FROM STUDENT_DETAILS;

SELECT * FROM Orders; */

SELECT * FROM Articles;

In line comment ->

SELECT * FROM Students;

SELECT * FROM /* STUDENT_DETAILS;

SELECT * FROM Orders;

SELECT * FROM */ Articles;


SQL | Constraints
Constraints are the rules that we can apply on the type of data in a table. That is, we
can specify the limit on the type of data that can be stored in a particular column in
a table using constraints.

The available constraints in SQL are:

 NOT NULL: This constraint tells that we cannot store a null value in a column.
That is, if a column is specified as NOT NULL then we will not be able to store
null in this particular column any more.
 UNIQUE: This constraint when specified with a column, tells that all the
values in the column must be unique. That is, the values in any row of a
column must not be repeated.
 PRIMARY KEY: A primary key is a field which can uniquely identify each row in
a table. And this constraint is used to specify a field in a table as primary key.
 FOREIGN KEY: A Foreign key is a field which can uniquely identify each row in
a another table. And this constraint is used to specify a field as Foreign key.
 CHECK: This constraint helps to validate the values of a column to meet a
particular condition. That is, it helps to ensure that the value stored in a
column meets a specific condition.
 DEFAULT: This constraint specifies a default value for the column when no
value is specified by the user.
How to specify constraints?
We can specify constraints at the time of creating the table using CREATE TABLE
statement. We can also specify the constraints after creating a table using ALTER
TABLE statement.
Syntax:
Below is the syntax to create constraints using CREATE TABLE statement at the time
of creating the table.

CREATE TABLE sample_table

column1 data_type(size) constraint_name,

column2 data_type(size) constraint_name,

column3 data_type(size) constraint_name,


....

);

sample_table: Name of the table to be created.


data_type: Type of data that can be stored in the field.
constraint_name: Name of the constraint. for example- NOT NULL, UNIQUE,
PRIMARY KEY etc.

Let us see each of the constraint in detail.

1. NOT NULL
If we specify a field in a table to be NOT NULL. Then the field will never
accept null value. That is, you will be not allowed to insert a new row in the
table without specifying any value to this field.
For example, the below query creates a table Student with the fields ID and
NAME as NOT NULL. That is, we are bound to specify values for these two
fields every time we wish to insert a new row.

2. CREATE TABLE Student

3. (

4. ID int(6) NOT NULL,

5. NAME varchar(10) NOT NULL,

6. ADDRESS varchar(20)

7. );

8. UNIQUE
This constraint helps to uniquely identify each row in the table. i.e. for a
particular column, all the rows should have unique values. We can have more
than one UNIQUE columns in a table.
For example, the below query creates a tale Student where the field ID is
specified as UNIQUE. i.e, no two students can have the same ID. Unique
constraint in detail.

9. CREATE TABLE Student

10. (

11. ID int(6) NOT NULL UNIQUE,

12. NAME varchar(10),

13. ADDRESS varchar(20)

14. );

15. PRIMARY KEY


Primary Key is a field which uniquely identifies each row in the table. If a field
in a table as primary key, then the field will not be able to contain NULL
values as well as all the rows should have unique values for this field. So, in
other words we can say that this is combination of NOT NULL and UNIQUE
constraints.
A table can have only one field as primary key.Below query will create a table
named Student and specifies the field ID as primary key.

16. CREATE TABLE Student

17. (

18. ID int(6) NOT NULL UNIQUE,

19. NAME varchar(10),

20. ADDRESS varchar(20),

21. PRIMARY KEY(ID)

22. );

23. FOREIGN KEY


Foreign Key is a field in a table which uniquely identifies each row of a
another table. That is, this field points to primary key of another table. This
usually creates a kind of link between the tables.
Consider the two tables as shown below:
Orders
O_ID ORDER_NO C_ID

1 2253 3

2 3325 3

3 4521 2

4 8532 1

Customers

C_ID NAME ADDRESS

1 RAMESH DELHI

2 SURESH NOIDA

3 DHARMESH GURGAON

As we can see clearly that the field C_ID in Orders table is the primary key in
Customers table, i.e. it uniquely identifies each row in the Customers table.
Therefore, it is a Foreign Key in Orders table.
Syntax:

CREATE TABLE Orders

O_ID int NOT NULL,

ORDER_NO int NOT NULL,


C_ID int,

PRIMARY KEY (O_ID),

FOREIGN KEY (C_ID) REFERENCES Customers(C_ID)

24. CHECK
Using the CHECK constraint we can specify a condition for a field, which
should be satisfied at the time of entering values for this field.
For example, the below query creates a table Student and specifies the
condition for the field AGE as (AGE >= 18 ). That is, the user will not be
allowed to enter any record in the table with AGE < 18. Check constraint in
detail

25. CREATE TABLE Student

26. (

27. ID int(6) NOT NULL,

28. NAME varchar(10) NOT NULL,

29. AGE int NOT NULL CHECK (AGE >= 18)

30. );

31. DEFAULT
This constraint is used to provide a default value for the fields. That is, if at
the time of entering new records in the table if the user does not specify any
value for these fields then the default value will be assigned to them.
For example, the below query will create a table named Student and specify
the default value for the field AGE as 18.

32. CREATE TABLE Student

33. (

34. ID int(6) NOT NULL,

35. NAME varchar(10) NOT NULL,


36. AGE int DEFAULT 18

37. );
SQL | Creating Roles
A role is created to ease setup and maintenance of the security model. It is a
named group of related privileges that can be granted to the user. When there are
many users in a database it becomes difficult to grant or revoke privileges to users.
Therefore, if you define roles:

 You can grant or revoke privileges to users, thereby automatically granting or


revoking privileges.
 You can either create Roles or use the system roles pre-defined.
Some of the privileges granted to the system roles are as given below:

SYSTEM

ROLES PRIVILEGES GRANTED TO THE ROLE

Create table, Create view, Create synonym, Create sequence,

Connect Create session etc.

Create Procedure, Create Sequence, Create Table, Create

Trigger etc. The primary usage of the Resource role is to restrict

Resource access to database objects.

DBA All system privileges

Creating and Assigning a Role –

First, the (Database Administrator)DBA must create the role. Then the DBA can
assign privileges to the role and users to the role.

Syntax –
CREATE ROLE manager;

Role created.

In the syntax:
‘manager’ is the name of the role to be created.

 Now that the role is created, the DBA can use the GRANT statement to assign
users to the role as well as assign privileges to the role.
 It’s easier to GRANT or REVOKE privileges to the users through a role rather
than assigning a privilege directly to every user.
 If a role is identified by a password, then GRANT or REVOKE privileges have to
be identified by the password.
Grant privileges to a role –

GRANT create table, create view

TO manager;

Grant succeeded.

Grant a role to users

GRANT manager TO SAM, STARK;

Grant succeeded.

Revoke privilege from a Role :

REVOKE create table FROM manager;

Drop a Role :

DROP ROLE manager;

Explanation –
Firstly it creates a manager role and then allows managers to create tables and
views. It then grants Sam and Stark the role of managers. Now Sam and Stark can
create tables and views. If users have multiple roles granted to them, they receive
all of the privileges associated with all of the roles. Then create table privilege is
removed from role ‘manager’ using Revoke. Role is dropped from database using
drop.
SQL indexes
In this we will see how to create, delete and uses of index in database.
An index is a schema object. It is used by the server to speed up the retrieval of
rows by using a pointer. It can reduce disk I/O(input/output) by using a rapid path
access method to locate data quickly. An index helps to speed up select queries
and where clauses, but it slows down data input, with the update and
the insertstatements. Indexes can be created or dropped with no effect on the
data.
For example, if you want to reference all pages in a book that discusses a certain
topic, you first refer to the index, which lists all the topics alphabetically and are
then referred to one or more specific page numbers.

Creating an Index – It’s syntax is:

CREATE INDEX index

ON TABLE column;

where index is the name given to that index and TABLE is the name of the table on
which that index is created and column is the name of that column for which it is
applied.
For multiple columns –

CREATE INDEX index

ON TABLE (cloumn1, column2,.....);

Unique Indexes –

CREATE UNIQUE INDEX index

ON TABLE column;

Unique indexes are used for the maintenance of the integrity of the data present in
the table as well as for the fast performance, it does not allow multiple values to
enter into the table.
When should indexes be created –
 A column contains a wide range of values
 A column does not contain a large number of null values
 One or more columns are frequently used together in a where clause or a
join condition
When should indexes be avoided –
 The table is small
 The columns are not often used as a condition in the query
 The column is updated frequently
Removing an Index – To remove an index from the data dictionary by using
the DROP INDEX command.

DROP INDEX index;

To drop an index, you must be the owner of the index or have the DROP ANY
INDEX privilege.
Confirming Indexes –
You can check the different indexes present on a particular table given by the user
or the server itself and their uniqueness.

select *

from USER_INDEXES;

It will show you all the indexes present in the server, in which you can locate your
own tables too.
SQL | SEQUENCES
Sequence is a set of integers 1, 2, 3, … that are generated and supported by some
database systems to produce unique values on demand.

 A sequence is a user defined schema bound object that generates a


sequence of numeric values.
 Sequences are frequently used in many databases because many
applications require each row in a table to contain a unique value and
sequences provides an easy way to generate them.
 The sequence of numeric values is generated in an ascending or descending
order at defined intervals and can be configured to restart when exceeds
max_value.
Syntax:

CREATE SEQUENCE sequence_name

START WITH initial_value

INCREMENT BY increment_value

MINVALUE minimum value

MAXVALUE maximum value

CYCLE|NOCYCLE ;

sequence_name: Name of the sequence.

initial_value: starting value from where the sequence starts.


Initial_value should be greater than or equal
to minimum value and less than equal to maximum value.

increment_value: Value by which sequence will increment itself.


Increment_value can be positive or negative.

minimum_value: Minimum value of the sequence.


maximum_value: Maximum value of the sequence.

cycle: When sequence reaches its set_limit


it starts from beginning.

nocycle: An exception will be thrown


if sequence exceeds its max_value.

Example
Following is the sequence query creating sequence in ascending order.

 Example 1:

 CREATE SEQUENCE sequence_1

 start with 1

 increment by 1

 minvalue 0

 maxvalue 100

 cycle;

Above query will create a sequence named sequence_1.Sequence will start


from 1 and will be incremented by 1 having maximum value 100. Sequence
will repeat itself from start value after exceeding 100.
 Example 2:
Following is the sequence query creating sequence in descending order.

CREATE SEQUENCE sequence_2

start with 100

increment by -1

minvalue 1

maxvalue 100

cycle;
Above query will create a sequence named sequence_2.Sequence will start
from 100 and should be less than or equal to maximum value and will be
incremented by -1 having minimum value 1.
 Example to use sequence : create a table named students with columns as id
and name.

 CREATE TABLE students

 (

 ID number(10),

 NAME char(20)

 );

Now insert values into table

INSERT into students VALUES(sequence_1.nextval,'Ramesh');

INSERT into students VALUES(sequence_1.nextval,'Suresh');

where sequence_1.nextval will insert id’s in id column in a sequence as


defined in sequence_1.
Output:

______________________

| ID | NAME |

------------------------

| 1 | Ramesh |

| 2 | Suresh |

----------------------
SQL | WITH clause
The SQL WITH clause was introduced by Oracle in the Oracle 9i release 2 database.
The SQL WITH clause allows you to give a sub-query block a name (a process also
called sub-query refactoring), which can be referenced in several places within the
main SQL query.

 The clause is used for defining a temporary relation such that the output of
this temporary relation is available and is used by the query that is
associated with the WITH clause.
 Queries that have an associated WITH clause can also be written using
nested sub-queries but doing so add more complexity to read/debug the SQL
query.
 WITH clause is not supported by all database system.
 The name assigned to the sub-query is treated as though it was an inline
view or table
 The SQL WITH clause was introduced by Oracle in the Oracle 9i release 2
database.
Syntax:

WITH temporaryTable (averageValue) as

(SELECT avg(Attr1)

FROM Table),

SELECT Attr1

FROM Table

WHERE Table.Attr1 > temporaryTable.averageValue;

In this query, WITH clause is used to define a temporary relation temporaryTable


that has only 1 attribute averageValue. averageValue holds the average value of
column Attr1 described in relation Table. The SELECT statement that follows the
WITH clause will produce only those tuples where the value of Attr1 in relation
Table is greater than the average value obtained from the WITH clause statement.

Note: When a query with a WITH clause is executed, first the query mentioned
within the clause is evaluated and the output of this evaluation is stored in a
temporary relation. Following this, the main query associated with the WITH clause
is finally executed that would use the temporary relation produced.

Queries
Example 1: Find all the employee whose salary is more than the average salary of
all employees.
Name of the relation: Employee

EMPLOYEEID NAME SALARY

100011 Smith 50000

100022 Bill 94000

100027 Sam 70550

100845 Walden 80000

115585 Erik 60000

1100070 Kate 69000

SQL Query:

WITH temporaryTable(averageValue) as

(SELECT avg(Salary)
from Employee),

SELECT EmployeeID,Name, Salary

FROM Employee, temporaryTable

WHERE Employee.Salary > temporaryTable.averageValue;

Output:

EMPLOYEEID NAME SALARY

100022 Bill 94000

100845 Walden 80000

Explanation: The average salary of all employees is 70591. Therefore, all employees
whose salary is more than the obtained average lies in the output relation.

Example 2: Find all the airlines where the total salary of all pilots in that airline is
more than the average of total salary of all pilots in the database.
Name of the relation: Pilot

EMPLOYEEID AIRLINE NAME SALARY

70007 Airbus 380 Kim 60000

70002 Boeing Laura 20000

10027 Airbus 380 Will 80050


10778 Airbus 380 Warren 80780

115585 Boeing Smith 25000

114070 Airbus 380 Katy 78000

SQL Query:

WITH totalSalary(Airline, total) as

(SELECT Airline, sum(Salary)

FROM Pilot

GROUP BY Airline),

airlineAverage(avgSalary) as

(SELECT avg(total)

FROM totalSalary )

SELECT Airline

FROM totalSalary, airlineAverage

WHERE totalSalary.total > airlineAverage.avgSalary;

Output:

AIRLINE

Airbus 380

Explanation: The total salary of all pilots of Airbus 380 = 298,830 and that of Boeing
= 45000. Average salary of all pilots in the table Pilot = 57305. Since only the total
salary of all pilots of Airbus 380 is greater than the average salary obtained, so
Airbus 380 lies in the output relation.
Important Points:
 The SQL WITH clause is good when used with complex SQL statements rather
than simple ones
 It also allows you to break down complex SQL queries into smaller ones
which make it easy for debugging and processing the complex queries.
 The SQL WITH clause is basically a drop-in replacement to the normal sub-
query.
SQL | With Ties Clause
This post is a continuation of SQL Offset-Fetch Clause
Now, we understand that how to use the Fetch Clause in Oracle Database, along
with the Specified Offset and we also understand that Fetch clause is the newly
added clause in the Oracle Database 12c or it is the new feature added in the
Oracle database 12c.

Now consider the below example:

Suppose we a have a table named myTable with below data:

ID NAME SALARY

-----------------------------

1 Geeks 10000

4 Finch 10000

2 RR 6000

3 Dhoni 16000

5 Karthik 7000

6 Watson 10000

Now, suppose we want the first three rows to be Ordered by Salary in descending
order, then the below query must be executed:

Query:
SELECT * from myTable
order by salary desc
fetch first 3 rows only;

Output:
We got only first 3 rows order by Salary in Descending Order

ID NAME SALARY
--------------------------
3 Dhoni 16000
1 Geeks 10000
4 Finch 10000

Note: In the above result we got first 3 rows, ordered by Salary in Descending
Order, but we have one more row with same salary i.e, the row with
name Watson and Salary 10000, but it didn’t came up, because we restricted our
output to first three rows only. But this is not optimal, because most of the time in
live applications we will be required to display the tied rows also.
Real Life Example – Suppose we have 10 Racers running, and we have only 3 prizes
i.e, first, second, third, but suppose, Racers 3 and 4 finished the race together in
same time, so in this case we have a tie between 3 and 4 and that’s why both are
holder of Position 3.

With Ties

So, to overcome the above problem, Oracle introduces a clause known as With
Ties clause. Now, let’s see our previous example using With Ties clause.

Query:
SELECT * from myTable
order by salary desc
fetch first 3 rows With Ties;

Output:
See we get only first 3 rows order by Salary in Descending Order along with Tied
Row also

ID NAME SALARY
--------------------------
3 Dhoni 16000
1 Geeks 10000
6 Watson 10000 // We get Tied Row also
4 Finch 10000

Now, see we got the tied row also, which we were not getting previously.
Note: We get the tied row in our output, only when we use the order by clause in
our Select statement. Suppose, if we won’t use order by clause, and still we are
using with ties clause, then we won’t get the tied row in our output and the query
behaves same as, if we are using ONLY clause instead of With Ties clause.
Example – Suppose we execute the below query(without using order by clause) :

Query:
SELECT * from myTable
fetch first 3 rows With Ties;

Output:
See we won't get the tied row because we didn't use order by clause

ID NAME SALARY
--------------------------
1 Geeks 10000
4 Finch 10000
2 RR 6000

In the above result we won’t get the tied row and we get only first 3 rows. So With
Ties is tied with order byclause, i.e, we get the tied row in output if and only if we
use With Ties along with Order by clause.
Note: Please make sure that, you run these queries in Oracle Database 12c,
because Fetch clause is the newly added feature in Oracle 12c, also With Ties, runs
only in Oracle Database 12c, these queries won’t run in below versions of 12c like
10g or 11g.
SQL | Wildcard operators
Prerequisite: SQL | WHERE Clause
In the above mentioned article WHERE Clause is discussed in which LIKE operator is
also explained, where you must have encountered the word wildcards now lets get
deeper into Wildcards.
Wildcard operators are used with LIKE operator, there are four basic operators:

Operator Description

It is used in substitute of zero or more

% characters.

_ It is used in substitute of one character.

It is used to fetch matching set or range

of characters specified inside the

[range_of_characters] brackets.

It is used to fetch non-matching set or

[^range_of_characters] or range of characters specified inside the

[!range of characters] brackets.

Basic syntax:

SELECT column1,column2 FROM table_name WHERE column LIKE


wildcard_operator;
column1 , column2: fields in the table
table_name: name of table
column: name of field used for filtering data

Queries
 To fetch records from Student table with NAME ending with letter ‘T’.

 SELECT * FROM Student WHERE NAME LIKE '%T';

Output:

ROLL_NO NAME ADDRESS PHONE Age

3 SUJIT ROHTAK 9156253131 20

3 SUJIT ROHTAK 9156253131 20

 To fetch records from Student table with NAME ending any letter but starting
from ‘RAMES’.

 SELECT * FROM Student WHERE NAME LIKE 'RAMES_';


Output:

2RAMESHGURGAON965243154318

ROLL_NO NAME ADDRESS PHONE Age

2 RAMESH GURGAON 9652431543 18

 To fetch records from Student table with address containing letters ‘a’, ‘b’, or
‘c’.

 SELECT * FROM Student WHERE ADDRESS LIKE '%[A-C]%';

Output:

2RAMESHGURGAON965243154318

ROLL_NO NAME ADDRESS PHONE Age

2 RAMESH GURGAON 9652431543 18

2 RAMESH GURGAON 9652431543 18

 To fetch records from Student table with ADDRESS not containing letters ‘a’,
‘b’, or ‘c’.

 SELECT * FROM Student WHERE ADDRESS LIKE '%[^A-C]%';

Output:

ROLL_NO NAME ADDRESS PHONE Age


ROLL_NO NAME ADDRESS PHONE Age

1 Ram Delhi 9455123451 18

3 SUJIT ROHTAK 9156253131 20

4 SURESH Delhi 9156768971 18

3 SUJIT ROHTAK 9156253131 20

 To fetch records from Student table with PHONE feild having a ‘9’ in 1st
position and a ‘5’ in 4th position.

 SELECT * FROM Student WHERE PHONE LIKE '9__5%';

Output:

ROLL_NO NAME ADDRESS PHONE Age

1 Ram Delhi 9455123451 18

 To fetch records from Student table with ADDRESS containing total of 6


characters.

 SELECT * FROM Student WHERE ADDRESS LIKE '______';

Output:

ROLL_NO NAME ADDRESS PHONE Age

3 SUJIT ROHTAK 9156253131 20


ROLL_NO NAME ADDRESS PHONE Age

3 SUJIT ROHTAK 9156253131 20

 To fetch records from Student table with ADDRESS containing ‘OH’ at any
position, and the result set should not contain duplicate data.

 SELECT DISTINCT * FROM Student WHERE NAME LIKE '%OH%';

Output:

ROLL_NO NAME ADDRESS PHONE Age

3 SUJIT ROHTAK 9156253131 20


SQL | Intersect & Except clause
1. INTERSECT clause :
As the name suggests, the intersect clause is used to provide the result of the
intersection of two select statements. This implies the result contains all the rows
which are common to both the SELECT statements.
Syntax :

SELECT column-1, column-2 ……

FROM table 1

WHERE…..

INTERSECT

SELECT column-1, column-2 ……

FROM table 2

WHERE…..

Example :

Table 1 containing Employee Details


Table 2 containing details of employees who are provided bonus

Query :

SELECT ID, Name, Bonus

FROM

table1

LEFT JOIN

table2

ON table1.ID = table2.Employee_ID

INTERSECT

SELECT ID, Name, Bonus

FROM

table1

RIGHT JOIN

table2

ON table1.ID = table2.Employee_ID;
Result :

2. EXCEPT clause :
This works exactly opposite to the INTERSECT clause. The result, in this case,
contains all the rows except the common rows of the two SELECT statements.
Syntax :

SELECT column-1, column-2 ……

FROM table 1

WHERE…..

EXCEPT

SELECT column-1, column-2 ……

FROM table 2

WHERE…..

Example :
Table 1 containing Employee Details

Table 2 containing details of employees who are provided bonus

Query :

SELECT ID, Name, Bonus

FROM

table1

LEFT JOIN

table2

ON table1.ID = table2.Employee_ID

EXCEPT

SELECT ID, Name, Bonus

FROM
table1

RIGHT JOIN

table2

ON table1.ID = table2.Employee_ID;

Result :
SQL | USING Clause
If several columns have the same names but the datatypes do not match,
the NATURAL JOIN clause can be modified with the USING clause to specify the
columns that should be used for an EQUIJOIN.
 USING Clause is used to match only one column when more than one
column matches.
 NATURAL JOIN and USING Clause are mutually exclusive.
 It should not have a qualifier(table name or Alias) in the referenced columns.
 NATURAL JOIN uses all the columns with matching names and datatypes to
join the tables. The USING Clause can be used to specify only those columns
that should be used for an EQUIJOIN.
EXAMPLES:
We will apply the below mentioned commands on the following base tables:

Employee Table
Department Table

QUERY 1: Write SQL query to find the working location of the employees. Also give
their respective employee_id and last_name?

Input : SELECT e.EMPLOYEE_ID, e.LAST_NAME, d.LOCATION_ID


FROM Employees e JOIN Departments d
USING(DEPARTMENT_ID);
Output :

Explanation: The example shown joins the DEPARTMENT_ID column in the


EMPLOYEES and DEPARTMENTS
tables, and thus shows the location where an employee works.
We will apply the below mentioned commands on the following base tables:
Country Table
Location Table

QUERY 2: Write SQL query to find the location_id, street_address, postal_code and
their respective country name?

Input : SELECT l.location_id, l.street_address, l.postal_code, c.country_name


FROM locations l JOIN countries c
USING(country_id);
Output :

Explanation: The example shown joins the COUNTRY_ID column in the LOCATIONS
and COUNTRIES
tables, and thus shows the required details.
NOTE: When we use the USING clause in a join statement, the join column is not
qualified with table Alias. Do not Alias it even if the same column is used elsewhere
in the SQL statement:
Example:

Input: SELECT l.location_id, l.street_address, l.postal_code, c.country_name

FROM locations l JOIN countries c

USING(country_id)

WHERE c.country_id'IT';

Output:

Explanation: Since the column in USING Clause is used again in WHERE Clause, thus
it throws an error to the user.
SQL | LIMIT Clause
If there are a large number of tuples satisfying the query conditions, it might be
resourceful to view only a handful of them at a time.

 The LIMIT clause is used to set an upper limit on the number of tuples
returned by SQL.
 It is important to note that this clause is not supported by all SQL versions.
 The LIMIT clause can also be specfied using the SQL 2008 OFFSET/FETCH
FIRST clauses.
 The limit/offset expressions must be a non-negative integer.
Example:
Say we have a relation, Student.
Student Table:

ROLLNO NAME GRADE

12001 Aditya 9

12002 Sahil 6

12003 Hema 8

12004 Robin 9

12005 Sita 7

12006 Anne 10

12007 Yusuf 7
12008 Alex 5

Queries

SELECT *

FROM Student

LIMIT 5;

Output:

12001 Aditya 9

12002 Sahil 6

12003 Hema 8

12004 Robin 9

12005 Sita 7

SELECT *

FROM Student

ORDER BY Grade DESC

LIMIT 3;

Output:

12006 Anne 10
12001 Aditya 9

12004 Robin 9

The LIMIT operator can be used in situations such as the above, where we need to
find the top 3 students in a class and do not want to use any condition statements.

Using LIMIT along with OFFSET


LIMIT x OFFSET y simply means skip the first y entries and then return the next x
entries.
Queries:

SELECT *

FROM Student

LIMIT 5 OFFSET 2;

Output:

12003 Hema 8

12004 Robin 9

12005 Sita 7

12006 Anne 10

12007 Yusuf 7

Using LIMIT ALL


LIMIT ALL implies no limit.

SELECT *

FROM Student
LIMIT ALL;

The above query simply returns all the entries in the table.
SQL | MERGE Statement
Prerequisite – INSERT, UPDATE, DELETE
The MERGE command in SQL is actually a combination of three SQL
statements: INSERT, UPDATE and DELETE. In simple words, the MERGE statement in
SQL provides a convenient way to perform all these three operations together
which can be very helpful when it comes to handle the large running databases. But
unlike INSERT, UPDATE and DELETE statements MERGE statement requires a source
table to perform these operations on the required table which is called as target
table.
Now we know that the MERGE in SQL requires two tables : one the target table on
which we want to perform INSERT, UPDATE and DELETE operations, and the other
one is source table which contains the new modified and correct data for target
table and is actually compared with the actual target table in order to modify it.

In other words, the MERGE statement in SQL basically merges data from a source
result set to a target table based on a condition that is specified. The syntax of
MERGE statement can be complex to understand at first but its very easy once you
know what it means.So,not to get confused first let’s discuss some basics. Suppose
you have two tables: source and target, now think if you want to make changes in
the required target table with the help of provided source table which consists of
latest details.

 When will you need to insert the data in the target table?
Obviously when there is data in source table and not in target table i.e when
data not matched with target table.
 When will you need to update the data?
When the data in source table is matched with target table but any entry
other than the primary key is not matched.
 When will you need to delete the data?
When there is data in target table and not in source table i.e when data not
matched with source table.
Now, we know when to use INSERT, UPDATE and DELETE statements in case we
want to use MERGE statement so there should be no problem for you
understanding the syntax given below :
//.....syntax of MERGE statement....//

//you can use any other name in place of target

MERGE target_table_name AS TARGET

//you can use any other name in place of source

USING source_table_name AS SOURCE

ON condition (for matching source and target table)

WHEN MATCHED (another condition for updation)

//now use update statement syntax accordingly

THEN UPDATE

WHEN NOT MATCHED NY TARGET

//now use insert statement syntax accordingly

THEN INSERT

WHEN NOT MATCHED BY SOURCE

THEN DELETE;

That’s all about the MERGE statement and its syntax.


SQL | DDL, DML, DCL and TCL
Commands
Structured Query Language(SQL) as we all know is the database language by the
use of which we can perform certain operations on the existing database and also
we can use this language to create a database. SQL uses certain commands like
Create, Drop, Insert etc. to carry out the required tasks.

These SQL commands are mainly categorized into four categories as discussed
below:

1. DDL(Data Definition Language) : DDL or Data Definition Language actually


consists of the SQL commands that can be used to define the database
schema. It simply deals with descriptions of the database schema and is used
to create and modify the structure of database objects in database.
Examples of DDL commands:
 CREATE – is used to create the database or its objects (like table, index,
function, views, store procedure and triggers).
 DROP – is used to delete objects from the database.
 ALTER-is used to alter the structure of the database.
 TRUNCATE–is used to remove all records from a table, including all
spaces allocated for the records are removed.
 COMMENT –is used to add comments to the data dictionary.
 RENAME –is used to rename an object existing in the database.
2. DML(Data Manipulation Language) : The SQL commands that deals with the
manipulation of data present in database belong to DML or Data
Manipulation Language and this includes most of the SQL statements.
Examples of DML:
 SELECT – is used to retrieve data from the a database.
 INSERT – is used to insert data into a table.
 UPDATE – is used to update existing data within a table.
 DELETE – is used to delete records from a database table.
3. DCL(Data Control Language) : DCL includes commands such as GRANT and
REVOKE which mainly deals with the rights, permissions and other controls
of the database system.
Examples of DCL commands:
 GRANT-gives user’s access privileges to database.
 REVOKE-withdraw user’s access privileges given by using the GRANT
command.
4. TCL(transaction Control Language) : TCL commands deals with
the transaction within the database.
Examples of TCL commands:
 COMMIT– commits a Transaction.
 ROLLBACK– rollbacks a transaction in case of any error occurs.
 SAVEPOINT–sets a savepoint within a transaction.
 SET TRANSACTION–specify characteristics for the transaction.
SQL | CREATE DOMAIN
Used in : Postgre sql
CREATE DOMAIN creates a new domain. A domain is essentially a data type with
optional constraints (restrictions on the allowed set of values). The user who
defines a domain becomes its owner.
Domains are useful for abstracting common constraints on fields into a single
location for maintenance. For example, several tables might contain email address
columns, all requiring the same CHECK constraint to verify the address syntax.
Define a domain rather than setting up each table’s constraint individually.

Examples:

CREATE DOMAIN CPI_DATA AS REAL CHECK


(value >= 0 AND value <= 10);

Now CPI_DATA domain is create so, we can use this domain anywhere in any table
of database as below :

CREATE TABLE student(


sid char(9) PRIMARY KEY,
name varchar(30),
cpi CPI_DATA
);

Every time cpi_data will check the constraint, when you add data in student table.

Example 1 :

Insert into student values (201501408,Raj,7.5);


This will not violate the property of cpi.

Example 2 :

Insert into student values (201501188,Dhaval,12);


ERROR. This will violate the property of cpi.
SQL | DESCRIBE Statement
Prerequisite : Sql Create Clause,
As the name suggests, DESCRIBE is used to describe something. Since in database
we have tables, that’s why we use DESCRIBE or DESC(both are same) command to
describe the structure of a table.
Syntax:

DESCRIBE one;
OR
DESC one;

Note : We can use either DESCRIBE or DESC(both are Case Insensitive).


Suppose our table whose name is one has 3 columns
named FIRST_NAME, LAST_NAME and SALARY and all are of can contain null values.
Output:

Name Null Type


FIRST_NAME CHAR(25)
LAST_NAME CHAR(25)
SALARY NUMBER(6)

 Here, above on using DESC or either DESCRIBE we are able to see


the structure of a table but not on the console tab, the structure of table is
shown in the describe tab of the Database System Software.
 So desc or describe command shows the structure of table which
include name of the column, data-type of column and the nullability which
means, that column can contain null values or not.
 All of these features of table are described at the time of Creation of table.
Example :
Creating table or defining the structure of a table

create table one

id int not null,


name char(25)

Here, we created a table whose name is one and its columns are ID, NAME and
the id is of not null type i.e, we can’t put null values in the ID column but we can put
null values in the NAME column.
Example to demonstrate DESC:
Step 1: Defining structure of table i.e, Creating a table:

create table one

id int not null,

name char(25),

city varchar2(25)

Step 2: Displaying the structure of table:

DESC one

OR

DESCRIBE one

Output:

Name Null Type

ID Not Null INT

NAME CHAR(25)

CITY VARCHAR2(25)

Note: Here above ID column is of not null type and rest 2 column can contain null
values.
Note: You have to execute DESC command on your system software only, because
this command won’t run on any editor. Make sure to run this command on your
own installed Database only
SQL | Case Statement
Control statements form the heart of most languages since they control the
execution of other sets of statements. These are found in SQL too, and should be
exploited for uses such as query filtering and query optimization through careful
selection of tuples that match our requirement. In this post, we explore the Case-
Switch statement in SQL.
The CASE statement is SQL’s way of handling if/then logic.
Syntax:
There can be two valid ways of going about the case-switch statements.
1. The first takes a variable called case_value and matches it with some
statement_list.

2. CASE case_value

3. WHEN when_value THEN statement_list

4. [WHEN when_value THEN statement_list] ...

5. [ELSE statement_list]

6. END CASE

7. The second considers a search_condition instead of variable equality and


executes the statement_list accordingly.

8. CASE

9. WHEN search_condition THEN statement_list

10. [WHEN search_condition THEN statement_list] ...

11. [ELSE statement_list]

12. END CASE

Examples:
Say we have a relation, Faculty.

Faculty Table:
FACULTYID NAME DEPARTMENT GENDER

001 Aakash CS M

002 Sahil EC M

003 John HSS M

004 Shelley CS F

005 Anannya CS F

006 Sia HSS F

Let’s say we would like to modify this table such that if the department name is ‘CS’,
it gets modified to ‘Computer Science’, if it is ‘EC’ it gets modified to ‘Electronics and
Communication’, and if it is ‘HSS’ it gets modified to ‘Humanities and Social
Sciences’. This can be achieved using case statement.

Sample Query:
Consider a variable, department_name which is entered in the SQL code.

CASE department_name

WHEN 'CS'

THEN UPDATE Faculty SET

department='Computer Science';

WHEN 'EC'

THEN UPDATE Faculty SET


department='Electronics and Communication';

ELSE UPDATE Faculty SET

department='Humanities and Social Sciences';

END CASE

Output:

The department name corresponding to the given input gets renamed.

Consider another query which selects all the fields corresponding to the Faculty
table. Since the values written in the Gender field are single character values (M/F),
we would like to present them in a more readable format.

SELECT FacultyID, Name, Department,

CASE Gender

WHEN'M' THEN 'Male'

WHEN'F' THEN 'Female'

END

FROM Faculty

Output:

FACULTYID NAME DEPARTMENT GENDER

001 Aakash CS Male

002 Sahil EC Male


003 John HSS Male

004 Shelley CS Female

005 Anannya CS Female

006 Sia HSS Female

Consider yet another application of case-switch in SQL- custom sorting.

CREATE PROCEDURE GetFaculty(@ColToSort varchar(150)) AS

SELECT FacultyID, Name, Gender, Department

FROM Customers

ORDER BY

CASE WHEN @ColToSort='Department' THEN Department

WHEN @ColToSort='Name' THEN Name

WHEN @ColToSort='Gender' THEN Gender

ElSE FacultyID

END

Output:

The output gets sorted according to the provided field.

The above procedure (function) takes a variable of varchar data type as its
argument, and on the basis of that, sorts the tuples in the Faculty table.
SQL | UNIQUE Constraint
SQL Constraints
Unique constraint in SQL is used to check whether the sub query has duplicate
tuples in it’s result. It returns a boolean value indicating the presence/absence of
duplicate tuples. Unique construct returns true only if the sub query has no
duplicate tuples, else it return false.

Important Points:
 Evaluates to true on an empty sub query.
 Returns true only if there are unique tuples present as the output of the sub
query (two tuples are unique if the value of any attribute of the two tuples
differ).
 Returns true if the sub query has two duplicate rows with at least one
attribute as NULL.
Syntax:

SELECT table.ID

FROM table

WHERE UNIQUE (SELECT table2.ID

FROM table2

WHERE table.ID = table2.ID);

Note: During the execution, first the outer query is evaluated to obtain table.ID.
Following this, the inner sub query is processed which produces a new relation that
contains the output of inner query such that table.ID == table2.ID. If every row in
the new relation is unique then unique returns true and the corresponding table.ID
is added as a tuple in the output relation produced. However, if every row in the
new relation is not unique then unique evaluates to false and the corresponding
table.ID is not add to the output relation.

Unique applied to a sub query return false if and only if there are two tuples t1 and
t2 such that t1 = t2. It considers t1 and t2 to be two different tuple, when unique is
applied to a sub query that contains t1 and t2 such that t1 = t2 and at least one of
the attribute of these tuples contains a NULL value. Unique predicate in this case
evaluates to true. This is because, a NULL value in SQL is treated as an unknown
value therefore, two NULL values are considered to be distinct.

Note: The SQL statement without UNIQUE clause can also be written as:

SELECT table.ID

FROM table

WHERE 1 <= (SELECT count(table2.ID)

FROM table2

WHERE table.ID = table2.ID);

Queries
Example 1: Find all the instructors that taught at most one course in the year 2017.
Instructor relation:

EMPLOYEEID NAME COURSEID YEAR

77505 Alan SC110 2017

77815 Will CSE774 2017

85019 Smith EE457 2017

92701 Sam PYS504 2017

60215 Harold HSS103 2016

77505 Alan BIO775 2017


92701 Sam ECO980 2017

SQL Query:

SELECT I.EMPLOYEEID, I.NAME

FROM Instructor as I

WHERE UNIQUE (SELECT Inst.EMPLOYEEID

FROM Instructor as Inst

WHERE I.EMPLOYEEID = Inst.EMPLOYEEID

and Inst.YEAR = 2017);

Output:

EMPLOYEEID NAME

77815 Will

85019 Smith

Explanation: In the Instructor relation, only instructors Will and Smith teach a single
course during the year 2017. The sub query corresponding to these instructors
contains only a single tuple and therefore the unique clause corresponding to these
instructors evaluates to true thereby producing these two instructors in the output
relation.

Example 2: Find all the courses in Computer Science department that has only a
single instructor allotted to that course.
Course relation:
COURSEID NAME DEPARTMENT INSTRUCTORID

CSE505 Computer Network Computer Science 11071

CSE245 Operating System Computer Science 74505

CSE101 Programming Computer Science 12715

HSS505 Psychology Social Science 85017

EE475 Signals & Systems Electrical 22150

CSE314 DBMS Computer Science 44704

CSE505 Computer Network Computer Science 11747

CSE314 DBMS Computer Science 44715

SQL Query:

SELECT C.COURSEID, C.NAME

FROM Course as C

WHERE UNIQUE (SELECT T.INSTRUCTORID

FROM Course as T

WHERE T.COURSEID = C.COURSEID

and C.DEPARTMENT = 'Computer Science');


Output:

COURSEID NAME

CSE245 Operating System

CSE101 Programming

Explanation: In the course relation, the only courses in computer science


department that has a single instructor allotted are Operating System and
Programming. The unique constraint corresponding to these two courses has only
a single tuple consisting of the corresponding instructors. So, the unique clause for
these two courses evaluates to true and these courses are displayed in output
relation. Other courses in the Course relation either have two or more instructors
or they do not belong to computer science department and therefore, those
courses aren’t displayed in the output relation.
SQL | Create Table Extension
SQL provides an extension for CREATE TABLE clause that creates a new table with
the same schema of some existing table in the database.
 It is used to store the result of complex queries temporarily in a new table.
 The new table created has the same schema as the referencing table.
 By default, the new table has the same column names and the data type of
the referencing table.
Syntax:

CREATE TABLE newTable LIKE pets

Example:

CREATE TABLE newTable as

(SELECT *

FROM pets

WHERE pets.BREED = 'German Shepherd')

Queries
pets table:

ID NAME BREED GENDER

11441 Tommy German Shepherd Male

11442 Max Beagle Male

11443 Charlie Pug Male


11444 Daisy Poodle Female

11445 Zoe Labrador Female

11446 Toby Bulldog Male

Query 1:

CREATE TABLE newTable LIKE pets;

SELECT *

FROM newTable

where newTable.GENDER = 'Female';

Output:

ID NAME BREED GENDER

11444 Daisy Poodle Female

11445 Zoe Labrador Female

Explanation: The newTable created is a copy of pets table. So, selecting female pets
from newTable returns only two rows in which the pet is a female.
Query 2 :

CREATE TABLE newTable as

(SELECT *

FROM pets

WHERE pets.BREED = 'German Shepherd');


SELECT * from newTable;

Output:

ID NAME BREED GENDER

11441 Tommy German Shepherd Male

Explanation: First the inner query is evaluated and the results are stored in a new
temporary relation. Following this, the outer query is evaluated which create
newTable as add the output of inner query to newTable.
SQL | ALTER (RENAME)
Sometimes we may want to rename our table to give it a more relevant name. For
this purpose we can use ALTER TABLE to rename the name of table.
*Syntax may vary in different databases.
Syntax(Oracle,MySQL,MariaDB):

ALTER TABLE table_name


RENAME TO new_table_name;

Columns can be also be given new name with the use of ALTER TABLE.
Syntax(Oracle):

ALTER TABLE table_name


RENAME COLUMN old_name TO new_name;

Syntax(MySQL,MariaDB):

ALTER TABLE table_name


CHANGE COLUMN old_name TO new_name;

Sample Table:
Student

ROLL_NO NAME

1 Ram

2 Abhi

3 Rahul

4 Tanu
QUERY:
 Change the name of column NAME to FIRST_NAME in table Student.

ALTER TABLE Student RENAME COLUMN NAME TO FIRST_NAME;

OUTPUT:

ROLL_NO FIRST_NAME

1 Ram

2 Abhi

3 Rahul

4 Tanu

Change the name of the table Student to Student_Details


OUTPUT:
Student_Details

ROLL_NO FIRST_NAME

1 Ram

2 Abhi

3 Rahul

4 Tanu
SQL | ALTER (ADD, DROP, MODIFY)
ALTER TABLE is used to add, delete/drop or modify columns in the existing table. It
is also used to add and drop various constraints on the existing table.

ALTER TABLE – ADD

ADD is used to add columns into the existing table. Sometimes we may require to
add additional information, in that case we do not require to create the whole
database again, ADD comes to our rescue.
Syntax:

ALTER TABLE table_name


ADD (Columnname_1 datatype,
Columnname_2 datatype,

Columnname_n datatype);

ALTER TABLE – DROP

DROP COLUMN is used to drop column in a table. Deleting the unwanted columns
from the table.

Syntax:

ALTER TABLE table_name


DROP COLUMN column_name;

ALTER TABLE-MODIFY

It is used to modify the existing columns in a table. Multiple columns can also be
modified at once.
*Syntax may vary slightly in different databases.
Syntax(Oracle,MySQL,MariaDB):

ALTER TABLE table_name


MODIFY column_name column_type;

Syntax(SQL Server):
ALTER TABLE table_name
ALTER COLUMN column_name column_type;

Queries
Sample Table:
Student

ROLL_NO

QUERY:
 To ADD 2 columns AGE and COURSE to table Student.

ALTER TABLE Student ADD (AGE number(3),COURSE varchar(40));

OUTPUT:

ROLL_NO NAME AGE

1 Ram

2 Abhi

3 Rahul
ROLL_NO NAME AGE

4 Tanu

 MODIFY column COURSE in table Student

ALTER TABLE Student MODIFY COURSE varchar(20);

After running the above query maximum size of Course Column is reduced to 20
from 40.

 DROP column COURSE in table Student.

ALTER TABLE Student DROP COLUMN COURSE;

OUTPUT:

ROLL_NO NAME

1 Ram

2 Abhi

3 Rahul

4 Tanu
SQL | INSERT IGNORE Statement
We know that a primary key of a table cannot be duplicated. For instance, the roll
number of a student in the student table must always be distinct. Similarly, the
EmployeeID is expected to be unique in an employee table. When we try to insert a
tuple into a table where the primary key is repeated, it results in an error. However,
with the INSERT IGNORE statement, we can prevent such errors from popping up,
especially when inserting entries in bulk and such errors can interrupt the flow of
insertion. Instead, only a warning is generated.

Cases where INSERT IGNORE avoids error


 Upon insertion of a duplicate key where the column must contain a PRIMARY
KEY or UNIQUE constraint
 Upon insertion of NULL value where the column has a NOT NULL constraint.
 Upon insertion of a row to a partitioned table where the inserted values go
against the partition format.
Example:
Say we have a relation, Employee.

Employee Table:

EMPLOYEEID NAME CITY

15001 Aakash Delhi

15003 Sahil Bangalore

15010 John Hyderabad

15008 Shelley Delhi

15002 Ananya Mumbai


15004 Sia Pune

As we can notice, the entries are not sorted on the basis of their primary key, i.e.
EmployeeID.

Sample Query:

INSERT IGNORE INTO Employee (EmployeeID, Name, City)

VALUES (15002, 'Ram', 'Mumbai');

Output:
No entry inserted.
Sample Query:
Inserting multiple records
When inserting multiple records at once, any that cannot be inserting will not be,
but any that can will be:

INSERT IGNORE INTO Employee (EmployeeID, Name, City)

VALUES (15007, 'Shikha', 'Delhi'), (15002, 'Ram', 'Mumbai'), (15009, 'Sam',


'Ahmedabad');

Output:
The first and the last entries get inserted; the middle entry is simple ignored. No
error is flashed.
Disadvantage
Most users do not prefer INSERT IGNORE over INSERT since some errors may slip
unnoticed. This may cause inconsistencies in the table, thereby causing some
tuples to not get inserted without the user having a chance to correct them. Hence,
INSERT IGNORE must be used in very specific conditions.
SQL | LIKE
Sometimes we may require tuples from the database which match certain patterns.
For example, we may wish to retrieve all columns where the tuples start with the
letter ‘y’, or start with ‘b’ and end with ‘l’, or even more complicated and restrictive
string patterns. This is where the LIKE Clause comes to rescue, often coupled with
the WHERE Clause in SQL.

There are two kinds of wildcards used to filter out the results:

 % : Used to match zero or more characters. (Variable Length)


 _ : Used to match exactly one character. (Fixed Length)
The following are the rules for pattern matching with the LIKE Clause:

PATTERN MEANING

‘a%’ Match strings which start with ‘a’

‘%a’ Match strings with end with ‘a’

‘a%t’ Match strings which contain the start with ‘a’ and end with ‘t’.

Match strings which contain the substring ‘wow’ in them at any

‘%wow%’ position.

Match strings which contain the substring ‘wow’ in them at the

‘_wow%’ second position.

‘_a%’ Match strings which contain ‘a’ at the second position.


Match strings which start with ‘a’ and contain at least 2 more

‘a_%_%’ characters.

Example:
Say we have a relation, Supplier. We want to test various patterns using the LIKE
clause:

Supplier Table:

SUPPLIERID NAME ADDRESS

S1 Paragon Suppliers 21-3, Okhla, Delhi

S2 Mango Nation 21, Faridabad, Haryana

S3 Canadian Biz 6/7, Okhla Phase II, Delhi

S4 Caravan Traders 2-A, Pitampura, Delhi

S5 Harish and Sons Gurgaon, NCR

S6 Om Suppliers 2/1, Faridabad, Haryana

Sample Queries and Outputs:

SELECT SupplierID, Name, Address

FROM Suppliers
WHERE Name LIKE 'Ca%';

Output:

S3 Canadian Biz 6/7, Okhla Phase II, Delhi

S4 Caravan Traders 2-A, Pitampura, Delhi

SELECT *

FROM Suppliers

WHERE Address LIKE '%Okhla%';

Output:

S1 Paragon Suppliers 21-3, Okhla, Delhi

S3 Canadian Biz 6/7, Okhla Phase II, Delhi

SELECT SupplierID, Name, Address

FROM Suppliers

WHERE Name LIKE '_ango%';

Output:

S2 Mango Nation 21, Faridabad, Haryana

Application: The LIKE operator is extremely resourceful in situations such as


address filtering wherein we know only a segment or a portion of the entire
address (such as locality or city) and would like to retrieve results based on that.
The wildcards can be resourcefully exploited to yield even better and more filtered
tuples based on the requirement.
SQL | SOME
SQL | ALL and ANY
SOME operator evaluates the condition between the outer and inner tables and
evaluates to true if the final result returns any one row. If not, then it evaluates to
false.
 The SOME and ANY comparison conditions are similar to each other and are
completely interchangeable.
 SOME must match at least one row in the subquery and must be preceded
by comparison operators.
Syntax:

SELECT column_name(s)

FROM table_name

WHERE expression comparison_operator SOME (subquery)

Instructor Table:

NAME DEPARTMENT SALARY

Chandra Computational Biology 1

Visweswaran Electronics 1.5

Abraham Computer Science 1.3

John Electronics 1.2

Samantha Computer Science 2


Jyoti Electronics 1.2

Debarka Computer Science 2

Ganesh Computational Biology 0.9

Sample Queries and Outputs:

select name

from instructor

where Salary > some(select Salary

from instructor

where dept='Computer Science');

Output:

Visweswaran

Samantha

Debarka

Explanation
The instructors with salary > (salary of some instructor in the ‘Computer Science’
department) get returned. The salaries in the ‘Computer Science’ department are
1.3, 2 and 2. This implies any instructor with a salary greater than 1.3 can be
included in the final result.
SQL | OFFSET-FETCH Clause
OFFSET and FETCH Clause are used in conjunction with SELECT and ORDER BY
clause to provide a means to retrieve a range of records.

OFFSET
The OFFSET argument is used to identify the starting point to return rows from a
result set. Basically, it exclude the first set of records.
Note:
 OFFSET can only be used with ORDER BY clause. It cannot be used on its own.
 OFFSET value must be greater than or equal to zero. It cannot be negative,
else return error.
Syntax:

SELECT column_name(s)

FROM table_name

WHERE condition

ORDER BY column_name

OFFSET rows_to_skip ROWS;

Examples:
Consider the following Employee table,
 Print Fname, Lname of all the Employee except the employee having lowest
salary.

 SELECT Fname, Lname

 FROM Employee

 ORDER BY Salary

OFFSET 1 ROWS;

Output:

FETCH
The FETCH argument is used to return a set of number of rows. FETCH can’t be
used itself, it is used in conjuction with OFFSET.
Syntax:

SELECT column_name(s)

FROM table_name

ORDER BY column_name

OFFSET rows_to_skip

FETCH NEXT number_of_rows ROWS ONLY;

Example:

 Print the Fname, Lname from 3rd to 6th tuple of Employee table when sorted
according to the Salary.
 SELECT Fname, Lname

 FROM Employee

 ORDER BY Salary

 OFFSET 2 ROWS

FETCH NEXT 4 ROWS ONLY;

Output:

 Print the bottom 2 tuples of Employee table when sorted by Salary.

 SELECT Fname, Lname

 FROM Employee

 ORDER BY Salary

 OFFSET (SELECT COUNT(*) FROM EMPLOYEE) - 2 ROWS

FETCH NEXT 2 ROWS;

Output:

Important Points:
1. OFFSET clause is mandatory with FETCH. You can never use, ORDER BY …
FETCH.
2. TOP cannot be combined with OFFSET and FETCH.
3. The OFFSET/FETCH row count expression can be only be any arithmetic,
constant, or parameter expression which will return an integer value.
4. ORDER BY is mandatory to be used with OFFSET and FETCH clause.
5. OFFSET value must be greater than or equal to zero. It cannot be negative,
else return error.
SQL | Except Clause
In SQL, EXCEPT returns those tuples that are returned by the first SELECT operation,
and not returned by the second SELECT operation.

This is the same as using a subtract operator in relational algebra.

Example:
Say we have two relations, Students and TA (Teaching Assistant). We want to return
all those students who are not teaching assistants. The query can be formulated as:

Students Table:

STUDENTID NAME COURSE

1 Rohan DBMS

2 Kevin OS

3 Mansi DBMS

4 Mansi ADA

5 Rekha ADA

6 Megha OS

TA Table:

STUDENTID NAME COURSE


1 Kevin TOC

2 Sita IP

3 Manik AP

4 Rekha SNS

SELECT Name

FROM Students

EXCEPT

SELECT NAME

FROM TA;

Output:

Rohan

Mansi

Megha

To retain duplicates, we must explicitly write EXCEPTALL instead of EXCEPT.

SELECT Name

FROM Students

EXCEPTALL

SELECT Name
FROM TA;

Output:

Rohan

Mansi

Mansi

Megha

Difference between EXCEPT and NOT IN Clause


EXCEPT automatically removes all duplicates in the final result, whereas NOT IN
retains duplicate tuples. It is also important to note that EXCEPT is not supported by
MySQL.
SQL | GROUP BY
The GROUP BY Statement in SQL is used to arrange identical data into groups with
the help of some functions. i.e if a particular column has same values in different
rows then it will arrange these rows in a group.

Important Points:

 GROUP BY clause is used with the SELECT statement.


 In the query, GROUP BY clause is placed after the WHERE clause.
 In the query, GROUP BY clause is placed before ORDER BY clause if used any.
Syntax:

SELECT column1, function_name(column2)

FROM table_name

WHERE condition

GROUP BY column1, column2

ORDER BY column1, column2;

function_name: Name of the function used for example, SUM() , AVG().


table_name: Name of the table.
condition: Condition used.

Sample Table:

Employee
Student

Example:
 Group By single column: Group By single column means, to place all the rows
with same value of only that particular column in one group. Consider the
query as shown below:

 SELECT NAME, SUM(SALARY) FROM Employee

 GROUP BY NAME;

The above query will produce the below output:

As you can see in the above output, the rows with duplicate NAMEs are
grouped under same NAME and their corresponding SALARY is the sum of
the SALARY of duplicate rows. The SUM() function of SQL is used here to
calculate the sum.
 Group By multiple columns: Group by multiple column is say for
example, GROUP BY column1, column2. This means to place all the rows with
same values of both the columns column1 and column2 in one group.
Consider the below query:

 SELECT SUBJECT, YEAR, Count(*)

 FROM Student

 GROUP BY SUBJECT, YEAR;

Output:

As you can see in the above output the students with both same SUBJECT
and YEAR are placed in same group. And those whose only SUBJECT is same
but not YEAR belongs to different groups. So here we have grouped the table
according to two columns or more than one column.
HAVING Clause
We know that WHERE clause is used to place conditions on columns but what if we
want to place conditions on groups?

This is where HAVING clause comes into use. We can use HAVING clause to place
conditions to decide which group will be the part of final result-set. Also we can not
use the aggregate functions like SUM(), COUNT() etc. with WHERE clause. So we
have to use HAVING clause if we want to use any of these functions in the
conditions.

Syntax:

SELECT column1, function_name(column2)

FROM table_name

WHERE condition

GROUP BY column1, column2


HAVING condition

ORDER BY column1, column2;

function_name: Name of the function used for example, SUM() , AVG().


table_name: Name of the table.
condition: Condition used.

Example:

SELECT NAME, SUM(SALARY) FROM Employee

GROUP BY NAME

HAVING SUM(SALARY)>3000;

Output:

As you can see in the above output only one group out of the three groups appears
in the result-set as it is the only group where sum of SALARY is greater than 3000.
So we have used HAVING clause here to place this condition as the condition is
required to be placed on groups not columns.
SQL | ORDER BY
The ORDER BY statement in sql is used to sort the fetched data in either ascending
or descending according to one or more columns.

 By default ORDER BY sorts the data in ascending order.


 We can use the keyword DESC to sort the data in descending order and the
keyword ASC to sort in ascending order.
Syntax of all ways of using ORDER BY is shown below:

 Sort according to one column: To sort in ascending or descending order we


can use the keywords ASC or DESC respectively.
Syntax:

SELECT * FROM table_name ORDER BY column_name ASC|DESC

table_name: name of the table.


column_name: name of the column according to which the data is needed to
be arranged.
ASC: to sort the data in ascending order.
DESC: to sort the data in descending order.
| : use either ASC or DESC to sort in ascending or descending order

 Sort according to multiple columns: To sort in ascending or descending order


we can use the keywords ASC or DESC respectively. To sort according to
multiple columns, separate the names of columns by (,) operator.
Syntax:

 SELECT * FROM table_name ORDER BY column1 ASC|DESC , column2


ASC|DESC
Queries:

 Sort according to single column: In this example we will fetch all data from
the table Student and sort the result in descending order according to the
column ROLL_NO.

 SELECT * FROM Student ORDER BY ROLL_NO DESC;

Output:

ROLL_NO NAME ADDRESS PHONE Age

8 NIRAJ ALIPUR 7412356890 19

7 ROHIT BALURGHAT 9630258741 18

6 DHANRAJ BARABAJAR 7412589630 20


ROLL_NO NAME ADDRESS PHONE Age

5 SAPTARHI KOLKATA 9654783210 19

4 DEEP RAMNAGAR 8520369741 18

3 RIYANKA SILIGURI 9876543210 20

2 PRATIK BIHAR 7333834064 19

1 HARSH DELHI 8759770477 18

To sort in ascending order we have to use ASC in place of DESC.

 Sort according to multiple columns:In this example we will fetch all data from
the table Student and then sort the result in ascending order first according
to the column Age. and then in descending order according to the
column ROLL_NO.

 SELECT * FROM Student ORDER BY Age ASC , ROLL_NO DESC;

Output:

ROLL_NO NAME ADDRESS PHONE Age

7 ROHIT BALURGHAT 9630258741 18

4 DEEP RAMNAGAR 8520369741 18

1 HARSH DELHI 8759770477 18


ROLL_NO NAME ADDRESS PHONE Age

8 NIRAJ ALIPUR 7412356890 19

5 SAPTARHI KOLKATA 9654783210 19

2 PRATIK BIHAR 7333834064 19

6 DHANRAJ BARABAJAR 7412589630 20

3 RIYANKA SILIGURI 9876543210 20

In the above output you can see that first the result is sorted in ascending
order according to Age.

There are multiple rows having same Age. Now, sorting further this result-set
according to ROLL_NO will sort the rows with same Age according to
ROLL_NO in descending order.
SQL | Aliases
Aliases are the temporary names given to table or column for the purpose of a
particular SQL query. It is used when name of column or table is used other than
their original names, but the modified name is only temporary.

 Aliases are created to make table or column names more readable.


 The renaming is just a temporary change and table name does not change in
the original database.
 Aliases are useful when table or column names are big or not very readable.
 These are preferred when there are more than one table involved in a query.
Basic Syntax:
 For column alias:

 SELECT column as alias_name FROM table_name;


 column: fields in the table
 alias_name: temporary alias name to be used in replacement of original
column name
 table_name: name of table

 For table alias:

 SELECT column FROM table_name as alias_name;


 column: fields in the table
 table_name: name of table
 alias_name: temporary alias name to be used in replacement of original table
name
Queries for illustrating column alias
 To fetch ROLL_NO from Student table using CODE as alias name.

 SELECT ROLL_NO AS CODE FROM Student;

Output:

CODE

 To fetch Branch using Stream as alias name and Grade as CGPA from table
Student_Details.

 SELECT Branch AS Stream,Grade as CGPA FROM Student_Details;

Output:

Stream CGPA

Information Technology O
Stream CGPA

Computer Science E

Computer Science O

Mechanical Engineering A

Queries for illustrating table alias

Generally table aliases are used to fetch the data from more than just single table
and connect them through the field relations.
 To fetch Grade and NAME of Student with Age = 20.

 SELECT s.NAME, d.Grade FROM Student AS s, Student_Details

 AS d WHERE s.Age=20 AND s.ROLL_NO=d.ROLL_NO;


Output:

NAME Grade

SUJIT O
SQL | Union Clause
The Union Clause is used to combine two separate select statements and produce
the result set as a union of both the select statements.
NOTE:
1. The fields to be used in both the selet statements must be in same order,
same number and same data type.
2. The Union clause produces distinct values in the result set, to fetch the
duplicate values too UNION ALL must be used instead of just UNION.
Basic Syntax:

SELECT column_name(s) FROM table1 UNION SELECT column_name(s) FROM


table2;

Resultant set consists of distinct values.


SELECT column_name(s) FROM table1 UNION ALL SELECT column_name(s) FROM
table2;

Resultant set consists of duplicate values too.


Queries
 To fetch distinct ROLL_NO from Student and Student_Details table.

 SELECT ROLL_NO FROM Student UNION SELECT ROLL_NO FROM


Student_Details;

Output:

ROLL_NO

 To fetch ROLL_NO from Student and Student_Details table including


duplicate values.
 SELECT ROLL_NO FROM Student UNION ALL SELECT ROLL_NO FROM
Student_Details;

Output:

ROLL_NO

 To fetch ROLL_NO , NAME from Student table WHERE ROLL_NO is greater


than 3 and ROLL_NO , Branch from Student_Details table WHERE ROLL_NO is
less than 3 , including duplicate values and finally sorting the data by
ROLL_NO.

 SELECT ROLL_NO,NAME FROM Student WHERE ROLL_NO>3

 UNION ALL

 SELECT ROLL_NO,Branch FROM Student_Details WHERE ROLL_NO<3

 ORDER BY 1;

 Note:The column names in both the select statements can be different but
the
 data type must be same.And in the result set the name of column used in
the first
 select statement will appear.

Output:

ROLL_NO NAME

1 Information Technology

2 Computer Science

4 SURESH
SQL | WHERE Clause
WHERE keyword is used for fetching filtered data in a result set.
 It is used to fetch data according to a particular criteria.
 WHERE keyword can also be used to filter data by matching patterns.
Basic Syntax:
SELECT column1,column2 FROM table_name WHERE column_name operator value;

column1 , column2: fields int the table


table_name: name of table
column_name: name of field used for filtering the data
operator: operation to be considered for filtering
value: exact value or pattern to get related data in result

List of operators that can be used with where clause:

operator description

> Greater Than

>= Greater than or Equal to

< Less Than

<= Less than or Equal to

= Equal to

<> Not Equal to

BETWEEN In an inclusive Range


operator description

LIKE Search for a pattern

IN To specify multiple possible values for a column

Queries

 To fetch record of students with age equal to 20

 SELECT * FROM Student WHERE Age=20;

Output:

ROLL_NO NAME ADDRESS PHONE Age

3 SUJIT ROHTAK 9156253131 20


ROLL_NO NAME ADDRESS PHONE Age

3 SUJIT ROHTAK 9156253131 20

 To fetch Name and Address of students with ROLL_NO greater than 3

 SELECT ROLL_NO,NAME,ADDRESS FROM Student WHERE ROLL_NO > 3;

Output:

ROLL_NO NAME ADDRESS

4 SURESH Delhi

BETWEEN operator
It is used to fetch filtered data in a given range inclusive of two values.
Basic Syntax:
SELECT column1,column2 FROM table_name WHERE column_name BETWEEN
value1 AND value2;

BETWEEN: operator name

value1 AND value2: exact value from value1 to value2 to get related data in
result set.

Queries
 To fetch records of students where ROLL_NO is between 1 and 3 (inclusive)

 SELECT * FROM Student WHERE ROLL_NO BETWEEN 1 AND 3;

Output:

ROLL_NO NAME ADDRESS PHONE Age


ROLL_NO NAME ADDRESS PHONE Age

1 Ram Delhi 9455123451 18

2 RAMESH GURGAON 9652431543 18

3 SUJIT ROHTAK 9156253131 20

3 SUJIT ROHTAK 9156253131 20

2 RAMESH GURGAON 9652431543 18

 To fetch NAME,ADDRESS of students where Age is between 20 and 30


(inclusive)

 SELECT NAME,ADDRESS FROM Student WHERE Age BETWEEN 20 AND 30;

Output:

NAME ADDRESS

SUJIT Rohtak

SUJIT Rohtak

LIKE operator
It is used to fetch filtered data by searching for a particular pattern in where clause.
Basic Syntax:
SELECT column1,column2 FROM table_name WHERE column_name LIKE pattern;
LIKE: operator name

pattern: exact value extracted from the pattern to get related data in
result set.
Note: The character(s) in pattern are not case sensitive.
Queries
 To fetch records of students where NAME starts with letter S.

SELECT * FROM Student WHERE NAME LIKE 'S%';

The ‘%'(wildcard) signifies the later characters here which can be of any
length and
value.More about wildcards will be discussed in the later set.

Output:

ROLL_NO NAME ADDRESS PHONE Age

3 SUJIT ROHTAK 9156253131 20

4 SURESH Delhi 9156768971 18

3 SUJIT ROHTAK 9156253131 20

 To fetch records of students where NAME contains the patter ‘AM’.

 SELECT * FROM Student WHERE NAME LIKE '%AM%';

Output:

ROLL_NO NAME ADDRESS PHONE Age

1 Ram Delhi 9455123451 18


ROLL_NO NAME ADDRESS PHONE Age

2 RAMESH GURGAON 9652431543 18

2 RAMESH GURGAON 9652431543 18

IN operator
It is used to fetch filtered data same as fetched by ‘=’ operator just the difference is
that here we can specify multiple values for which we can get the result set.
Basic Syntax:
SELECT column1,column2 FROM table_name WHERE column_name IN
(value1,value2,..);

IN: operator name

value1,value2,..: exact value matching the values given and get related data in result
set.
Queries
 To fetch NAME and ADDRESS of students where Age is 18 or 20.

 SELECT NAME,ADDRESS FROM Student WHERE Age IN (18,20);

Output:

NAME ADDRESS

Ram Delhi

RAMESH GURGAON

SUJIT ROHTAK
NAME ADDRESS

SURESH Delhi

SUJIT ROHTAK

RAMESH GURGAON

 To fetch records of students where ROLL_NO is 1 or 4.

 SELECT * FROM Student WHERE ROLL_NO IN (1,4);

Output:

ROLL_NO NAME ADDRESS PHONE Age

1 Ram Delhi 9455123451 18

4 SURESH Delhi 9156768971 18


SQL | AND and OR operators
In SQL, the AND & OR operators are used for filtering the data and getting precise
result based on conditions.

 The AND and OR operators are used with the WHERE clause.
 These two operators are called conjunctive operators.
AND Operator : This operators displays only those records where both the
conditions condition1 and condition2 evaluates to True.
OR Operator: This operators displays the records where either one of the
conditions condition1 and condition2 evaluates to True. That is, either condition1 is
True or condition2 is True.

AND Operator
Basic Syntax:

SELECT * FROM table_name WHERE condition1 AND condition2 and ...conditionN;

table_name: name of the table


condition1,2,..N : first condition, second condition and so on

Sample Queries:
1. To fetch all the records from Student table where Age is 18 and ADDRESS is
Delhi.

2. SELECT * FROM Student WHERE Age = 18 AND ADDRESS = 'Delhi';

Output:

ROLL_NO NAME ADDRESS PHONE Age

1 Ram Delhi 9455123451 18

4 SURESH Delhi 9156768971 18

3. To fetch all the records from Student table where NAME is Ram and Age is
18.

4. SELECT * FROM Student WHERE Age = 18 AND NAME = 'Ram';

Output:

ROLL_NO NAME ADDRESS PHONE Age

1 Ram Delhi 9455123451 18

OR Operator
Basic Syntax:

SELECT * FROM table_name WHERE condition1 OR condition2 OR... conditionN;

table_name: name of the table


condition1,2,..N : first condition, second condition and so on

Sample Queries:
1. To fetch all the records from Student table where NAME is Ram or NAME is
SUJIT.

2. SELECT * FROM Student WHERE NAME = 'Ram' OR NAME = 'SUJIT';


Output:

ROLL_NO NAME ADDRESS PHONE Age

1 Ram Delhi 9455123451 18

3 SUJIT ROHTAK 9156253131 20

3 SUJIT ROHTAK 9156253131 20

3. To fetch all the records from Student table where NAME is Ram or Age is 20.

4. SELECT * FROM Student WHERE NAME = 'Ram' OR Age = 20;

Output:

ROLL_NO NAME ADDRESS PHONE Age

1 Ram Delhi 9455123451 18

3 SUJIT ROHTAK 9156253131 20

3 SUJIT ROHTAK 9156253131 20

Combining AND and OR


You can combine AND and OR operators in below manner to write complex
queries.
Basic Syntax:

SELECT * FROM table_name WHERE condition1 AND (condition2 OR condition3);

Sample Queries:
1. To fetch all the records from Student table where Age is 18 NAME is Ram or
RAMESH.
SELECT * FROM Student WHERE Age = 18 AND (NAME = 'Ram' OR NAME =
'RAMESH');

Output:

ROLL_NO NAME ADDRESS PHONE Age

1 Ram Delhi 9455123451 18

2 RAMESH GURGAON 9152431543 18


SQL | Distinct Clause
The distinct keyword is used in conjunction with select keyword. It is helpful when
there is need of avoiding the duplicate values present in any specific columns/table.
When we use distinct keyword only the unique values are fetched.
Basic Syntax:

SELECT DISTINCT column1,column2 FROM table_name


column1 , column2: names of the fields of the table
table_name: from where we want to fetch

This query will return all the unique combination of rows in the table with fields
column1 , column2.

NOTE: If distinct keyword is used with multiple columns, the distinct combination is
displayed in the result set.

Queries
 To fetch unique names from the NAME field

SELECT DISTINCT NAME FROM Student;

Output:
NAME

Ram

RAMESH

SUJIT

SURESH

 To fetch unique combination of rows from the whole table

SELECT DISTINCT * FROM Student;

Output:

ROLL_NO NAME ADDRESS PHONE Age

1 Ram Delhi 9455123451 18

2 RAMESH GURGAON 9652431543 18

3 SUJIT ROHTAK 9156253131 20

4 SURESH Delhi 9156768971 18


Please note: Without the keyword distinct in both the above examples 6
records would have been fetched instead of 4, since in the original table
there are 6 records with the duplicate values.
SQL | SELECT TOP Clause
SELECT TOP clause is used to fetch limited number of rows from a database. This
clause is very useful while dealing with large databases.

 Basic Syntax:

 SELECT TOP value column1,column2 FROM table_name;


 value: number of rows to return from top
 column1 , column2: fields in the table
 table_name: name of table

 Syntax using Percent

 SELECT TOP value PERCENT column1,column2 FROM table_name;


 value: percentage of number of rows to return from top
 column1 , column2: fields in the table
 table_name: name of table

Queries
 To fetch first two data set from Student table.

 SELECT TOP 2 * FROM Student;

Output:
ROLL_NO NAME ADDRESS PHONE Age

1 Ram Delhi 9455123451 18

2 RAMESH GURGAON 9652431543 18

 To fetch 50 percent of the total records from Student table.

 SELECT TOP 50 PERCENT * FROM Student;

Output:

ROLL_NO NAME ADDRESS PHONE Age

1 Ram Delhi 9455123451 18

2 RAMESH GURGAON 9652431543 18

3 SUJIT ROHTAK 9156253131 20

NOTE: To get the same functionality on MySQL and Oracle databases there is a bit
of difference in the basic syntax;
Equivalent Syntaxes are as follows:
 For MySQL databases:

 SELECT column1,column2 FROM table_name LIMIT value;


 column1 , column2: fields int the table
 table_name: name of table
 value: number of rows to return from top

 For Oracle databases:

 SELECT column1,column2 FROM table_name WHERE ROWNUM <= value;


 column1 , column2: fields int the table
 table_name: name of table
 value: number of rows to return from top
SQL | SELECT Query
Select is the most commonly used statement in SQL. The SELECT Statement in SQL
is used to retrieve or fetch data from a database. We can fetch either the entire
table or according to some specified rules. The data returned is stored in a result
table. This result table is also called result-set.

With the SELECT clause of a SELECT command statement, we specify the columns
that we want to be displayed in the query result and, optionally, which column
headings we prefer to see above the result table.

The select clause is the first clause and is one of the last clauses of the select
statement that the database server evaluates. The reason for this is that before we
can determine what to include in the final result set, we need to know all of the
possible columns that could be included in the final result set.

Sample Table:

Basic Syntax:

SELECT column1,column2 FROM table_name


column1 , column2: names of the fields of the table
table_name: from where we want to fetch

This query will return all the rows in the table with fields column1 , column2.

 To fetch the entire table or all the fields in the table:


SELECT * FROM table_name;

 Query to fetch the fields ROLL_NO, NAME, AGE from the table Student:

SELECT ROLL_NO, NAME, AGE FROM Student;

Output:

ROLL_NO NAME Age

1 Ram 18

2 RAMESH 18

3 SUJIT 20

4 SURESH 18

 To fetch all the fields from the table Student:

SELECT * FROM Student;

Output:

ROLL_NO NAME ADDRESS PHONE Age

1 Ram Delhi 9455123451 18

2 RAMESH GURGAON 9652431543 18


ROLL_NO NAME ADDRESS PHONE Age

3 SUJIT ROHTAK 9156253131 20

4 SURESH Delhi 9156768971 18


SQL | UPDATE Statement
The UPDATE statement in SQL is used to update the data of an existing table in
database. We can update single columns as well as multiple columns using UPDATE
statement as per our requirement.

Basic Syntax

UPDATE table_name SET column1 = value1, column2 = value2,...


WHERE condition;

table_name: name of the table


column1: name of first , second, third column....
value1: new value for first, second, third column....
condition: condition to select the rows for which the
values of columns needs to be updated.

NOTE: In the above query the SET statement is used to set new values to the
particular column and the WHERE clause is used to select the rows for which the
columns are needed to be updated. If we have not used the WHERE clause then the
columns in all the rows will be updated. So the WHERE clause is used to choose the
particular rows.

Example Queries
 Updating single column: Update the column NAME and set the value to
‘PRATIK’ in all the rows where Age is 20.

 UPDATE Student SET NAME = 'PRATIK' WHERE Age = 20;


Output:
This query will update two rows(third row and fifth row) and the
table Student will now look like,

ROLL_NO NAME ADDRESS PHONE Age

1 Ram Delhi 9455123451 18

2 RAMESH GURGAON 9562431543 18

3 PRATIK ROHTAK 9156253131 20

4 SURESH Delhi 9156768971 18

3 PRATIK ROHTAK 9156253131 20

2 RAMESH GURGAON 9562431543 18

 Updating multiple columns: Update the columns NAME to ‘PRATIK’ and


ADDRESS to ‘SIKKIM’ where ROLL_NO is 1.

 UPDATE Student SET NAME = 'PRATIK', ADDRESS = 'SIKKIM' WHERE ROLL_NO


= 1;

Output:
The above query will update two columns in the first row and the
table Student will now look like,
ROLL_NO NAME ADDRESS PHONE Age

1 PRATIK SIKKIM 9455123451 18

2 RAMESH GURGAON 9562431543 18

3 PRATIK ROHTAK 9156253131 20

4 SURESH Delhi 9156768971 18

3 PRATIK ROHTAK 9156253131 20

2 RAMESH GURGAON 9562431543 18

Note: For updating multiple columns we have used comma(,) to separate the
names and values of two columns.

 Omitting WHERE clause: If we omit the WHERE clause from the update query
then all of the rows will get updated.

 UPDATE Student SET NAME = 'PRATIK';

Output:
The table Student will now look like,

ROLL_NO NAME ADDRESS PHONE Age

1 PRATIK Delhi 9455123451 18


ROLL_NO NAME ADDRESS PHONE Age

2 PRATIK GURGAON 9562431543 18

3 PRATIK ROHTAK 9156253131 20

4 PRATIK Delhi 9156768971 18

3 PRATIK ROHTAK 9156253131 20

2 PRATIK GURGAON 9562431543 18


SQL | DROP, TRUNCATE
DROP
DROP is used to delete a whole database or just a table.The DROP statement
destroys the objects like an existing database, table, index, or view.
A DROP statement in SQL removes a component from a relational database
management system (RDBMS).
Syntax:

DROP object object_name

Examples:
DROP TABLE table_name;
table_name: Name of the table to be deleted.

DROP DATABASE database_name;


database_name: Name of the database to be deleted.

TRUNCATE
TRUNCATE statement is a Data Definition Language (DDL) operation that is used to
mark the extents of a table for deallocation (empty for reuse). The result of this
operation quickly removes all data from a table, typically bypassing a number of
integrity enforcing mechanisms. It was officially introduced in
the SQL:2008 standard.
The TRUNCATE TABLE mytable statement is logically (though not physically)
equivalent to the DELETE FROM mytable statement (without a WHERE clause).
Syntax:

TRUNCATE TABLE table_name;


table_name: Name of the table to be truncated.
DATABASE name - student_data

DROP vs TRUNCATE

 Truncate is normally ultra-fast and its ideal for deleting data from a
temporary table.
 Truncate preserves the structure of the table for future use, unlike drop table
where the table is deleted with its full structure.
 Table or Database deletion using DROP statement cannot be rolled back, so
it must be used wisely.

Queries
 To delete the whole database

 DROP DATABASE student_data;

After running the above query whole database will be deleted.

 To truncate Student_details table from student_data database.

 TRUNCATE TABLE Student_details;


After running the above query Student_details table will be truncated, i.e, the
data will be deleted but the structure will remain in the memory for further
operations.
SQL | DELETE Statement
The DELETE Statement in SQL is used to delete existing records from a table. We
can delete a single record or multiple records depending on the condition we
specify in the WHERE clause.

Basic Syntax:

DELETE FROM table_name WHERE some_condition;

table_name: name of the table


some_condition: condition to choose particular record.

Note: We can delete single as well as multiple records depending on the condition
we provide in WHERE clause. If we omit the WHERE clause then all of the records
will be deleted and the table will be empty.
Sample Table:

Example Queries:
 Deleting single record: Delete the rows where NAME = ‘Ram’. This will delete
only the first row.

 DELETE FROM Student WHERE NAME = 'Ram';

Output:
The above query will delete only the first row and the table Student will now
look like,

ROLL_NO NAME ADDRESS PHONE Age

2 RAMESH GURGAON 9562431543 18

3 SUJIT ROHTAK 9156253131 20

4 SURESH Delhi 9156768971 18

3 SUJIT ROHTAK 9156253131 20

2 RAMESH GURGAON 9562431543 18

 Deleting multiple records: Delete the rows from the table Student where Age
is 20. This will delete 2 rows(third row and fifth row).

 DELETE FROM Student WHERE Age = 20;

Output:
The above query will delete two rows(third row and fifth row) and the
table Student will now look like,

ROLL_NO NAME ADDRESS PHONE Age

1 Ram Delhi 9455123451 18


ROLL_NO NAME ADDRESS PHONE Age

2 RAMESH GURGAON 9562431543 18

4 SURESH Delhi 9156768971 18

2 RAMESH GURGAON 9562431543 18

 Delete all of the records: There are two queries to do this as shown below,

 query1: "DELETE FROM Student";

 query2: "DELETE * FROM Student";

Output:
All of the records in the table will be deleted, there are no records left to
display. The table Student will become empty!
SQL | CREATE
There are two CREATE statements available in SQL:

1. CREATE DATABASE
2. CREATE TABLE
CREATE DATABASE
A Database is defined as a structured set of data. So, in SQL the very first step to
store the data in a well structured manner is to create a database. The CREATE
DATABASE statement is used to create a new database in SQL.
Syntax:

CREATE DATABASE database_name;

database_name: name of the database.

Example Query:
This query will create a new database in SQL and name the database
as my_database.

CREATE DATABASE my_database;

CREATE TABLE
We have learned above about creating databases. Now to store the data we need a
table to do that. The CREATE TABLE statement is used to create a table in SQL. We
know that a table comprises of rows and columns. So while creating tables we have
to provide all the information to SQL about the names of the columns, type of data
to be stored in columns, size of the data etc. Let us now dive into details on how to
use CREATE TABLE statement to create tables in SQL.

Syntax:

CREATE TABLE table_name

column1 data_type(size),
column2 data_type(size),

column3 data_type(size),

....

);

table_name: name of the table.


column1 name of the first column.
data_type: Type of data we want to store in the particular column.
For example,int for integer data.
size: Size of the data we can store in a particular column. For example if for
a column we specify the data_type as int and size as 10 then this column can store
an integer
number of maximum 10 digits.

Example Query:
This query will create a table named Students with three columns, ROLL_NO, NAME
and SUBJECT.

CREATE TABLE Students

ROLL_NO int(3),

NAME varchar(20),

SUBJECT varchar(20),

);

This query will create a table named Students. The ROLL_NO field is of type int and
can store an integer number of size 3. The next two columns NAME and SUBJECT
are of type varchar and can store characters and the size 20 specifies that these
two fields can hold maximum of 20 characters.
SQL | INSERT INTO Statement
The INSERT INTO statement of SQL is used to insert a new row in a table. There are
two ways of using INSERT INTO statement for inserting rows:

1. Only values: First method is to specify only the value of data to be inserted
without the column names.
Syntax:

2. INSERT INTO table_name VALUES (value1, value2, value3,...);


3.
4. table_name: name of the table.
5. value1, value2,.. : value of first column, second column,... for the new record

6. Column names and values both: In the second method we will specify both
the columns which we want to fill and their corresponding values as shown
below:
Syntax:

7. INSERT INTO table_name (column1, column2, column3,..) VALUES ( value1,


value2, value3,..);
8. table_name: name of the table.
9. column1: name of first column, second column ...

value1, value2, value3 : value of first column, second column,... for the new
record
Queries:

Method 1 (Inserting only values) :

INSERT INTO Student VALUES ('5','HARSH','WEST BENGAL','8759770477','19');

Output:
The table Student will now look like:

ROLL_NO NAME ADDRESS PHONE Age

1 Ram Delhi 9455123451 18

2 RAMESH GURGAON 9562431543 18

3 SUJIT ROHTAK 9156253131 20

4 SURESH Delhi 9156768971 18

3 SUJIT ROHTAK 9156253131 20

2 RAMESH GURGAON 9562431543 18

5 HARSH WEST BENGAL 8759770477 19

Method 2 (Inserting values in only specified columns):

INSERT INTO Student (ROLL_NO, NAME, Age) VALUES ('5','PRATIK','19');

Output:
The table Student will now look like:
ROLL_NO NAME ADDRESS PHONE Age

1 Ram Delhi 9455123451 18

2 RAMESH GURGAON 9562431543 18

3 SUJIT ROHTAK 9156253131 20

4 SURESH Delhi 9156768971 18

3 SUJIT ROHTAK 9156253131 20

2 RAMESH GURGAON 9562431543 18

5 PRATIK null null 19

Notice that the columns for which the values are not provided are filled by null.
Which is the default values for those columns.

Using SELECT in INSERT INTO Statement


We can use the SELECT statement with INSERT INTO statement to copy rows from
one table and insert them into another table.The use of this statement is similar to
that of INSERT INTO statement. The difference is that the SELECT statement is used
here to select data from a different table. The different ways of using INSERT INTO
SELECT statement are shown below:

 Inserting all columns of a table: We can copy all the data of a table and insert
into in a different table.
Syntax:

 INSERT INTO first_table SELECT * FROM second_table;



 first_table: name of first table.
 second_table: name of second table.

We have used the SELECT statement to copy the data from one table and
INSERT INTO statement to insert in a different table.

 Inserting specific columns of a table: We can copy only those columns of a


table which we want to insert into in a different table.
Syntax:

 INSERT INTO first_table(names_of_columns1) SELECT names_of_columns2


FROM second_table;

 first_table: name of first table.
 second_table: name of second table.
 names of columns1: name of columns separated by comma(,) for table 1.
 names of columns2: name of columns separated by comma(,) for table 2.

We have used the SELECT statement to copy the data of the selected
columns only from the second table and INSERT INTO statement to insert in
first table.

 Copying specific rows from a table: We can copy specific rows from a table to
insert into another table by using WHERE clause with the SELECT statement.
We have to provide appropriate condition in the WHERE clause to select
specific rows.
Syntax:

 INSERT INTO table1 SELECT * FROM table2 WHERE condition;



 first_table: name of first table.
 second_table: name of second table.
 condition: condition to select specific rows.

Table2: LateralStudent

ROLL_NO NAME ADDRESS PHONE Age

7 SOUVIK DUMDUM 9876543210 18


ROLL_NO NAME ADDRESS PHONE Age

8 NIRAJ NOIDA 9786543210 19

9 SOMESH ROHTAK 9687543210 20

Queries:
 Method 1(Inserting all rows and columns):

 INSERT INTO Student SELECT * FROM LateralStudent;

Output:
This query will insert all the data of the table LateralStudent in the table
Student. The table Student will now look like,

ROLL_NO NAME ADDRESS PHONE Age

1 Ram Delhi 9455123451 18

2 RAMESH GURGAON 9562431543 18

3 SUJIT ROHTAK 9156253131 20

4 SURESH Delhi 9156768971 18

3 SUJIT ROHTAK 9156253131 20

2 RAMESH GURGAON 9562431543 18


ROLL_NO NAME ADDRESS PHONE Age

7 SOUVIK DUMDUM 9876543210 18

8 NIRAJ NOIDA 9786543210 19

9 SOMESH ROHTAK 9687543210 20

 Method 2(Inserting specific columns):

 INSERT INTO Student(ROLL_NO,NAME,Age) SELECT ROLL_NO, NAME, Age


FROM LateralStudent;

Output:
This query will insert the data in the columns ROLL_NO, NAME and Age of the
table LateralStudent in the table Student and the remaining columns in the
Student table will be filled by null which is the default value of the remaining
columns. The table Student will now look like,

ROLL_NO NAME ADDRESS PHONE Age

1 Ram Delhi 9455123451 18

2 RAMESH GURGAON 9562431543 18

3 SUJIT ROHTAK 9156253131 20

4 SURESH Delhi 9156768971 18


ROLL_NO NAME ADDRESS PHONE Age

3 SUJIT ROHTAK 9156253131 20

2 RAMESH GURGAON 9562431543 18

7 SOUVIK null null 18

8 NIRAJ null null 19

9 SOMESH null null 20

 Select specific rows to insert:

 INSERT INTO Student SELECT * FROM LateralStudent WHERE Age = 18;

Output:
This query will select only the first row from table LateralStudent to insert
into the table Student. The table Student will now look like,

ROLL_NO NAME ADDRESS PHONE Age

1 Ram Delhi 9455123451 18

2 RAMESH GURGAON 9562431543 18

3 SUJIT ROHTAK 9156253131 20

4 SURESH Delhi 9156768971 18


ROLL_NO NAME ADDRESS PHONE Age

3 SUJIT ROHTAK 9156253131 20

2 RAMESH GURGAON 9562431543 18

7 SOUVIK DUMDUM 9876543210 18


SQL | Join (Cartesian Join & Self Join)
SQL| JOIN(Inner, Left, Right and Full Joins)
In this article, we will discuss about the remaining two JOINS:
 CARTESIAN JOIN
 SELF JOIN
Consider the two tables below:

StudentCourse

1. CARTESIAN JOIN: The CARTESIAN JOIN is also known as CROSS JOIN. In a


CARTESIAN JOIN there is a join for each row of one table to every row of
another table. This usually happens when the matching column or WHERE
condition is not specified.
 In the absence of a WHERE condition the CARTESIAN JOIN will behave
like a CARTESIAN PRODUCT . i.e., the number of rows in the result-set
is the product of the number of rows of the two tables.
 In the presence of WHERE condition this JOIN will function like a INNER
JOIN.
 Generally speaking, Cross join is similar to an inner join where the join-
condition will always evaluate to True
Syntax:

SELECT table1.column1 , table1.column2, table2.column1...

FROM table1

CROSS JOIN table2;

table1: First table.


table2: Second table

Example Queries(CARTESIAN JOIN):


 In the below query we will select NAME and Age from Student table and
COURSE_ID from StudentCourse table. In the output you can see that each
row of the table Student is joined with every row of the table StudentCourse.
The total rows in the result-set = 4 * 4 = 16.

 SELECT Student.NAME, Student.AGE, StudentCourse.COURSE_ID

 FROM Student

 CROSS JOIN StudentCourse;


Output:

2. SELF JOIN: As the name signifies, in SELF JOIN a table is joined to itself. That
is, each row of the table is joined with itself and all other rows depending on
some conditions. In other words we can say that it is a join between two
copies of the same table.Syntax:

3. SELECT a.coulmn1 , b.column2

4. FROM table_name a, table_name b

5. WHERE some_condition;

6.

7. table_name: Name of the table.


8. some_condition: Condition for selecting the rows.

Example Queries(SELF JOIN):

SELECT a.ROLL_NO , b.NAME

FROM Student a, Student b

WHERE a.ROLL_NO < b.ROLL_NO;

Output:
SQL | Join (Inner, Left, Right and Full
Joins)
A SQL Join statement is used to combine data or rows from two or more tables
based on a common field between them. Different types of Joins are:

 INNER JOIN
 LEFT JOIN
 RIGHT JOIN
 FULL JOIN
Consider the two tables below:

Student
StudentCourse

The simplest Join is INNER JOIN.

1. INNER JOIN: The INNER JOIN keyword selects all rows from both the tables as
long as the condition satisfies. This keyword will create the result-set by
combining all rows from both the tables where the condition satisfies i.e
value of the common field will be same.
Syntax:

2. SELECT table1.column1,table1.column2,table2.column1,....

3. FROM table1

4. INNER JOIN table2

5. ON table1.matching_column = table2.matching_column;

6.

7.

8. table1: First table.


9. table2: Second table
10. matching_column: Column common to both the tables.
Note: We can also write JOIN instead of INNER JOIN. JOIN is same as INNER
JOIN.

Example Queries(INNER JOIN)


 This query will show the names and age of students enrolled in
different courses.

 SELECT StudentCourse.COURSE_ID, Student.NAME, Student.AGE FROM


Student

 INNER JOIN StudentCourse

 ON Student.ROLL_NO = StudentCourse.ROLL_NO;

Output:

11. LEFT JOIN: This join returns all the rows of the table on the left side of the join
and matching rows for the table on the right side of join. The rows for which
there is no matching row on right side, the result-set will contain null. LEFT
JOIN is also known as LEFT OUTER JOIN.Syntax:

12. SELECT table1.column1,table1.column2,table2.column1,....


13. FROM table1

14. LEFT JOIN table2

15. ON table1.matching_column = table2.matching_column;

16.

17.

18. table1: First table.

19. table2: Second table

20. matching_column: Column common to both the tables.

Note: We can also use LEFT OUTER JOIN instead of LEFT JOIN, both are same.

Example Queries(LEFT JOIN):

SELECT Student.NAME,StudentCourse.COURSE_ID

FROM Student

LEFT JOIN StudentCourse

ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Output:

21. RIGHT JOIN: RIGHT JOIN is similar to LEFT JOIN. This join returns all the rows
of the table on the right side of the join and matching rows for the table on
the left side of join. The rows for which there is no matching row on left side,
the result-set will contain null. RIGHT JOIN is also known as RIGHT OUTER
JOIN.Syntax:

22. SELECT table1.column1,table1.column2,table2.column1,....

23. FROM table1

24. RIGHT JOIN table2

25. ON table1.matching_column = table2.matching_column;

26.

27.

28. table1: First table.

29. table2: Second table

30. matching_column: Column common to both the tables.


Note: We can also use RIGHT OUTER JOIN instead of RIGHT JOIN, both are
same.

Example Queries(RIGHT JOIN):

SELECT Student.NAME,StudentCourse.COURSE_ID

FROM Student

RIGHT JOIN StudentCourse

ON StudentCourse.ROLL_NO = Student.ROLL_NO;

Output:

31. FULL JOIN: FULL JOIN creates the result-set by combining result of both LEFT
JOIN and RIGHT JOIN. The result-set will contain all the rows from both the
tables. The rows for which there is no matching, the result-set will
contain NULL values.Syntax:

32. SELECT table1.column1,table1.column2,table2.column1,....


33. FROM table1

34. FULL JOIN table2

35. ON table1.matching_column = table2.matching_column;

36.

37.

38. table1: First table.

39. table2: Second table

40. matching_column: Column common to both the tables.

Example Queries(FULL JOIN):

SELECT Student.NAME,StudentCourse.COURSE_ID

FROM Student

FULL JOIN StudentCourse

ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Output:

SQL | JOIN (Cartesian Join, Self Join)


SQL | Alternative Quote Operator
This post is a continuation of the SQL Concatenation Operator.
Now, suppose we want to use apostrophe in our literal value but we can’t use it
directly.
See Incorrect code:
SELECT id, first_name, last_name, salary,
first_name||’ has salary’s ‘||salary
AS “new” FROM one

So above we are getting error, because Oracle server thinking that the first
apostrophe is for the starting literal and the second apostrophe is for the ending
literal, so what about the third apostrophe???. That’s why we get error.
Alternative Quote Operator(q):
To overcome the above problem Oracle introduce an operator known
as Alternative Quote Operator(q).
Let’s see through an example:

Query that uses Alternative Quote Operator(q)


SELECT id, first_name, last_name, salary,
first_name||q'{ has salary's }'||salary
AS "new" FROM myTable

Output:
See, we are able to use apostrophe in the
new column as a literal value of myTable

ID FIRST_NAME LAST_NAME SALARY new


3 Shane Watson 50000 Shane has salary's 50000
1 Rajat Rawat 10000 Rajat has salary's 10000
2 Geeks ForGeeks 20000 Geeks has salary's 20000
3 MS Dhoni 90000 MS has salary's 90000

Here above see, q'{ indicates starting of our literal value and then we use }’ which
indicates end of our literal value. So see here we have used apostrophe in our
literal value easily(means we easily use ‘s in salary) without any error that’s why we
get output as Rajat has salary‘s 50000.
So to use apostrophe in literal we first need to use q which is known as alternative
quote operator after that we need to use an apostrophe ‘ and after that we need to
use a delimiter and after delimiter we write our literal value, when we finished
writing our literal value then again we need to close the delimiter which we
have opened before and after that we need to put an apostrophe again and hence
in this way we can use apostrophe in our literal value. This concept is known
as Alternative Quote Operator(q).
We can use any character such as {, <, (, [, ! or any character as delimiter. These
characters are known as delimiters.
1 another example
:

Without using Quote Operator:

Here we get Error since we are using apostrophe in our literal value directly.

Error code below:


SELECT id, name, dept, name||' work's in '||dept||'
department' AS "work" FROM myTable2

Using Quote Operator:


SELECT id, name, dept, name||q'[ work’s in ‘]’||dept||’
department’ AS “work” FROM myTable2

Output:
See, we are able to use apostrophe in the
work column as a literal value of myTable2

ID NAME DEPT work


1 RR Executive RR work's in 'Executive department
2 GFG HR GFG work's in 'HR department
3 Steve Sales Steve work's in 'Sales department
4 Bhuvi CSE Bhuvi work's in 'CSE department

Here above see, q'[ indicates starting of our literal value and the we use ]’ which
indicate end of our literal value. So see here we have used apostrophe in our literal
value easily(means we easily use ‘s in work) without any error that’s why we get
output as RR work’s in Executive Department.]
Here above we use [ as delimiter so it is not a limitation in using delimiter means
we can use any character as delimiter.
SQL | Concatenation Operator
Prerequisite: Basic Select statement, Insert into clause, SQL Create Clause, SQL
Aliases
|| or concatenation operator is use to link columns or character strings. We can
also use a literal. A literal is a character, number or date that is included in the
SELECT statement.
Let’s demonstrate it through an example:

Syntax:

SELECT id, first_name, last_name, first_name || last_name,

salary, first_name || salary FROM myTable

Output (Third and Fifth Columns show values concatenated by operator ||)

id first_name last_name first_name||last_name salary first_name||salary

1 Rajat Rawat RajatRawat 10000 Rajat10000

2 Geeks ForGeeks GeeksForGeeks 20000 Geeks20000

3 Shane Watson ShaneWatson 50000 Shane50000

4 Kedar Jadhav KedarJadhav 90000 Kedar90000

Note: Here above we have used || which is known as Concatenation


operator which is used to link 2 or as many columns as you want in your select
query and it is independent of the datatype of column. Here above we have linked
2 columns i.e, first_name+last_name as well as first_name+salary.

We can also use literals in the concatenation operator. Let’s see:


Example 1: Using character literal
Syntax:

SELECT id, first_name, last_name, salary,

first_name||' has salary '||salary as "new" FROM myTable

Output : (Concatenating three values and giving a name 'new')


id first_name last_name salary new

1 Rajat Rawat 10000 Rajat has salary 10000

2 Geeks ForGeeks 20000 Geeks has salary 20000

3 Shane Watson 50000 Shane has salary 50000

4 Kedar Jadhav 90000 Kedar has salary 90000

Note: Here above we have used has salary as a character literal in our select
statement. Similarly we can use number literal or date literal according to our
requirement.
Example 2: Using character as well as number literal
Syntax:

SELECT id, first_name, last_name, salary, first_name||100||'

has id '||id AS "new" FROM myTable

Output (Making readable output by concatenating a string

with values)

id first_name last_name salary new

1 Rajat Rawat 10000 Rajat100 has id 1

2 Geeks ForGeeks 20000 Geeks100 has id 2

3 Shane Watson 50000 Shane100 has id 3

4 Kedar Jadhav 90000 Kedar100 has id 4

Here above we have used has salary as a character literal as well as 100 as number
literal in our select statement.
SQL | MINUS Operator
The Minus Operator in SQL is used with two SELECT statements. The MINUS
operator is used to subtract the result set obtained by first SELECT query from the
result set obtained by second SELECT query. In simple words, we can say that
MINUS operator will return only those rows which are unique in only first SELECT
query and not those rows which are common to both first and second SELECT
queries.

Pictorial Representation:

As you can see is in the above diagram, the MINUS operator will return only those
rows which are present in the result set from Table1 and not present in the result
set of Table2.
Basic Syntax:

SELECT column1 , column2 , ... columnN

FROM table_name

WHERE condition

MINUS

SELECT column1 , column2 , ... columnN


FROM table_name

WHERE condition;

columnN: column1, column2.. are the name of columns of the table.


Important Points:

 The WHERE clause is optional in the above query.


 The number of columns in both SELECT statements must be same.
 The data type of corresponding columns of both SELECT statement must be
same.
Sample Tables:
Table1

Queries:
SELECT NAME, AGE , GRADE

FROM Table1

MINUS

SELECT NAME, AGE, GRADE

FROM Table2

Output:
The above query will return only those rows which are unique in ‘Table1’. We can
clearly see that values in the fields NAME, AGE and GRADE for the last row in both
tables are same. Therefore, the output will be the first three rows from Table1. The
obtained output is shown below:

Note: The MINUS operator is not supported with all databases. It is supported by
Oracle database but not SQL server or PostgreSQL.
SQL | DIVISION
Division is typically required when you want to find out entities that are interacting
with all entities of a set of different type entities.
The division operator is used when we have to evaluate queries which contain the
keyword ‘all’.
Some instances where division operator is used are:
 Which person has account in all the banks of a particular city?
 Which students have taken all the courses required to graduate?
In all these queries, the description after the keyword ‘all’ defines a set which
contains some elements and the final result contains those units who satisfy these
requirements.

Important: Division is not supported by SQL implementations. However, it can be


represented using other operations.(like cross join, Except, In )

SQL Implementation of Division

Given two relations(tables): R(x,y) , S(y).


R and S : tables
x and y : column of R
y : column of S
R(x,y) div S(y) means gives all distinct values of x from R that are associated with all
values of y in S.
Computation of Division : R(x,y) div S(y)
Steps:
 Find out all possible combinations of S(y) with R(x) by computing R(x) x(cross
join) S(y), say r1
 Subtract actual R(x,y) from r1, say r2
 x in r2 are those that are not associated with every value in S(y); therefore
R(x)-r2(x) gives us x
that are associated with all values in S
Queries
1. Implementation 1:

2. SELECT * FROM R
3. WHERE x not in ( SELECT x FROM (
4. (SELECT x , y FROM (select y from S ) as p cross join
5. (select distinct x from R) as sp)
6. EXCEPT
7. (SELECT x , y FROM R) ) AS r );
8.

9. Implementation 2 : Using correlated subquery

10. SELECT * FROM R as sx


11. WHERE NOT EXISTS (
12. (SELECT p.y FROM S as p )
13. EXCEPT
14. (SELECT sp.y FROM R as sp WHERE sp.x = sx.x ) );
15.

Relational algebra

Using steps which is mention above:

All possible combinations

r1 ← πx(R) x S
x values with “incomplete combinations”,
r2x ← πx(r1-R)
and
result ← πx(R)-r2x

R div S = πx(R)- πx((πx(R) x S) – R)


Examples

Supply Schema

Here sid means supplierID and pid means partsID.


Tables: suppliers(sid,pid) , parts(pid)

1. Find suppliers that supply all parts.


Ans 1 : Using implementation 1

SELECT * FROM suppliers

WHERE sid not in ( SELECT sid FROM ( (SELECT sid, pid FROM (select pid from parts)
as p

cross join

(select distinct sid from supplies) as sp)

EXCEPT

(SELECT sid, pid FROM supplies)) AS r );


Ans 2: Using implementation 2

SELECT * FROM suppliers as s

WHERE NOT EXISTS (( SELECT p.pid FROM parts as p )

EXCEPT

(SELECT sp.pid FROM supplies sp WHERE sp.sid = s.sid ) );

Company schema
2. List employees who work on all projects controlled by dno=4.
Ans 1. Using implementation 1

SELECT * FROM employee AS e

WHERE ssn NOT IN (

SELECT essn FROM (

(SELECT essn, pno FROM (select pno from project where dno=4)

as p cross join (select distinct essn from works_on) as w)

EXCEPT (SELECT essn, pno FROM works_on)) AS r );

Ans 2. Using implementation 2

SELECT * FROM employee AS e

WHERE NOT EXISTS (

(SELECT pno FROM project WHERE dno = 4)

EXCEPT

(SELECT pno FROM works_on WHERE essn = e.ssn) );

Important : For division correlated query seems simpler to write but may expensive
to execute.
Some more Examples.

1. List supplier who supply all ‘Red’ Parts.(supply schema)


2. Retrieve the names of employees, who work on all the projects that ‘John
Smith’ works (company schema)
SQL | NOT Operator
NOT Syntax
SELECT column1, colomn2, … FROM table_name WHERE NOT condition;
Demo Database
Below is a selection from the “Customers” table in the Northwind sample database:

CUSTOMER ID CUSTOMER NAME CITY POSTALCODE COUNTRY

1 John Wick New York 1248 USA

2 Around the Horn London WA1 1DP UK

3 Rohan New Delhi 100084 India

NOT Example
The following SQL statement selects all fields from “Customers” where country is
not “UK”
SELECT * FROM Customers WHERE NOT Country=’UK’;

CUSTOMER ID CUSTOMER NAME CITY POSTALCODE COUNTRY

1 John Wick New York 1248 USA

3 Rohan New Delhi 100084 India

Combining AND, OR and NOT


You can also combine the AND, OR and NOT operators.
Example:
1.) SELECT * FROM Customers WHERE NOT Country=’USA’ AND NOT Country=’UK’;

CUSTOMER ID CUSTOMER NAME CITY POSTALCODE COUNTRY


3 Rohan New Delhi 100084 India
SQL | BETWEEN & IN Operator
BETWEEN
The SQL BETWEEN condition allows you to easily test if an expression is within a
range of values (inclusive). The values can be text, date, or numbers. It can be used
in a SELECT, INSERT, UPDATE, or DELETE statement. The SQL BETWEEN Condition
will return the records where expression is within the range of value1 and value2.

Syntax:

SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;

Examples:
Consider the following Employee Table,

Queries

 Using BETWEEN with Numeric Values:


List all the Employee Fname, Lname who is having salary between 30000 and
45000.

 SELECT Fname, Lname


 FROM Employee

 WHERE Salary

BETWEEN 30000 AND 45000;

Output:

 Using BETWEEN with Date Values:


Find all the Employee having Date of Birth Between 01-01-1985 and 12-12-
1990.

 SELECT Fname, Lname

 FROM Employee

 where DOB

BETWEEN '1985-01-01' AND '1990-12-30';


Output:

 Using NOT operator with BETWEEN


Find all the Employee name whose salary is not in the range of 30000 and
45000.

 SELECT Fname, Lname

 FROM Emplyoee

 WHERE Salary

NOT BETWEEN 30000 AND 45000;

Output:

IN
IN operator allows you to easily test if the expression matches any value in the list
of values. It is used to remove the need of multiple OR condition in SELECT, INSERT,
UPDATE or DELETE. You can also use NOT IN to exclude the rows in your list.
Syntax:
SELECT column_name(s)

FROM table_name

WHERE column_name IN (list_of_values);

Queries
 Find the Fname, Lname of the Employees who have Salary equal to 30000,
40000 or 25000.

 SELECT Fname, Lname

 FROM Employee

WHERE Salary IN (30000, 40000, 25000);

Output:

 Find the Fname, Lname of all the Employee who have Salary not equal to
25000 or 30000.

 SELECT Fname, Lname

 FROM Employee

WHERE Salary NOT IN (25000, 30000);


Output:
SQL | CHECK Constraint
SQL Constraints
Check Constraint is used to specify a predicate that every tuple must satisfy in a
given relation. It limits the values that a column can hold in a relation.
 The predicate in check constraint can hold a sub query.
 Check constraint defined on an attribute restricts the range of values for that
attribute.
 If the value being added to an attribute of a tuple violates the check
constraint, the check constraint evaluates to false and the corresponding
update is aborted.
 Check constraint is generally specified with the CREATE TABLE command in
SQL.
Syntax:

CREATE TABLE pets(

ID INT NOT NULL,

Name VARCHAR(30) NOT NULL,

Breed VARCHAR(20) NOT NULL,

Age INT,

GENDER VARCHAR(9),

PRIMARY KEY(ID),

check(GENDER in ('Male', 'Female', 'Unknown'))

);

Note: The check constraint in the above SQL command restricts the GENDER to
belong to only the categories specified. If a new tuple is added or an existing tuple
in the relation is updated with a GENDER that doesn’t belong to any of the three
categories mentioned, then the corresponding database update is aborted.
Query
Constraint: Only students with age >= 17 are can enroll themselves in a university.
Schema for student database in university:
CREATE TABLE student(

StudentID INT NOT NULL,

Name VARCHAR(30) NOT NULL,

Age INT NOT NULL,

GENDER VARCHAR(9),

PRIMARY KEY(ID),

check(Age >= 17)

);

Student relation:

STUDENTID NAME AGE GENDER

1001 Ron 18 Male

1002 Sam 17 Male

1003 Georgia 17 Female

1004 Erik 19 Unknown

1005 Christine 17 Female

Explanation: In the above relation, the age of all students is greater than equal to 17
years, according to the constraint mentioned in the check statement in the schema
of the relation. If, however following SQL statement is executed:
INSERT INTO student(STUDENTID, NAME, AGE, GENDER)

VALUES (1006, 'Emma', 16, 'Female');

There won’t be any database update and as the age < 17 years.

Different options to use Check constraint:


 With alter: Check constraint can also be added to an already created relation
using the syntax:

alter table TABLE_NAME modify COLUMN_NAME check(Predicate);

 Giving variable name to check constraint:Check constraints can be given a


variable name using the syntax:

alter table TABLE_NAME add constraint CHECK_CONST check (Predicate);

 Remove check constraint: Check constraint can be removed from the relation
in the database from SQL server using the syntax:

alter table TABLE_NAME drop constraint CHECK_CONSTRAINT_NAME;

 Drop check constraint: Check constraint can be dropped from the relation in
the database in MySQL using the syntax:

alter table TABLE_NAME drop check CHECK_CONSTRAINT_NAME;


SQL Server Mathematical functions
(SQRT, PI, SQUARE, ROUND,
CEILING & FLOOR)
Mathematical functions are present in SQL server which can be used to perform
mathematical calculations. Some commonly used mathematical functions are given
below:
1. SQRT():
SQRT() function is the most commonly used function. It takes any numeric values
and returns the square root value of that number.
Syntax:

SELECT SQRT(..value..)

Example:
2. PI(): There are calculations which require use of pi. Using pi() function, value of PI
can be used anywhere in the query.
Syntax:

SELECT PI()

Example:

3. SQUARE(): SQUARE() function is used to find the square of any number.


Syntax:

SELECT SQUARE(..value..)
Example:

4. ROUND(): ROUND() function is used to round a value to the nearest specified


decimal place.
Syntax:

SELECT ROUND(..value.., number_of_decimal_places)


Example:

5. CEILING() and FLOOR()


CEILING(): CEILING() function is used to find the next highest value (integer).
Syntax:

SELECT CEILING(..value..)

FLOOR(): FLOOR() function returns the next lowest value (integer).


Syntax:

SELECT FLOOR(..value..)
Example:
SQL | Conversion Function

In some cases, the Server uses data of one type where it expects data of a different
data type. This can happen when the Server can automatically convert the data to
the expected data type. This data type conversion can be done implicitly by the
Server, or explicitly by the user.

Implicit Data-Type Conversion :

In this type of conversion the data is converted from one type to another implicitly
(by itself/automatically).

FROM TO

VARCHAR2 or CHAR NUMBER


FROM TO

VARCHAR2 or CHAR DATE

DATE VARCHAR2

NUMBER VARCHAR2

EXAMPLE :

1. QUERY:

2. SELECT employee_id,first_name,salary

3. FROM employees

WHERE salary > 15000;

OUTPUT :

EMPLOYEE_ID FIRST_NAME SALARY

100 Steven 24000

101 Neena 17000


EMPLOYEE_ID FIRST_NAME SALARY

102 lex 17000

4. QUERY:

5. SELECT employee_id,first_name,salary

6. FROM employees

WHERE salary > '15000';

OUTPUT :

EMPLOYEE_ID FIRST_NAME SALARY

100 Steven 24000

101 Neena 17000

102 lex 17000

Here we see the output of both queries came out to be same,inspite of 2nd
query using ‘15000’ as text, it is automatically converted into int data type.
Explicit Data-Type Conversion :

TO_CHAR Function :

TO_CHAR function is used to typecast a numeric or date input to character type


with a format model (optional).
SYNTAX :

TO_CHAR(number1, [format], [nls_parameter])

Using the TO_CHAR Function with Dates :


SYNTAX :

TO_CHAR(date, ’format_model’)

The format model:


 Must be enclosed in single quotation marks and is case
sensitive
 Can include any valid date format element
 Has an fm element to remove padded blanks or
suppress leading zeros
 Is separated from the date value by a comma
EXAMPLE :

SELECT employee_id, TO_CHAR(hire_date, ’MM/YY’) Month_Hired

FROM employees

WHERE last_name = ’Higgins’;

OUTPUT :

EMPLOYEE_ID MONTH_HIRED

205 06/94

Elements of the Date Format Model :

YYYY Full year in Numbers

YEAR Year spelled out

MM Two digit value for month

MONTH Full name of the month


MON Three Letter abbreviation of the month

DY Three letter abbreviation of the day of the week

DAY Full Name of the of the week

DD Numeric day of the month

Elements of the Date Format Model :

Date Format Elements – Time Formats :


Use the formats listed in the following tables to display time information and
literals and to change numerals to spelled numbers.

ELEMENT DESCRIPTION

AM or PM Meridian indicater

A.M. or P.M. Meridian indicater with periods

HH or HH12 or HH24 Hour of day,or hour (1-12),or hour (0-23)

MI Minute 0-59
ELEMENT DESCRIPTION

SS Second 0-59

SSSSS Second past Mid Night 0-86399

Other Formats :

ELEMENT DESCRIPTION

/., Punctuation is reproduced in the result

“of the” Quoted string is reproduced in the result

Specifying Suffixes to Influence Number Display :

ELEMENT DESCRIPTION

TH Ordinal Number (for example DDTH for 4TH

SP Spelled out number (for example DDSP for FOUR

SPTH or spelled out ordinal numbers (for example DDSPTH for

THSP FOURTH
EXAMPLE :

SELECT last_name,

TO_CHAR(hire_date, ’fmDD Month YYYY’)

AS HIREDATE

FROM employees;

OUTPUT :

LASTNAME HIIREDATE

Austin 25 January 2005

Shubham 20 June 2004

Nishant 15 January 1999

Ankit 15 July 1995

Vanshika 5 August 2004

Kusum 10 June 1994

Faviet 11 March 2005


LASTNAME HIIREDATE

King 9 April 1996

Using the TO_CHAR Function with Numbers :


SYNTAX :

TO_CHAR(number, ’format_model’)

These are some of the format elements you can use


with the TO_CHAR function to display a number value
as a character :

9 Represent a number

0 Forces a zero to be displayed

$ places a floating dollar sign

L Uses the floating local currency symbol

. Print a decimal point

, Prints a Thousand indicator

EXAMPLE :
SELECT TO_CHAR(salary, ’$99,999.00’) SALARY

FROM employees

WHERE last_name = ’Ernst’;

OUTPUT :

SALARY

$5000

Using the TO_NUMBER and TO_DATE Functions :

Convert a character string to a number format using the TO_NUMBER function :

TO_NUMBER(char[, ’format_model’])

Convert a character string to a date format using the TO_DATE function:

TO_DATE(char[, ’format_model’])

These functions have an fx modifier. This modifier specifies the exact matching for
the character argument and date format model of a TO_DATE function.
EXAMPLE :

SELECT last_name, hire_date

FROM employees

WHERE hire_date = TO_DATE(’May 24, 1999’, ’fxMonth DD, YYYY’);

OUTPUT :
LASTNAME HIREDATE

Kumar 24-MAY-99
SQL | Conditional Expressions
Following are Conditional Expressions in SQL
1. The CASE Expression: Let you use IF-THEN-ELSE statements without having to
invoke procedures.
In a simple CASE expression, the SQL searches for the first WHEN……THEN
pair for which expr is equal to comparison_expr and returns return_expr. If
above condition is not satisfied, an ELSE clause exists, the SQL returns
else_expr. Otherwise, returns NULL.
We cannot specify literal null for the return_expr and the else_expr. All of the
expressions(expr, comparison_expr, return_expr) must be of the same data
type.
Syntax:

2. CASE expr WHEN comparison_expr1 THEN return_expr1


3. [WHEN comparison_expr2 THEN return_expr2
4. .
5. .
6. .
7. WHEN comparison_exprn THEN return_exprn
8. ELSE else_expr]
9. END

Example:

Input :
SELECT first_name, dpartment_id, salary,
CASE dpartment_id WHEN 50 THEN 1.5*salary
WHEN 12 THEN 2.0*salary
ELSE salary
END "REVISED SALARY"
FROM Employee;
Output :

Explanation: In above SQL statements, the value of department_id is


decoded. If it is 50 then salary is made 1.5 times, if it is 12 then salary is made
2 times, else there is no change in salary.
10. The DECODE Function : Facilitates conditional inquiries by doing the work of
a CASE or IF-THEN-ELSE statement.
The DECODE function decodes an expression in a way similar to the IF-THEN-
ELSE logic used in various languages. The DECODE function decodes
expression after comparing it to each search value. If the expression is the
same as search, result is returned.
If the default value is omitted, a null value is returned where a search value
does not match any of the result values.
Syntax:

11. DECODE(col/expression, search1, result1


12. [, search2, result2,........,]
13. [, default])
14. Input :
15. SELECT first_name, dpartment_id, salary,
16. DECODE(dpartment_id, 50, 1.5*salary,
17. 12, 2.0*salary,
18. salary)
19. "REVISED SALARY"
20. FROM Employee;
Output :

Explanation: In above SQL statements, the value of department_id is tested.


If it is 50 then salary is made 1.5 times, if it is 12 then salary is made 2 times,
else there is no change in salary.
21. COALESCE : Returns the first non-null argument. Null is returned only if all
arguments are null. It is often used to substitute a default value for null
values when data is retrieved for display.
NOTE: Same as CASE expressions, COALESCE also will not evaluate the
arguments to the right of the first non-null argument found.
Syntax:

22. COALESCE(value [, ......] )


23. Input:
24. SELECT COALESCE(last_name, '- NA -')
25. from Employee;
Output:

Explanation: “- NA -” will be displayed in place where last name is null else


respective last names will be shown.
26. GREATEST: Returns the largest value from a list of any number of
expressions. Comparison is case sensitive. If datatypes of all the expressions
in the list are not same, rest all expressions are converted to the datatype of
the first expression for comparison and if this conversion is not possible, SQL
will throw an error.
NOTE: Returns null if any expression in the list is null.
Syntax:

27. GREATEST(expr1, expr2 [, .....] )

 Input:
 SELECT GREATEST('XYZ', 'xyz')
 from dual;
 Output:
 GREATEST('XYZ', 'xyz')
 xyz

 Explanation: ASCII value of small alphabets is greater.

 Input:
 SELECT GREATEST('XYZ', null, 'xyz')
 from dual;

 Output:
 GREATEST('XYZ', null, 'xyz')
 -

Explanation: Since null is present hence, null will be shown as output


(as mentioned to note in description above).
28. IFNULL: If expr1 is not NULL, returns expr1; otherwise it returns expr2.
Returns a numeric or string value, depending on the context in which it is
used.
Syntax:

29. IFNULL(expr1, expr2)

 Input:
 SELECT IFNULL(1,0)
 FROM dual;
 Output:
 -
 1

 Explanation : Since, no expression is null.

 Input:
 SELECT IFNULL(NULL,10)
 FROM dual;

 Output:
 --
 10

 Explanation:Since, expr1 is null hence, expr2 is shown.


30. IN: Checks whether a value is present within a set of values and can be used
with WHERE, CHECK and creation of views.
NOTE: Same as CASE and COALESCE expressions, IN also will not evaluate the
arguments to the right of the first non-null argument found.
Syntax:

31. WHERE column IN (x1, x2, x3 [,......] )


32. Input:
33. SELECT * from Employee
34. WHERE dpartment_id IN(50, 12);

Output:

Explanation:All data of Employees is shown with department ID 50 or 12.


35. LEAST: Returns the smallest value from a list of any number of expressions.
Comparison is case sensitive. If datatypes of all the expressions in the list are
not same, rest all expressions are converted to the datatype of the first
expression for comparison and if this conversion is not possible, SQL will
throw an error.
NOTE: Returns null if any expression in the list is null.
Syntax:

LEAST(expr1, expr2 [, ......])


 strong>Input:
 SELECT LEAST('XYZ', 'xyz')
 from dual;

 Output:
 LEAST('XYZ', 'xyz')
 XYZ
Explanation: ASCII value of capital alphabets is smaller.



 Input:
 SELECT LEAST('XYZ', null, 'xyz')
 from dual;

 Output:
 LEAST('XYZ', null, 'xyz')
 -
Explanation: Since null is present hence, null will be shown as output
(as mentioned to note in description above).
36. NULLIF: Returns a null value if value1=value2, otherwise it returns value1.
Syntax:

37. NULLIF(value1, value2)

Example:

Input:
SELECT NULLIF(9995463931, contact_num)
from Employee;
Output:

Explanation: NULL is displayed for the Employee whose number is matched with
the given number. For rest of the Employees value1 is returned.
SQL general functions | NVL, NVL2,
DECODE, COALESCE, NULLIF,
LNNVL and NANVL
In this article, we’ll be discussing some powerful SQL general functions, which are –
NVL, NVL2, DECODE, COALESCE, NULLIF, LNNVL and NANVL.

These functions work with any data type and pertain to the use of null values in the
expression list. These are all single row function i.e. provide one result per row.
 NVL(expr1, expr2) : In SQL, NVL() converts a null value to an actual value.
Data types that can be used are date, character and number. Data type must
match with each other i.e. expr1 and expr2 must of same data type.
Syntax –

 NVL (expr1, expr2)

expr1 is the source value or expression that may contain a null.


expr2 is the target value for converting the null.
Example –

SELECT salary, NVL(commission_pct, 0),

(salary*12) + (salary*12*NVL(commission_pct, 0))

annual_salary FROM employees;


Output :

 NVL2(expr1, expr2, expr3) : The NVL2 function examines the first expression.
If the first expression is not null, then the NVL2 function returns the second
expression. If the first expression is null, then the third expression is
returned i.e. If expr1 is not null, NVL2 returns expr2. If expr1 is null, NVL2
returns expr3. The argument expr1 can have any data type.
Syntax –

NVL2 (expr1, expr2, expr3)

expr1 is the source value or expression that may contain null


expr2 is the value returned if expr1 is not null
expr3 is the value returned if expr2 is null
Example –

SELECT last_name, salary, commission_pct,

NVL2(commission_pct, ’SAL+COMM’, ’SAL’)

income FROM employees;

Output :
 DECODE() : Facilitates conditional inquiries by doing the work of a CASE or IF-
THEN-ELSE statement.
The DECODE function decodes an expression in a way similar to the IF-THEN-
ELSE logic used in various languages. The DECODE function decodes
expression after comparing it to each search value. If the expression is the
same as search, result is returned.
If the default value is omitted, a null value is returned where a search value
does not match any of the result values.
Syntax –

DECODE(col|expression, search1, result1

[, search2, result2,...,][, default])

Example –

SELECT last_name, job_id, salary,

DECODE(job_id, ’IT_PROG’, 1.10*salary,

’ST_CLERK’, 1.15*salary,

’SA_REP’, 1.20*salary,salary)

REVISED_SALARY FROM employees;

Output :

 COALESCE() : The COALESCE() function examines the first expression, if the


first expression is not null, it returns that expression; Otherwise, it does a
COALESCE of the remaining expressions.
The advantage of the COALESCE() function over the NVL() function is that the
COALESCE function can take multiple alternate values. In simple words
COALESCE() function returns the first non-null expression in the list.
Syntax –

COALESCE (expr_1, expr_2, ... expr_n)

Examples –

SELECT last_name,

COALESCE(commission_pct, salary, 10) comm

FROM employees ORDER BY commission_pct;

Output :

 NULLIF() : The NULLIF function compares two expressions. If they are equal,
the function returns null. If they are not equal, the function returns the first
expression. You cannot specify the literal NULL for first expression.
Syntax –

NULLIF (expr_1, expr_2)

Examples –

SELECT LENGTH(first_name) "expr1",


LENGTH(last_name) "expr2",

NULLIF(LENGTH(first_name),LENGTH(last_name))

result FROM employees;

Output :

 LNNVL() : LNNVL evaluate a condition when one or both operands of the


condition may be null. The function can be used only in the WHERE clause of
a query. It takes as an argument a condition and returns TRUE if the
condition is FALSE or UNKNOWN and FALSE if the condition is TRUE.
Syntax –

LNNVL( condition(s) )

Examples –

SELECT COUNT(*) FROM employees

WHERE commission_pct < .2;

Output :
Now the above examples does not considered those employees who have no
commission at all.
To include them as well we use LNNVL()

SELECT COUNT(*) FROM employees

WHERE LNNVL(commission_pct >= .2);

Output :

 NANVL() : The NANVL function is useful only for floating-point numbers of


type BINARY_FLOAT or BINARY_DOUBLE. It instructs the Database to return
an alternative value n2 if the input value n1 is NaN (not a number). If n1 is
not NaN, then database returns n1. This function is useful for mapping NaN
values to NULL.
Syntax –

NANVL( n1 , n2 )

Consider the following table named nanvl_demo :

Example –

SELECT bin_float, NANVL(bin_float,0)

FROM nanvl_demo;
Output :
SQL | Character Functions with
Examples
Character functions accept character inputs and can return either characters or
number values as output. SQL provides a number of different character datatypes
which includes – CHAR, VARCHAR, VARCHAR2, LONG, RAW, and LONG RAW. The
various datatypes are categorized into three different datatypes :

1. VARCHAR2 – A variable-length character datatype whose data is converted by


the RDBMS.
2. CHAR – The fixed-length datatype.
3. RAW – A variable-length datatype whose data is not converted by the RDBMS,
but left in “raw” form.
Note : When a character function returns a character value, that value is always of
type VARCHAR2 ( variable length ), with the following two exceptions: UPPER and
LOWER. These functions convert to upper and to lower case, respectively, and
return the CHAR values ( fixed length ) if the strings they are called on to convert
are fixed-length CHAR arguments.
Character Functions
SQL provides a rich set of character functions that allow you to get information
about strings and modify the contents of those strings in multiple ways. Character
functions are of the following two types:
1. Case-Manipulative Functions (LOWER, UPPER and INITCAP)
2. Character-Manipulative Functions (CONCAT, LENGTH, SUBSTR, INSTR, LPAD,
RPAD, TRIM and REPLACE)

Case-Manipulative Functions

1. LOWER : This function converts alpha character values to lowercase. LOWER


will actually return a fixed-length string if the incoming string is fixed-length.
LOWER will not change any characters in the string that are not letters, since
case is irrelevant for numbers and special characters, such as the dollar sign (
$ ) or modulus ( % ).
Syntax:

LOWER(SQL course)
Input1: SELECT LOWER('GEEKSFORGEEKS') FROM DUAL;
Output1: geeksforgeeks
Input2: SELECT LOWER('DATABASE@456') FROM DUAL;
Output2: database@456

2. UPPER : This function converts alpha character values to uppercase. Also


UPPER function too, will actually return a fixed-length string if the incoming
string is fixed-length. UPPER will not change any characters in the string that
are not letters, since case is irrelevant for numbers and special characters,
such as the dollar sign ( $ ) or modulus ( % ).
Syntax:

UPPER(SQL course)
Input1: SELECT UPPER('geeksforgeeks') FROM DUAL;
Output1: GEEKSFORGEEKS

Input2: SELECT UPPER('dbms$508%7') FROM DUAL;


Output2: DBMS$508%7

3. INITCAP : This function converts alpha character values to uppercase for the
first letter of each word and all others in lowercase. The words in the string is
must be separated by either # or _ or space.
Syntax:

INITCAP(SQL course)
Input1: SELECT INITCAP('geeksforgeeks is a computer science portal for
geeks') FROM DUAL;
Output1: Geeksforgeeks Is A Computer Science Portal For Geeks

Input2: SELECT INITCAP('PRACTICE_CODING_FOR_EFFICIENCY') FROM DUAL;


Output2: Practice_Coding_For_Efficiency

Character-Manipulative Functions
1. CONCAT : This function always appends ( concatenates ) string2 to the end of
string1. If either of the string is NULL, CONCAT function returns the non-
NULL argument. If both strings are NULL, CONCAT returns NULL.
Syntax:

CONCAT('String1', 'String2')
Input1: SELECT CONCAT('computer' ,'science') FROM DUAL;
Output1: computerscience
Input2: SELECT CONCAT( NULL ,'Android') FROM DUAL;
Output2: Android

Input3: SELECT CONCAT( NULL ,NULL ) FROM DUAL;


Output3: -

2. LENGTH : This function returns the length of the input string. If the input
string is NULL, then LENGTH function returns NULL and not Zero. Also, if the
input string contains extra spaces at the start, or in between or at the end of
the string, then the LENGTH function includes the extra spaces too and
returns the complete length of the string.
Syntax:

LENGTH(Column|Expression)
Input1: SELECT LENGTH('Learning Is Fun') FROM DUAL;
Output1: 15

Input2: SELECT LENGTH(' Write an Interview Experience ') FROM DUAL;


Output2: 34

Input3: SELECT LENGTH('') FROM DUAL; or SELECT LENGTH( NULL ) FROM


DUAL;
Output3: -

3. SUBSTR : This function returns a portion of a string from a given start point
to an end point. If a substring length is not given, then SUBSTR returns all the
characters till the end of string (from the starting position specified).
Syntax:

SUBSTR('String',start-index,length_of_extracted_string)
Input1: SELECT SUBSTR('Database Management System', 9) FROM DUAL;
Output1: Management System

Input2: SELECT SUBSTR('Database Management System', 9, 7) FROM DUAL;


Output2: Manage

4. INSTR : This function returns numeric position of a character or a string in a


given string. Optionally, you can provide a position m to start searching, and
the occurrence n of string. Also, if the starting position is not given, then it
starts search from index 1, by default. If after searching in the string, no
match is found then, INSTR function returns 0.

Syntax: INSTR(Column|Expression, 'String', [,m], [n])


Input: SELECT INSTR('Google apps are great applications','app',1,2) FROM
DUAL;
Output: 23

5. LPAD and RPAD : These functions return the strings padded to the left or
right ( as per the use ) ; hence the “L” in “LPAD” and the “R” in “RPAD” ; to a
specified length, and with a specified pad string. If the pad string is not
specified, then the given string is padded on the left or right ( as per the use )
with spaces.
Syntax:

6. LPAD(Column|Expression, n, 'String')

Syntax: RPAD(Column|Expression, n, 'String')


LPAD Input1: SELECT LPAD('100',5,'*') FROM DUAL;
LPAD Output1: **100

LPAD Input2: SELECT LPAD('hello', 21, 'geek') FROM DUAL;


LPAD Output2: geekgeekgeekgeekhello

RPAD Input1: SELECT RPAD('5000',7,'*') FROM DUAL;


RPAD Output1: 5000***

RPAD Input1: SELECT RPAD('earn', 19, 'money') FROM DUAL;


RPAD Output1: earnmoneymoneymoney

7. TRIM : This function trims the string input from the start or end (or both). If
no string or char is specified to be trimmed from the string and there exists
some extra space at start or end of the string, then those extra spaces are
trimmed off.

Syntax:
TRIM(Leading|Trailing|Both, trim_character FROM trim_source)

Input1: SELECT TRIM('G' FROM 'GEEKS') FROM DUAL;


Output1: EEKS
Input2: SELECT TRIM(' geeksforgeeks ') FROM DUAL;
Output2:geeksforgeeks

8. REPLACE : This function searches for a character string and, if found, replaces
it with a given replacement string at all the occurrences of the string.
REPLACE is useful for searching patterns of characters and then changing all
instances of that pattern in a single function call.
If a replacement string is not given, then REPLACE function removes all the
occurrences of that character string in the input string. If neither a match
string nor a replacement string is specified, then REPLACE returns NULL.
Syntax:

REPLACE(Text, search_string, replacement_string)


Input1: SELECT REPLACE('DATA MANAGEMENT', 'DATA','DATABASE') FROM
DUAL;
Output1: DATABASE MANAGEMENT

Input2: SELECT REPLACE('abcdeabcccabdddeeabcc', 'abc') FROM DUAL;


Output2: deccabdddeec
SQL | NULL functions
Following are the NULL functions defined in SQL:

1. ISNULL(): The ISNULL function have different uses in SQL Server and MySQL.
In SQL Server, ISNULL() function is used to replace NULL values.
Syntax:

2. SELECT column(s), ISNULL(column_name, value_to_replace)

FROM table_name;

Example:
Consider the following Employee table,

Query: Find the sum of salary of all Employee, if Salary of any employee is
not available (or NULL value), use salary as 10000.

SELECT SUM(ISNULL(Salary, 10000) AS Salary

FROM Employee;

Output:

In MySQL, ISNULL() function is used to test whether an expression is NULL or


not. If the expression is NULL it returns TRUE, else FALSE.
Syntax:

SELECT column(s)
FROM table_name

WHERE ISNULL(column_name);

Example:
Consider the following Employee table,

Query: Fetch the name of all employee whose salary is available in the table
(not NULL).

SELECT Name

FROM Employee

WHERE ISNULL(Salary);

Output:

3. IFNULL(): This function is available in MySQL, and not in SQL Server or Oracle.
This function take two arguments. If the first argument is not NULL, the
function returns the first argument. Otherwise, the second argument is
returned. This function is commonly used to replace NULL value with
another value.
Syntax:

4. SELECT column(s), IFNULL(column_name, value_to_replace)

FROM table_name;

Example:
Consider the following Employee table,
Query: Find the sum of salary of all Employee, if Salary of any employee is
not available (or NULL value), use salary as 10000.

SELECT SUM(IFNULL(Salary, 10000) AS Salary

FROM Employee;

Output:

5. COALESCE(): COALESCE function in SQL returns the first non-NULL


expression among its arguments. If all the expressions evaluate to null, then
the COALESCE function will return null.
Syntax:

6. SELECT column(s), CAOLESCE(expression_1,....,expression_n)

FROM table_name;

Example:
Consider the following Contact_info table,

Query: Fetch the name, contact number of each employee.

SELECT Name, COALESCE(Phone1, Phone2) AS Contact

FROM Contact_info;

Output:
7. NULLIF(): The NULLIF function takes two argument. If the two arguments are
equal, then NULL is returned. Otherwise the first argument is returned.
Syntax:

8. SELECT column(s), NULLIF(expression1, expression2)

FROM table_name;

Example:
Consider the following Sales table,

SELECT Store, NULLIF(Actual, Goal)

FROM Sales;

Output:
SQL | LISTAGG
LISTAGG function in DBMS is used to aggregate strings from data in columns in a
database table.

 It makes it very easy to concatenate strings. It is similar to concatenation but


uses grouping.
 The speciality about this function is that, it also allows to order the elements
in the concatenated list.
Syntax:

LISTAGG (measure_expr [, 'delimiter']) WITHIN GROUP

(order_by_clause) [OVER query_partition_clause]

measure_expr : The column or expression to concatenate the values.


delimiter : Character in between each measure_expr, which is by default a comma
(,) .
order_by_clause : Order of the concatenated values.

Let us have a table named Gfg having two columns showing the subject names and
subject number that each subject belongs to, as shown below :

SQL> select * from GfG;

SUBNO SUBNAME

---------- ------------------------------

D20 Algorithm

D30 DataStructure

D30 C

D20 C++

D30 Python

D30 DBMS

D10 LinkedList
D20 Matrix

D10 String

D30 Graph

D20 Tree

11 rows selected.

Query 1: Write an SQL query using LISTAGG function to output the subject names in
a single field with the values comma delimited.

SQL> SELECT LISTAGG(SubName, ' , ') WITHIN GROUP (ORDER BY SubName) AS


SUBJECTS

2 FROM GfG ;

Output:

SUBJECTS

-----------------------------------------------------------------------------------

Algorithm , C , C++ , DBMS , DataStructure , Graph , LinkedList , Matrix , Python ,

String , Tree

Query 2: Write an SQL query to group each subject and show each subject in its
respective department separated by comma with the help of LISTAGG function.

SQL> SELECT SubNo, LISTAGG(SubName, ' , ') WITHIN GROUP (ORDER BY SubName)
AS SUBJECTS

2 FROM GfG
3 GROUP BY SubNo;

Output:

SUBNO SUBJECTS

------ --------------------------------------------------------------------------------

D10 LinkedList , String

D20 Algorithm , C++ , Matrix , Tree

D30 C , DBMS , DataStructure , Graph , Python

Query 3: Write an SQL query to show the subjects belonging to each department
ordered by the subject number (SUBNO) with the help of LISTAGG function.

SQL> SELECT SubNo, LISTAGG(SubName, ',') WITHIN GROUP (ORDER BY SubName)


AS SUBJECTS

2 FROM GfG

3 GROUP BY SubNo

4 ORDER BY SubNo;

Output:

SUBNO SUBJECTS

----- --------------------------------

D10 LinkedList, String

D20 Algorithm, C++, Matrix, Tree

D30 C, DBMS, DataStructure, Graph, Python


SQL | Date functions
In SQL, dates are complicated for newbies, since while working with database, the
format of the date in table must be matched with the input date in order to insert.
In various scenarios instead of date, datetime (time is also involved with date) is
used.
In MySql the default date functions are:

 NOW(): Returns the current date and time. Example:

 SELECT NOW();

Output:

2017-01-13 08:03:52

 CURDATE(): Returns the current date. Example:

 SELECT CURDATE();

Output:

2017-01-13

 CURTIME(): Returns the current time. Example:

 SELECT CURTIME();

Output:

08:05:15

 DATE(): Extracts the date part of a date or date/time expression. Example:


For the below table named ‘Test’
Id Name BirthTime

4120 Pratik 1996-09-26 16:44:15.581

SELECT Name, DATE(BirthTime) AS BirthDate FROM Test;

Output:

Name BirthDate

Pratik 1996-09-26

 EXTRACT(): Returns a single part of a date/time. Syntax:

 EXTRACT(unit FORM date);

There are several units that can be considered but only some are used such
as:
MICROSECOND, SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER,
YEAR, etc.
And ‘date’ is a valid date expression.

Example:
For the below table named ‘Test’

Id Name BirthTime

4120 Pratik 1996-09-26 16:44:15.581

Queries

 SELECT Name, Extract(DAY FROM BirthTime) AS BirthDay FROM Test;

 Output:
Name BirthDay

Pratik 26

 SELECT Name, Extract(YEAR FROM BirthTime) AS BirthYear FROM Test;

 Output:

Name BirthYear

Pratik 1996

 SELECT Name, Extract(SECOND FROM BirthTime) AS BirthSecond


FROM Test;

 Output:

Name BirthSecond

Pratik 581

 DATE_ADD() : Adds a specified time interval to a date


Syntax:

 DATE_ADD(date, INTERVAL expr type);

Where, date – valid date expression and expr is the number of interval we
want to add.
and type can be one of the following:
MICROSECOND, SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER,
YEAR, etc.
Example:
For the below table named ‘Test’

Id Name BirthTime

4120 Pratik 1996-09-26 16:44:15.581

Queries

 SELECT Name, DATE_ADD(BirthTime, INTERVAL 1 YEAR) AS


BirthTimeModified FROM Test;

 Output:

Name BirthTimeModified

Pratik 1997-09-26 16:44:15.581

 SELECT Name, DATE_ADD(BirthTime, INTERVAL 30 DAY) AS


BirthDayModified FROM Test;

 Output:

Name BirthDayModified

Pratik 1996-10-26 16:44:15.581

 SELECT Name, DATE_ADD(BirthTime, INTERVAL 4 HOUR) AS


BirthHourModified FROM Test;

 Output:
Name BirthSecond

Pratik 1996-10-26 20:44:15.581

 DATE_SUB(): Subtracts a specified time interval from a date. Syntax for


DATE_SUB is same as DATE_ADD just the difference is that DATE_SUB is used
to subtract a given interval of date.
 DATEDIFF(): Returns the number of days between two dates.Syntax:

 DATEDIFF(date1, date2);

 date1 & date2- date/time expression

Example:

SELECT DATE_DIFF('2017-01-13','2017-01-03') AS DateDiff;

Output:

DateDiff

10

 DATE_FORMAT(): Displays date/time data in different formats.Syntax:

 DATE_FORMAT(date,format);

date is a valid date and format specifies the output format for the date/time.
The formats that can be used are:

 %a-Abbreviated weekday name (Sun-Sat)


 %b-Abbreviated month name (Jan-Dec)
 %c-Month, numeric (0-12)
 %D-Day of month with English suffix (0th, 1st, 2nd, 3rd)
 %d-Day of month, numeric (00-31)
 %e-Day of month, numeric (0-31)
 %f-Microseconds (000000-999999)
 %H-Hour (00-23)
 %h-Hour (01-12)
 %I-Hour (01-12)
 %i-Minutes, numeric (00-59)
 %j-Day of year (001-366)
 %k-Hour (0-23)
 %l-Hour (1-12)
 %M-Month name (January-December)
 %m-Month, numeric (00-12)
 %p-AM or PM
 %r-Time, 12-hour (hh:mm:ss followed by AM or PM)
 %S-Seconds (00-59)
 %s-Seconds (00-59)
 %T-Time, 24-hour (hh:mm:ss)
 %U-Week (00-53) where Sunday is the first day of week
 %u-Week (00-53) where Monday is the first day of week
 %V-Week (01-53) where Sunday is the first day of week, used with %X
 %v-Week (01-53) where Monday is the first day of week, used with %x
 %W-Weekday name (Sunday-Saturday)
 %w-Day of the week (0=Sunday, 6=Saturday)
 %X-Year for the week where Sunday is the first day of week, four digits,
used with %V
 %x-Year for the week where Monday is the first day of week, four
digits, used with %v
 %Y-Year, numeric, four digits
 %y-Year, numeric, two digits
Example:

DATE_FORMAT(NOW(),'%d %b %y')

Result:

13 Jan 17
SQL | Functions (Aggregate and Scalar
Functions)
For doing operations on data sql has many built-in functions, they are categorised
in two categories and further sub-categorised in different seven functions under
each category. The categories are:

1. Aggregate functions:
These functions are used to do operations from the values of the column
and a single value is returned.
1. AVG()
2. COUNT()
3. FIRST()
4. LAST()
5. MAX()
6. MIN()
7. SUM()
2. Scalar functions:
These functions are based on user input, these too returns single value.
1. UCASE()
2. LCASE()
3. MID()
4. LEN()
5. ROUND()
6. NOW()
7. FORMAT()
Students-Table
Aggregate Functions

 AVG(): It returns average value after calculating from values in a numeric


column.
Syntax:

 SELECT AVG(column_name) FROM table_name;

Queries:
1. Computing average marks of students.

2. SELECT AVG(MARKS) AS AvgMarks FROM Students;

Output:

AvgMarks

80

3. Computing average age of students.

4. SELECT AVG(AGE) AS AvgAge FROM Students;

Output:

AvgAge

19.4

 COUNT(): It is used to count the number of rows returned in a SELECT


statement. It can’t be used in MS ACCESS.
Syntax:

 SELECT COUNT(column_name) FROM table_name;


Queries:

1. Computing total number of students.

2. SELECT COUNT(*) AS NumStudents FROM Stuents;

Output:

NumStudents

3. Computing number of students with unique/distinct age.

4. SELECT COUNT(DISTINCT AGE) AS NumStudents FROM Students;

Output:

NumStudents

 FIRST(): The FIRST() function returns the first value of the selected column.
Syntax:

 SELECT FIRST(column_name) FROM table_name;

Queries:

1. Fetching marks of first student from the Students table.

2. SELECT FIRST(MARKS) AS MarksFirst FROM Students;

Output:

MarksFirst
90

3. Fetching age of first student from the Students table.

4. SELECT FIRST(AGE) AS AgeFirst FROM Students;

Output:

AgeFirst

19

 LAST(): The LAST() function returns the last value of the selected column. It
can be used only in MS ACCESS.
Syntax:

 SELECT LAST(column_name) FROM table_name;

Queries:
1. Fetching marks of last student from the Students table.

2. SELECT LAST(MARKS) AS MarksLast FROM Students;

Output:

MarksLast

82

3. Fetching age of last student from the Students table.

4. SELECT FIRST(AGE) AS AgeLast FROM Students;

Output:
AgeLast

18

 MAX(): The MAX() function returns the maximum value of the selected
column.
Syntax:

 SELECT MAX(column_name) FROM table_name;

Queries:
1. Fetching maximum marks among students from the Students table.

2. SELECT MAX(MARKS) AS MaxMarks FROM Students;

Output:

MaxMarks

95

3. Fetching max age among students from the Students table.

4. SELECT MAX(AGE) AS MaxAge FROM Students;

Output:

MaxAge

21

 MIN(): The MIN() function returns the minimum value of the selected column.
Syntax:
 SELECT MIN(column_name) FROM table_name;

Queries:
1. Fetching minimum marks among students from the Students table.

2. SELECT MIN(MARKS) AS MinMarks FROM Students;

Output:

MinMarks

50

3. Fetching minimum age among students from the Students table.

4. SELECT MIN(AGE) AS MinAge FROM Students;

Output:

MinAge

18

 SUM(): The SUM() function returns the sum of all the values of the selected
column.
Syntax:

 SELECT SUM(column_name) FROM table_name;

Queries:
1. Fetching summation of total marks among students from the Students
table.

2. SELECT SUM(MARKS) AS TotalMarks FROM Students;


Output:

TotalMarks

400

3. Fetching summation of total age among students from the Students


table.

4. SELECT SUM(AGE) AS TotalAge FROM Students;

Output:

TotalAge

97

Scalar Functions
 UCASE(): It converts the value of a field to uppercase.
Syntax:

 SELECT UCASE(column_name) FROM table_name;

Queries:
1. Converting names of students from the table Students to uppercase.

2. SELECT UCASE(NAME) FROM Students;

Output:

NAME

HARSH
SURESH

PRATIK

DHANRAJ

RAM

 LCASE(): It converts the value of a field to lowercase.


Syntax:

 SELECT LCASE(column_name) FROM table_name;

Queries:
1. Converting names of students from the table Students to lowercase.

2. SELECT LCASE(NAME) FROM Students;

Output:

NAME

Harsh

suresh

Pratik

dhanraj
Ram

 MID(): The MID() function extracts texts from the text field.
Syntax:

 SELECT MID(column_name,start,length) AS some_name FROM table_name;

 specifying length is optional here, and start signifies start position ( starting
from 1 )

Queries:
1. Fetching first four characters of names of students from the Students
table.

2. SELECT MID(NAME,1,4) FROM Students;

Output:

NAME

HARS

SURE

PRAT

DHAN

RAM

 LEN(): The LEN() function returns the length of the value in a text field.
Syntax:
 SELECT LENGTH(column_name) FROM table_name;

Queries:
1. Fetching length of names of students from Students table.

2. SELECT LENGTH(NAME) FROM Students;

Output:

NAME

 ROUND(): The ROUND() function is used to round a numeric field to the


number of decimals specified.NOTE: Many database systems have adopted
the IEEE 754 standard for arithmetic operations, which says that when any
numeric .5 is rounded it results to the nearest even integer i.e, 5.5 and 6.5
both gets rounded off to 6.
Syntax:

SELECT ROUND(column_name,decimals) FROM table_name;

decimals- number of decimals to be fetched.


Queries:
1. Fetching maximum marks among students from the Students table.

2. SELECT ROUND(MARKS,0) FROM table_name;

Output:

MARKS

90

50

80

95

85

 NOW(): The NOW() function returns the current system date and time.
Syntax:

 SELECT NOW() FROM table_name;

Queries:
1. Fetching current system time.

2. SELECT NAME, NOW() AS DateTime FROM Students;

Output:

NAME DateTim
HARSH 1/13/2017 1:30

SURESH 1/13/2017 1:30

PRATIK 1/13/2017 1:30

DHANRAJ 1/13/2017 1:30

RAM 1/13/2017 1:30

 FORMAT(): The FORMAT() function is used to format how a field is to be


displayed.
Syntax:

 SELECT FORMAT(column_name,format) FROM table_name;

Queries:
1. Formatting current date as ‘YYYY-MM-DD’.

2. SELECT NAME, FORMAT(Now(),'YYYY-MM-DD') AS Date FROM Students;

Output:

NAME Date

HARSH 2017-01-13

SURESH 2017-01-13

PRATIK 2017-01-13
DHANRAJ 2017-01-13

RAM 2017-01-13
Joining three or more tables in SQL
There may occur some situations sometimes where data needs to be fetched from
three or more tables. This article deals with two approaches to achieve it.

Example:
Creating three tables:
1. student
2. marks
3. details
Note: Click on image if not clear to view in bigger size.
Table 1: student

create table student(s_id int primary key,

s_name varchar(20));

insert into student values(1, 'Jack');

insert into student values(2, 'Rithvik');

insert into student values(3, 'Jaspreet');

insert into student values(4, 'Praveen');

insert into student values(5, 'Bisa');

insert into student values(6, 'Suraj');


Table 2: marks

create table marks(school_id int primary key, s_id int,

score int, status varchar(20));

insert into marks values(1004, 1, 23, 'fail');

insert into marks values(1008, 6, 95, 'pass');

insert into marks values(1012, 2, 97, 'pass');

insert into marks values(1016, 7, 67, 'pass');

insert into marks values(1020, 3, 100, 'pass');

insert into marks values(1025, 8, 73, 'pass');

insert into marks values(1030, 4, 88, 'pass');

insert into marks values(1035, 9, 13, 'fail');

insert into marks values(1040, 5, 16, 'fail');

insert into marks values(1050, 10, 53, 'pass');

Table 3: details

create table details(address_city varchar(20), email_ID varchar(20),

school_id int, accomplishments varchar(50));


insert into details values('Banglore', 'jsingh@geeks.com',

1020, 'ACM ICPC selected');

insert into details values('Hyderabad', 'praveen@geeks.com',

1030, 'Geek of the month');

insert into details values('Delhi', 'rithvik@geeks.com',

1012, 'IOI finalist');

insert into details values('Chennai', 'om@geeks.com',

1111, 'Geek of the year');

insert into details values('Banglore', ' suraj@geeks.com',

1008, 'IMO finalist');

insert into details values('Mumbai', 'sasukeh@geeks.com',

2211, 'Made a robot');

insert into details values('Ahmedabad', 'itachi@geeks.com',

1172, 'Code Jam finalist');

insert into details values('Jaipur', 'kumar@geeks.com',

1972, 'KVPY finalist');


Two approaches to join three or more tables:
1. Using joins in sql to join the table:
The same logic is applied which is done to join 2 tables i.e. minimum number of join
statements to join ntables are (n-1).
Query:

select s_name, score, status, address_city, email_id,

accomplishments from student s inner join marks m on

s.s_id = m.s_id inner join details d on

d.school_id = m.school_id;

Output:

2. Using parent-child relationship:


This is rather an interesting approach. Create column X as primary key in one table
and as foreign key in another table (i.e creating a parent-child relationship).
Let’s look in the tables created:
s_id is the primary key in student table and is foreign key in marks table. (student
(parent) – marks(child)).
school_id is the primary key in marks table and foreign key in details
table. (marks(parent) – details(child)).
Query:

select s_name, score, status, address_city,

email_id, accomplishments from student s,

marks m, details d where s.s_id = m.s_id and

m.school_id = d.school_id;
Output:
How to Get the names of the table in
SQL
The syntax provided in this article works only for SQL Server and MySQL.

If you want to know how many tables are present in your database and the details
of the table like TABLE_SCHEMA, TABLE_TYPE and all.

Syntax:

SELECT * FROM INFORMATION_SCHEMA.TABLES

WHERE
1. INFORMATION_SCHEMA views allow you to retrieve metadata about the objects
within a database. These views can be found in the master database under Views /
System Views and be called from any database in your SQL Server instance.
2. INFORMATION_SCHEMA.TABLES The INFORMATION_SCHEMA.TABLES view allows
you to get information about all tables and views within a database.
Example:

Output:
SQL | Sub queries in From Clause
From clause can be used to specify a sub-query expression in SQL. The relation
produced by the sub-query is then used as a new relation on which the outer query
is applied.

 Sub queries in the from clause are supported by most of the SQL
implementations.
 The correlation variables from the relations in from clause cannot be used in
the sub-queries in the from clause.
Syntax:

SELECT column1, column2 FROM


(SELECT column_x as C1, column_y FROM table WHERE PREDICATE_X)
as table2
WHERE PREDICATE;

Note: The sub-query in the from clause is evaluated first and then the results of
evaluation are stored in a new temporary relation.
Next, the outer query is evaluated, selecting only those tuples from the temporary
relation that satisfies the predicate in the where clause of the outer query.
Query

Example 1: Find all professors whose salary is greater than the average budget of
all the departments.
Instructor relation:

INSTRUCTORID NAME DEPARTMENT SALARY

44547 Smith Computer Science 95000

44541 Bill Electrical 55000


47778 Sam Humanities 44000

48147 Erik Mechanical 80000

411547 Melisa Information Technology 65000

48898 Jena Civil 50000

Department relation:

DEPARTMENT NAME BUDGET

Computer Science 100000

Electrical 80000

Humanities 50000

Mechanical 40000

Information Technology 90000

Civil 60000

Query:

select I.ID, I.NAME, I.DEPARTMENT, I.SALARY from


(select avg(BUDGET) as averageBudget from DEPARTMENT) as BUDGET, Instructor
as I
where I.SALARY > BUDGET.averageBudget;
Output

INSTRUCTORID NAME DEPARTMENT SALARY

44547 Smith Computer Science 95000

48147 Erik Mechanical 80000

Explanation: The average budget of all departments from the department relation
is 70000. Erik and Smith are the only instructors in the instructor relation whose
salary is more than 70000 and thereofre are present in the output relation.
SQL Correlated Subqueries
Correlated subqueries are used for row-by-row processing. Each subquery is
executed once for every row of the outer query.

A correlated subquery is evaluated once for each row processed by the parent
statement. The parent statement can be a SELECT, UPDATE, or DELETE statement.

SELECT column1, column2, ....

FROM table1 outer

WHERE column1 operator

(SELECT column1, column2

FROM table2

WHERE expr1 =

outer.expr2);
A correlated subquery is one way of reading every row in a table and comparing
values in each row against related data. It is used whenever a subquery must return
a different result or set of results for each candidate row considered by the main
query. In other words, you can use a correlated subquery to answer a multipart
question whose answer depends on the value in each row processed by the parent
statement.

Nested Subqueries Versus Correlated Subqueries :

With a normal nested subquery, the inner SELECT query runs first and executes
once, returning values to be used by the main query. A correlated subquery,
however, executes once for each candidate row considered by the outer query. In
other words, the inner query is driven by the outer query.
NOTE : You can also use the ANY and ALL operator in a correlated subquery.
EXAMPLE of Correlated Subqueries : Find all the employees who earn more than
the average salary in their department.

SELECT last_name, salary, department_id

FROM employees outer

WHERE salary >

(SELECT AVG(salary)

FROM employees

WHERE department_id =

outer.department_id);

Other use of correlation are in UPDATE and DELETE

CORRELATED UPDATE :

UPDATE table1 alias1

SET column = (SELECT expression


FROM table2 alias2

WHERE alias1.column =

alias2.column);

Use a correlated subquery to update rows in one table based on rows from another
table.

CORRELATED DELETE :

DELETE FROM table1 alias1

WHERE column1 operator

(SELECT expression

FROM table2 alias2

WHERE alias1.column = alias2.column);

Use a correlated subquery to delete rows in one table based on the rows from
another table.

Using the EXISTS Operator :

The EXISTS operator tests for existence of rows in the results set of the subquery. If
a subquery row value is found the condition is flagged TRUE and the search does
not continue in the inner query, and if it is not found then the condition is
flagged FALSE and the search continues in the inner query.
EXAMPLE of using EXIST operator :
Find employees who have at least one person reporting to them.

SELECT employee_id, last_name, job_id, department_id


FROM employees outer

WHERE EXISTS ( SELECT ’X’

FROM employees

WHERE manager_id =

outer.employee_id);

OUTPUT :

EXAMPLE of using NOT EXIST operator :


Find all departments that do not have any employees.

SELECT department_id, department_name

FROM departments d

WHERE NOT EXISTS (SELECT ’X’

FROM employees

WHERE department_id

= d.department_id);
OUTPUT :
SQL | SUB Queries
In SQL a Subquery can be simply defined as a query within another query. In other
words we can say that a Subquery is a query that is embedded in WHERE clause of
another SQL query.

Important rules for Subqueries:

 You can place the Subquery in a number of SQL


clauses: WHERE clause, HAVING clause, FROM clause.
Subqueries can be used with SELECT, UPDATE, INSERT, DELETE statements
along with expression operator. It could be equality operator or comparison
operator such as =, >, =, <= and Like operator.
 A subquery is a query within another query. The outer query is called as main
query and inner query is called as subquery.
 The subquery generally executes first, and its output is used to complete the
query condition for the main or outer query.
 Subquery must be enclosed in parentheses.
 Subqueries are on the right side of the comparison operator.
 ORDER BY command cannot be used in a Subquery. GROUPBY command can
be used to perform same function as ORDER BY command.
 Use single-row operators with singlerow Subqueries. Use multiple-row
operators with multiple-row Subqueries.
Syntax:
There is not any general syntax for Subqueries. However, Subqueries are seen to be
used most frequently with SELECT statement as shown below:

SELECT column_name

FROM table_name

WHERE column_name expression operator


( SELECT COLUMN_NAME from TABLE_NAME WHERE ... );

Sample Table:
DATABASE
NAME ROLL_NO LOCATION PHONE_NUMBER

Ram 101 Chennai 9988775566

Raj 102 Coimbatore 8877665544

Sasi 103 Madurai 7766553344

Ravi 104 Salem 8989898989

Sumathi 105 Kanchipuram 8989856868

STUDENT

NAME ROLL_NO SECTION

Ravi 104 A

Sumathi 105 B

Raj 102 A

Sample Queries
:

 To display NAME, LOCATION, PHONE_NUMBER of the students from


DATABASE table whose section is A

 Select NAME, LOCATION, PHONE_NUMBER from DATABASE

 WHERE ROLL_NO IN
 (SELECT ROLL_NO from STUDENT where SECTION=’A’);

Explanation : First subquery executes “ SELECT ROLL_NO from STUDENT


where SECTION=’A’ ” returns ROLL_NO from STUDENT table whose SECTION
is ‘A’.Then outer-query executes it and return the NAME, LOCATION,
PHONE_NUMBER from the DATABASE table of the student whose ROLL_NO is
returned from inner subquery.
Output:

NAME ROLL_NO LOCATION PHONE_NUMBER

Ravi 104 Salem 8989898989

Raj 102 Coimbatore 8877665544

 Insert Query Example:


Table1: Student1

NAME ROLL_NO LOCATION PHONE_NUMBER

Ram 101 chennai 9988773344

Raju 102 coimbatore 9090909090

Ravi 103 salem 8989898989

Table2: Student2

NAME ROLL_NO LOCATION PHONE_NUMBER

Raj 111 chennai 8787878787


Sai 112 mumbai 6565656565

Sri 113 coimbatore 7878787878

To insert Student2 into Student1 table:

INSERT INTO Student1 SELECT * FROM Student2;

Output:

NAME ROLL_NO LOCATION PHONE_NUMBER

Ram 101 chennai 9988773344

Raju 102 coimbatore 9090909090

Ravi 103 salem 8989898989

Raj 111 chennai 8787878787

Sai 112 mumbai 6565656565

Sri 113 coimbatore 7878787878

 To delete students from Student2 table whose rollno is same as that in


Student1 table and having location as chennai

 DELETE FROM Student2

 WHERE ROLL_NO IN ( SELECT ROLL_NO

 FROM Student1
 WHERE LOCATION = ’chennai’);

Output:

1 row delete successfully.

Display Student2 table:

NAME ROLL_NO LOCATION PHONE_NUMBER

Sai 112 mumbai 6565656565

Sri 113 coimbatore 7878787878

 To update name of the students to geeks in Student2 table whose location is


same as Raju,Ravi in Student1 table

 UPDATE Student2

 SET NAME=’geeks’

 WHERE LOCATION IN ( SELECT LOCATION

 FROM Student1

 WHERE NAME IN (‘Raju’,’Ravi’));

Output:

1 row updated successfully.

Display Student2 table:

NAME ROLL_NO LOCATION PHONE_NUMBER


Sai 112 mumbai 6565656565

geeks 113 coimbatore 7878787878


SQL | Top-N Queries
Top-N Analysis in SQL deals with How to limit the number of rows returned from
ordered sets of data in SQL.
Top-N queries ask for the n smallest or largest values of a column. Both smallest
and largest values sets are considered Top-N queries. Following this type of
searching technique could save lot of time and complexities. Top-N analysis are
useful in cases where the need is to display only the n bottom-most or the n top-
most records from a table based on a condition. This result set can be used for
further analysis.
For example, using Top-N analysis we can perform the following types of queries:
 The top five products that have had the maximum sales in the last two
months.
 The top three agents who sold the maximum policies.
 The least two students who scored minimum marks in end semester exams.
Performing Top-N Analysis
Following the below mentioned queries we can easily understand the working of
Top-N analysis in SQL:
Syntax:

SELECT [column_list], ROWNUM


FROM (SELECT [column_list]
FROM table_name
ORDER BY Top-N_clolumn)
WHERE ROWNUM<=N;

We will perform the various commands on the following table named Employee:
Example 1:

Input :
SELECT ROWNUM as RANK, first_name, last_name, employee_id, salary
FROM (SELECT salary, first_name, last_name, employee_id
FROM Employee
ORDER BY salary)
WHERE ROWNUM<=3;
Output :

Explanation: In the above SQL statement, the required fields are displayed for
employees with top 3 highest salaries. The result is displayed in decreasing order of
their salaries.
Example 2:

Input :
SELECT ROWNUM as RANK, first_name, employee_id, hire_date
FROM (SELECT first_name, employee_id, hire_date
FROM Employee
ORDER BY hire_date)
WHERE ROWNUM<=3;
Output :

Explanation: In the above SQL statement, the required fields are displayed for those
3 employees who were hired earliest. The result is displayed in increasing order of
their hire date.
Different styles for using Top-N analysis
 Inline View and ROWNUM : The classic Top-N style query uses an ordered
inline view to force the data into the correct order which then finally uses the
ROWNUM check to limit the data returned.

Example:

 Input :
 SELECT first_name, last_name
 FROM (SELECT first_name, last_name
 FROM Employee
 ORDER BY salary DESC)
 WHERE ROWNUM<=4;
Output :

Explanation: In the above SQL statement, the required fields are displayed
for highest paid 4 employees. The altering is done by ORDER BY clause.
 Nested Inline View and ROWNUM : This method can also be used for paging
through data, like paged web reports.
Example:

 Input :
 SELECT employee_id, first_name, salary
 FROM (SELECT employee_id, first_name, salary, rownum AS rnum
 FROM (SELECT employee_id, first_name, salary
 FROM Employee
 ORDER BY salary)
 WHERE rownum<=4)
 WHERE rnum>=2;
Output:

Explanation: In the above SQL statement, first of all the inside query runs and
gives its output to the outer query which then finally gives us the desired
output.
 Using RANK function : The RANK analytic function assigns a sequential rank
to each distinct value in output.
Example:

 Input :
 SELECT dpartment_id, first_name
 FROM (SELECT dpartment_id, first_name,
 RANK() OVER (ORDER BY dpartment_id DESC) AS rnum
 FROM Employee)
 WHERE rnum<=3;
Output :

Explanation: In the above SQL statement, RANK() function also acts as a


virtual field whose value is restricted at the end. RANK() function doesn’t give
us the top N rows or the top N distinct values. The number of rows returned
is dependent on the number of duplicates in the data.
 Using DENSE_RANK function : The DENSE_RANK analytic function is similar to
RANK() function. The difference is that the ranks are compacted due to which
there are no gaps.
Example:

 Input :
 SELECT dpartment_id, first_name
 FROM (SELECT dpartment_id, first_name,
 DENSE_RANK() OVER (ORDER BY dpartment_id DESC) AS rnum
 FROM Employee)
 WHERE rnum<=3;
Output :

Explanation: In the above SQL statement, DENSE_RANK() function also


assigns same rank to the duplicate values but there is no gap in the rank
sequence. Thus it always gives us a Top N distinct valuesresult.
 Using ROW_NUMBER function : The ROW_NUMBER analytic function is
similar to ROWNUM virtual column but like all analytic functions its action
can be limited to a specific output of data based on the order of data.
Example:

 Input :
 SELECT dpartment_id, first_name
 FROM (SELECT dpartment_id, first_name,
 ROW_NUMBER() OVER (ORDER BY dpartment_id DESC) AS rnum
 FROM Employee)
 WHERE rnum<=4;
Output :
DBMS | Nested Queries in SQL
Prerequisites : Basics of SQL

In nested queries, a query is written inside a query. The result of inner query is
used in execution of outer query. We will use STUDENT, COURSE,
STUDENT_COURSE tables for understanding nested queries.

STUDENT

S_ID S_NAME S_ADDRESS S_PHONE S_AGE

S1 RAM DELHI 9455123451 18

S2 RAMESH GURGAON 9652431543 18

S3 SUJIT ROHTAK 9156253131 20

S4 SURESH DELHI 9156768971 18

COURSE

C_ID C_NAME

C1 DSA

C2 Programming
C3 DBMS

STUDENT_COURSE

S_ID C_ID

S1 C1

S1 C3

S2 C1

S3 C2

S4 C2

S4 C3

There are mainly two types of nested queries:

 Independent Nested Queries: In independent nested queries, query


execution starts from innermost query to outermost queries. The execution
of inner query is independent of outer query, but the result of inner query is
used in execution of outer query. Various operators like IN, NOT IN, ANY, ALL
etc are used in writing independent nested queries.

IN: If we want to find out S_ID who are enrolled in C_NAME ‘DSA’ or ‘DBMS’,
we can write it with the help of independent nested query and IN operator.
From COURSE table, we can find out C_ID for C_NAME‘DSA’ or DBMS’ and we
can use these C_IDs for finding S_IDs from STUDENT_COURSE TABLE.

STEP 1: Finding C_ID for C_NAME =’DSA’ or ‘DBMS’


Select C_ID from COURSE where C_NAME = ‘DSA’ or C_NAME = ‘DBMS’

STEP 2: Using C_ID of step 1 for finding S_ID


Select S_ID from STUDENT_COURSE where C_ID IN
(SELECT C_ID from COURSE where C_NAME = ‘DSA’ or C_NAME=’DBMS’);

The inner query will return a set with members C1 and C3 and outer query
will return those S_IDs for which C_ID is equal to any member of set (C1 and
C3 in this case). So, it will return S1, S2 and S4.

Note: If we want to find out names of STUDENTs who have either enrolled in
‘DSA’ or ‘DBMS’, it can be done as:
Select S_NAME from STUDENT where S_ID IN
(Select S_ID from STUDENT_COURSE where C_ID IN
(SELECT C_ID from COURSE where C_NAME=’DSA’ or C_NAME=’DBMS’));

NOT IN: If we want to find out S_IDs of STUDENTs who have neither enrolled
in ‘DSA’ nor in ‘DBMS’, it can be done as:
Select S_ID from STUDENT where S_ID NOT IN
(Select S_ID from STUDENT_COURSE where C_ID IN
(SELECT C_ID from COURSE where C_NAME=’DSA’ or C_NAME=’DBMS’));

The innermost query will return a set with members C1 and C3. Second inner
query will return those S_IDs for which C_ID is equal to any member of set
(C1 and C3 in this case) which are S1, S2 and S4. The outermost query will
return those S_IDs where S_ID is not a member of set (S1, S2 and S4). So it
will return S3.

 Co-related Nested Queries: In co-related nested queries, the output of inner


query depends on the row which is being currently executed in outer query.
e.g.; If we want to find out S_NAME of STUDENTs who are enrolled
in C_ID ‘C1’, it can be done with the help of co-related nested query as:
Select S_NAME from STUDENT S where EXISTS
( select * from STUDENT_COURSE SC where S.S_ID=SC.S_ID and SC.C_ID=’C1’);

For each row of STUDENT S, it will find the rows


from STUDENT_COURSE where S.S_ID = SC.S_ID and SC.C_ID=’C1’. If for
a S_ID from STUDENT S, atleast a row exists in STUDENT_COURSE SC
with C_ID=’C1’, then inner query will return true and corresponding S_ID will
be returned as output.
How to print duplicate rows in a table?
Let us consider below table.

NAME SECTION

abc CS1

bcd CS2

abc CS1

In the above table, we can find duplicate row using below query.

SELECT name, section FROM tbl

GROUP BY name, section

HAVING COUNT(*) > 1

Another Example:
Given a table named PERSON task is to write an SQL query to find all duplicate
name in the table.
Example :

+----+---------+

| Id | NAME |

+----+---------+

| 1 | Geeks |

| 2 | for |

| 3 | Geeks |

+----+---------+
Output :

+---------+

| NAME |

+---------+

| Geeks |

+---------+

The simple approach is to make a temporary table which have count of all the
names in a table.
Duplicated NAME existed more than one time, so to count the times each NAME
exists, we can use the following code:

select NAME, count(NAME) as num

from Person

group by NAME;

| NAME | num |

|---------|-----|

| Geeks | 2 |

| for |1 |

This is a temporary table, on which we can run the below code to get duplicate
NAME.

select NAME from

(
select NAME, count(NAME) as num

from Person

group by NAME

) as statistic

where num > 1;

The Best approach is to use GROUP BY and HAVING condition. It is more effective
and faster then previous.
MySql :

select NAME

from Person

group by NAME

having count(NAME) > 1;


How to find Nth highest salary from a
table
Finding Nth highest salary in a table is the most common question asked in
interviews. Here is a way to do this task using dense_rank() function.

Consider the following table:


Employee

ename sal

A 23000

B 31000

C 24500

D 35000

E 28500

F 31500

G 39800

H 51000

I 39800

Query :
select * from(

select ename, sal, dense_rank()

over(order by sal desc)r from Employee)

where r=&n;

To find to the 2nd highest sal set n = 2

To find 3rd highest sal set n = 3 and so on.

Output :

DENSE_RANK :

1. DENSE_RANK computes the rank of a row in an ordered group of rows and


returns the rank as a NUMBER. The ranks are consecutive integers beginning with
1.
2. This function accepts arguments as any numeric data type and returns NUMBER.
3. As an analytic function, DENSE_RANK computes the rank of each row returned
from a query with respect to the other rows, based on the values of the value_exprs
in the order_by_clause.
4. In the above query the rank is returned based on sal of the employee table. In
case of tie, it assigns equal rank to all the rows.

Alternate Solution :
———————————————————————————————————————
——————————————————————————————–

CREATE TABLE `Employee` (


`ENAME` varchar(225) COLLATE utf8_unicode_ci NOT NULL,
`SAL` bigint(20) unsigned NOT NULL,
PRIMARY KEY (`ENAME`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

———————————————————————————————————————
—————————————-

6th highest

mysql> select * from ((select * from Employee

ORDER BY `sal` DESC limit 6 ) AS T)

ORDER BY T.`sal` ASC limit 1;

Alternate use of Limit:

select * from Employee ORDER BY `sal` DESC limit 5,1; // will return 6th highest

+-------+-----+

| ENAME | SAL |

+-------+-----+

|B | 300 |

+-------+-----+
1 row in set (0.00 sec)

———————————————————————————————————————
———————————–

mysql> select * from Employee;

+-------+-----+

| ENAME | SAL |

+-------+-----+

|A | 100 |

|B | 300 |

|C | 200 |

|D | 500 |

|F | 400 |

|G | 600 |

|H | 700 |

|I | 800 |

+-------+-----+

8 rows in set (0.00 sec)


SQL query to find second highest salary?
Consider below simple table:

Name Salary

---------------

abc 100000

bcd 1000000

efg 40000

ghi 500000

How to find the employee whose salary is second highest. For example, in above
table, “ghi” has the second highest salary as 500000.

Below is simple query to find the employee whose salary is highest.

SELECT name, MAX(salary) as salary FROM employee

We can nest the above query to find the second largest salary.

SELECT name, MAX(salary) AS salary

FROM employee

WHERE salary < (SELECT MAX(salary)

FROM employee);

There are other ways also as suggested by RajnishKrJha.

SELECT name, MAX(salary) AS salary


FROM employee

WHERE salary IN

(SELECT salary FROM employee MINUS SELECT MAX(salary)

FROM employee);

SELECT name, MAX(salary) AS salary

FROM employee

WHERE salary (SELECT MAX(salary)

FROM employee);

One way as suggested by Arka Poddar.


IN SQL Server using Common Table Expression or CTE, we can find the second
highest salary:

WITH T AS

SELECT *

DENSE_RANK() OVER (ORDER BY Salary Desc) AS Rnk

FROM Employees

SELECT Name

FROM T

WHERE Rnk=2;

How to find the third largest salary?


Simple, we can do one more nesting.

SELECT name, MAX(salary) AS salary

FROM employee
WHERE salary < (SELECT MAX(salary)

FROM employee

WHERE salary < (SELECT MAX(salary)

FROM employee)

);

Note that instead of nesting for second, third largest salary, we can find nth salary
using general query like in mysql:

select salary from employee order by salary desc limit n-1,1;

Or

Select name,salary from employee A where n-1 = (Select count(1) from employee B
where B.salary>A.salary)
Check if Table, View, Trigger, etc present
in Oracle
Sometimes while working in SQL we often forget the names of the view or
sequence or index or synonyms or trigger we earlier created. Also it may happen
that we want to verify them in future.

Verifying means that we are checking for all the present database object or Trigger
in that particular schema.
This could be done for above all using the below mentioned queries:
PREREQUISITE: DATABASE OBJECTS
Triggers
1. verify VIEWS
SYNTAX:

SELECT VIEW_NAME FROM USER_VIEWS;

OR

SELECT * FROM USER_VIEWS;

Examples:

Input : SELECT VIEW_NAME FROM USER_VIEWS;


Output :

Input : SELECT * FROM USER_VIEWS;

Output :

2. verify SEQUENCES
SYNTAX:

SELECT SEQUENCE_NAME FROM USER_SEQUENCES;

OR
SELECT * FROM USER_SEQUENCES;

Examples:

Input : SELECT SEQUENCE_NAME FROM USER_SEQUENCES;

Output :

Input : SELECT * FROM USER_SEQUENCES;

Output :
3. verify INDEXES
SYNTAX:

SELECT INDEX_NAME FROM USER_INDEXES;

OR

SELECT * FROM USER_INDEXS;

Examples:

Input : SELECT INDEX_NAME FROM USER_INDEXES;

Output :

Input : SELECT * FROM USER_INDEXES;


Output :

4. verify TABLES
SYNTAX:

SELECT TABLE_NAME FROM USER_TABLES;

OR

SELECT * FROM USER_TABLES;

Examples:

Input : SELECT TABLE_NAME FROM USER_TABLES;


Output :

Input : SELECT * FROM USER_TABLES;

Output :

5. verify SYNONYMS
SYNTAX:

SELECT SYNONYM_NAME FROM USER_SYNONYMS;


OR

SELECT * FROM USER_SYNONYMS;

Examples:

Input : SELECT SYNONYM_NAME FROM USER_SYNONYMS;

Output :

Input : SELECT * FROM USER_SYNONYMS;


Output :

6. verify TRIGGERS
SYNTAX:

SELECT TRIGGER_NAME FROM USER_TRIGGERS;

OR

SELECT * FROM USER_TRIGGERS;

Examples:

Input : SELECT TRIGGER_NAME FROM USER_TRIGGERS;


Output :

Input : SELECT * FROM USER_TRIGGERS;

Output :

NOTE: Using * means that we need all the attributes for that database object or
Trigger to get displayed.
Difference between Simple and Complex
View in SQL
Prerequisite – SQL | Views
A View in SQL as a logical subset of data from one or more tables. Views are used to
restrict data access. A View contains no data of its own but its like window through
which data from tables can be viewed or changed. The table on which a View is
based are called BASE Tables.
There are 2 types of Views in SQL: Simple View and Complex View. Simple views can
only contain a single base table. Complex views can be constructed on more than
one base table. In particular, complex views can contain: join conditions, a group by
clause, a order by clause.
The key differences between these types of Views are:

SIMPLE VIEW COMPLEX VIEW

Conatins more than one base

Contains only one single base table or tables or is created from more

is created from only one table. than one tables.

We cannot use group functions like

MAX(), COUNT(), etc. We can use group functions.

Does not contain groups of data. It can conatin groups of data.

DML operations could not always

DML operations could be performed be performed through a complex

through a simple view. view.


We cannot apply INSERT, DELETE

INSERT, DELETE and UPDATE are and UPDATE on complex view

directly possible on a simle view. directly.

Simple view does not contain group by, It can contain group by, distinct,

distinct, pseudocolumn like rownum, pseudocolumn like rownum,

columns defiend by expressions. columns defiend by expressions.

NOT NULL columns that are not

Does not include NOT NULL columns selected by simple view can be

from base tables. included in complex view.


Difference between Static and Dynamic
SQL
Static or Embedded SQL are SQL statements in an application that do not change at
runtime and, therefore, can be hard-coded into the application. Dynamic SQL is SQL
statements that are constructed at runtime; for example, the application may allow
users to enter their own queries.
Dynamic SQL is a programming technique that enables you to build SQL
statements dynamically at runtime. You can create more general purpose, flexible
applications by using dynamic SQL because the full text of a SQL statement may be
unknown at compilation.
Below mentioned are the basic differences
between Static or Embedded and Dynamic or Interactive SQL:

STATIC (EMBEDDED) SQL DYNAMIC (INTERACTIVE) SQL

In Static SQL, how database will be In Dynamic SQL, how database will

accessed is predetermined in the be accessed is determined at run

embedded SQL statement. time.

It is more swift and efficient. It is less swift and efficient.

SQL statements are compiled at SQL statements are compiled at

compile time. run time.

Parsing, Validation, Optimization and Parsing, Validation, Optimization

Generation of application plan are and Generation of application plan

done at compile time. are done at run time.


It is generally used for situations

It is generally used for situations where data is distributed non

where data is distributed uniformly. uniformly.

EXECUTE IMMEDIATE, EXECUTE and EXECUTE IMMEDIATE, EXECUTE and

PREPARE statements are not used. PREPARE statements are used.

It is less flexible. It is more flexible.

Limitation of Dynamic SQL:


We cannot use some of the SQL statements Dynamically.
Performance of these statements is poor as compared to Static SQL.
Limitations of Static SQL:
They do not change at runtime thus are hard-coded into applications.
Having vs Where Clause?
The difference between the having and where clause in SQL is that the where
clause cannot be used with aggregates, but the having clause can.
The where clause works on row’s data, not on aggregated data. Let us consider
below table ‘Marks’.
Student Course Score
a c1 40

a c2 50

b c3 60

d c1 70

e c2 80

Consider the query

SELECT Student, Score FROM Marks WHERE Score >=40


This would select data row by row basis.

The having clause works on aggregated data.


For example, output of below query

SELECT Student, SUM(score) AS total FROM Marks GROUP BY Student


Student Total
a 90

b 60

d 70

e 80

When we apply having in above query, we get

SELECT Student, SUM(score) AS total FROM Marks GROUP BY Student


HAVING total > 70

Student Total
a 90
e 80

Note: It is not a predefined rule but in a good number of the SQL queries, we
use WHERE prior to GROUP BY and HAVING after GROUP BY. The Where clause acts
as a pre filter where as Having as a post filter.
Inner Join vs Outer Join
What is Join?
An SQL Join is used to combine data from two or more tables, based on a common
field between them. For example, consider the following two tables.
Student Table

ENROLLNO STUDENTNAME ADDRESS

1001 geek1 geeksquiz1

1002 geek2 geeksquiz2

1003 geek3 geeksquiz3

1004 geek4 geeksquiz4

StudentCourse Table

COURSEID ENROLLNO

1 1001

2 1001

3 1001

1 1002
2 1003

Following is join query that shows names of students enrolled in different


courseIDs.

SELECT StudentCourse.CourseID,Student.StudentName

FROM Student

INNER JOIN StudentCourse

ON StudentCourse.EnrollNo = Student.EnrollNo

ORDER BY StudentCourse.CourseID

Note: INNER is optional above. Simple JOIN is also considered as INNER JOIN

The above query would produce following result.

COURSEID STUDENTNAME

1 geek1

1 geek2

2 geek1

2 geek3

3 geek1

What is the difference between inner join and outer join?


Outer Join is of 3 types
1) Left outer join
2) Right outer join
3) Full Join

1) Left outer join returns all rows of table on left side of join. The rows for which
there is no matching row on right side, result contains NULL in the right side.

SELECT Student.StudentName,

StudentCourse.CourseID

FROM Student

LEFT OUTER JOIN StudentCourse

ON StudentCourse.EnrollNo = Student.EnrollNo

ORDER BY StudentCourse.CourseID

Note: OUTER is optional above. Simple LEFT JOIN is also considered as LEFT OUTER
JOIN

STUDENTNAME COURSEID

geek4 NULL

geek2 1

geek1 1

geek1 2

geek3 2
STUDENTNAME COURSEID

geek1 3

2) Right Outer Join is similar to Left Outer Join (Right replaces Left everywhere)
3) Full Outer Join Contains results of both Left and Right outer joins.
SQL | EXISTS
The EXISTS condition in SQL is used to check whether the result of a correlated
nested query is empty (contains no tuples) or not. The result of EXISTS is a boolean
value True or False. It can be used in a SELECT, UPDATE, INSERT or DELETE
statement.

Syntax:

SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name(s)
FROM table_name
WHERE condition);

Examples:
Consider the following two relation “Customers” and “Orders”.
Queries
1. Using EXISTS condition with SELECT statement
To fetch the first and last name of the customers who placed atleast one
order.

2. SELECT fname, lname

3. FROM Customers

4. WHERE EXISTS (SELECT *

5. FROM Orders

WHERE Customers.customer_id = Orders.c_id);

Output:
6. Using NOT with EXISTS
Fetch last and first name of the customers who has not placed any order.

7. SELECT lname, fname

8. FROM Customer

9. WHERE NOT EXISTS (SELECT *

10. FROM Orders

WHERE Customers.customer_id = Orders.c_id);

Output:

11. Using EXISTS condition with DELETE statement


Delete the record of all the customer from Order Table whose last name is
‘Mehra’.

DELETE

FROM Orders

WHERE EXISTS (SELECT *

FROM customers

WHERE Customers.customer_id = Orders.cid

AND Customers.lname = 'Mehra');

SELECT * FROM Orders;


Output:

12. Using EXISTS condition with UPDATE statement


Update the lname as ‘Kumari’ of customer in Customer Table whose
customer_id is 401.

13. UPDATE Customers

14. SET lname = 'Kumari'

15. WHERE EXISTS (SELECT *

16. FROM Customers

WHERE customer_id = 401);

SELECT * FROM Customers;

Output:
Combining aggregate and non-aggregate
values in SQL using Joins and Over
clause
Prerequisite – Aggregate functions in SQL, Joins in SQL
Aggregate functions perform a calculation on a set of values and return a single
value. Now, consider an employee table EMP and a department table DEPT with
following structure:

Table – EMPLOYEE TABLE

NAME NULL TYPE

EMPNO NOT NULL NUMBER(4)

ENAME VARCHAR2(10)

JOB VARCHAR2(9)

MGR NUMBER(4)

HIREDATE DATE

SAL NUMBER(7, 2)

COMM NUMBER(7, 2)
NAME NULL TYPE

DEPTNO NUMBER(2)

Table – DEPARTMENT TABLE

NAME NULL TYPE

DEPTNO NUMBER(2)

DNAME VARCHAR2(14)

LOC VARCHAR2(13)

And the following results are needed:

1. DISPLAY NAME, SAL, JOB OF EMP ALONG WITH MAX, MIN, AVG, TOTAL SAL
OF THE EMPS DOING THE SAME JOB.
2. DISPLAY DEPTNAME WITH NUMBER OF EMP WORKING IN IT.
The aggregated values can’t be directly used with non-aggregated values to obtain a
result. Thus one can use the following concepts:

 Using Joins –
1. Create a sub-table containing the result of aggregated values.
2. Using Join, use the results from the sub-table to display them with
non-aggregated values.
Solutions for the problem 1 using JOIN:

SELECT ENAME, SAL, EMP.JOB,

SUBTABLE.MAXSAL, SUBTABLE.MINSAL,
SUBTABLE.AVGSAL, SUBTABLE.SUMSAL

FROM EMP

INNER JOIN

(SELECT JOB, MAX(SAL) MAXSAL, MIN(SAL)

MINSAL, AVG(SAL) AVGSAL, SUM(SAL) SUMSAL

FROM EMP

GROUP BY JOB) SUBTABLE

ON EMP.JOB = SUBTABLE.JOB;

Output for sample data:

ENAME SAL JOB MAXSAL MINSAL AVGSAL SUMSAL

SCOTT 3300 ANALYST 3300 1925 2841.67 8525

HENRY 1925 ANALYST 3300 1925 2841.67 8525

FORD 3300 ANALYST 3300 1925 2841.67 8525

SMITH 3300 CLERK 3300 1045 1746.25 6985

MILLER 1430 CLERK 3300 1045 1746.25 6985

 Using ‘Over’ clause –


1. OVER CLAUSE ALONG WITH PARTION BY IS USED TO BRAKE UP DATA
INTO PARTITIONS.
2. THE SPECIFIED FUNCTION OPERATES FOR EACH PARTITION.
Solutions for the problem 2 using OVER Clause:
SELECT DISTINCT(DNAME),

COUNT(ENAME) OVER (PARTITION BY EMP.DEPTNO) EMP

FROM EMP

RIGHT OUTER JOIN DEPT

ON EMP.DEPTNO=DEPT.DEPTNO

ORDER BY EMP DESC;

DNAME EMP

SALES 6

RESEARCH 5

ACCOUNTING 3

OPERATIONS 0

OTHERS 0
SQL | ALL and ANY
ALL & ANY are logical operators in SQL. They return boolean value as a result.
ALL
ALL operator is used to select all tuples of SELECT STATEMENT. It is also used to
compare a value to every value in another value set or result from a subquery.

 The ALL operator returns TRUE iff all of the subqueries values meet the
condition. The ALL must be preceded by comparison operators and
evaluates true if all of the subqueries values meet the condition.
 ALL is used with SELECT, WHERE, HAVING statement.
ALL with SELECT Statement:

Syntax:

SELECT ALL field_name

FROM table_name

WHERE condition(s);

ALL with WHERE or HAVING Statement:

Syntax:

SELECT column_name(s)

FROM table_name

WHERE column_name comparison_operator ALL

(SELECT column_name

FROM table_name

WHERE condition(s));

Example:
Consider the following Products Table and OrderDetails Table,
Products Table

OrderDetails Table

Queries
 Find the name of the all the product.

 SELECT ALL ProductName


 FROM Products

 WHERE TRUE;

Output:

 Find the name of the product if all the records in the OrderDetails has
Quantity either equal to 6 or 2.

 SELECT ProductName

 FROM Products

 WHERE ProductID = ALL (SELECT ProductId

 FROM OrderDetails

 WHERE Quantity = 6 OR Quantity = 2);

Output:

 Find the OrderID whose maximum Quantity among all product of that
OrderID is greater than average quantity of all OrderID.
 SELECT OrderID

 FROM OrderDetails

 GROUP BY OrderID

 HAVING max(Quantity) > ALL (SELECT avg(Quantity)

 FROM OrderDetails

 GROUP BY OrderID);

Output:

ANY
ANY compares a value to each value in a list or results from a query and evaluates
to true if the result of an inner query contains at least one row.

 ANY return true if any of the subqueries values meet the condition.
 ANY must be preceded by comparison operators.
Syntax:

SELECT column_name(s)

FROM table_name

WHERE column_name comparison_operator ANY

(SELECT column_name

FROM table_name

WHERE condition(s));

Queries
 Find the Distinct CategoryID of the products which have any record in
OrderDetails Table.

 SELECT DISTINCT CategoryID


 FROM Products

 WHERE ProductID = ANY (SELECT ProductID

 FROM OrderDetails);

Output:

 Finds any records in the OrderDetails table that Quantity = 9.

 SELECT ProductName

 FROM Products

 WHERE ProductID = ANY (SELECT ProductID

 FROM OrderDetails

 WHERE Quantity = 9);


Database Management System |
Aggregate functions in SQL
In database management an aggregate function is a function where the values of
multiple rows are grouped together as input on certain criteria to form a single
value of more significant meaning.

Various Aggregate Functions

1) Count()

2) Sum()

3) Avg()

4) Min()

5) Max()

Now let us understand each Aggregate function with a example:

Id Name Salary

-----------------------

1 A 80

2 B 40

3 C 60

4 D 70

5 E 60
6 F Null

Count():

Count(*): Returns total number of records .i.e 6.


Count(salary): Return number of Non Null values over the column salary. i.e 5.
Count(Distinct Salary): Return number of distinct Non Null values over the column
salary .i.e 4

Sum():

sum(salary): Sum all Non Null values of Column salary i.e., 310
sum(Distinct salary): Sum of all distinct Non-Null values i.e., 250.

Avg():

Avg(salary) = Sum(salary) / count(salary) = 310/5


Avg(Distinct salary) = sum(Distinct salary) / Count(Distinct Salary) = 250/4

Min():

Min(salary): Minimum value in the salary column except NULL i.e., 40.
Max(salary): Maximum value in the salary i.e., 80.
SQL | Numeric Functions
Numeric Functions are used to perform operations on numbers and return
numbers.
Following are the numeric functions defined in SQL:
1. ABS(): It returns the absolute value of a number.

Syntax: SELECT ABS(-243.5);

Output: 243.5

SQL> SELECT ABS(-10);

+--------------------------------------+

| ABS(10)

+--------------------------------------+

| 10

+--------------------------------------+

2. ACOS(): It returns the cosine of a number.

Syntax: SELECT ACOS(0.25);

Output: 1.318116071652818
3. ASIN(): It returns the arc sine of a number.

Syntax: SELECT ASIN(0.25);

Output: 0.25268025514207865
4. ATAN(): It returns the arc tangent of a number.

Syntax: SELECT ATAN(2.5);

Output: 1.1902899496825317
5. CEIL(): It returns the smallest integer value that is greater than or equal to a
number.

Syntax: SELECT CEIL(25.75);

Output: 26
6. CEILING(): It returns the smallest integer value that is greater than or equal to
a number.

Syntax: SELECT CEILING(25.75);

Output: 26
7. COS(): It returns the cosine of a number.

Syntax: SELECT COS(30);

Output: 0.15425144988758405
8. COT(): It returns the cotangent of a number.

Syntax: SELECT COT(6);

Output: -3.436353004180128
9. DEGREES(): It converts a radian value into degrees.

Syntax: SELECT DEGREES(1.5);

Output: 85.94366926962348

SQL>SELECT DEGREES(PI());

+------------------------------------------+

| DEGREES(PI())

+------------------------------------------+

| 180.000000

+------------------------------------------+

10. DIV(): It is used for integer division.

Syntax: SELECT 10 DIV 5;

Output: 2
11. EXP(): It returns e raised to the power of number.

Syntax: SELECT EXP(1);

Output: 2.718281828459045
12. FLOOR(): It returns the largest integer value that is less than or equal to a
number.

Syntax: SELECT FLOOR(25.75);

Output: 25
13. GREATEST(): It returns the greatest value in a list of expressions.

Syntax: SELECT GREATEST(30, 2, 36, 81, 125);

Output: 125
14. LEAST(): It returns the smallest value in a list of expressions.

Syntax: SELECT LEAST(30, 2, 36, 81, 125);

Output: 2
15. LN(): It returns the natural logarithm of a number.

Syntax: SELECT LN(2);

Output: 0.6931471805599453
16. LOG10(): It returns the base-10 logarithm of a number.

Syntax: SELECT LOG(2);

Output: 0.6931471805599453
17. LOG2(): It returns the base-2 logarithm of a number.

Syntax: SELECT LOG2(6);

Output: 2.584962500721156
18. MOD(): It returns the remainder of n divided by m.

Syntax: SELECT MOD(18, 4);

Output: 2
19. PI(): It returns the value of PI displayed with 6 decimal places.

Syntax: SELECT PI();

Output: 3.141593
20. POW(): It returns m raised to the nth power.

Syntax: SELECT POW(4, 2);


Output: 16
21. RADIANS(): It converts a value in degrees to radians.

Syntax: SELECT RADIANS(180);

Output: 3.141592653589793
22. RAND(): It returns a random number.

Syntax: SELECT RAND();

Output: 0.33623238684258644
23. ROUND(): It returns a number rounded to a certain number of decimal
places.

Syntax: SELECT ROUND(5.553);

Output: 6
24. SIGN(): It returns a value indicating the sign of a number.

Syntax: SELECT SIGN(255.5);

Output: 1
25. SIN(): It returns the sine of a number.

Syntax: SELECT SIN(2);

Output: 0.9092974268256817
26. SQRT(): It returns the square root of a number.

Syntax: SELECT SQRT(25);

Output: 5
27. TAN(): It returns the tangent of a number.

Syntax: SELECT TAN(1.75);

Output: -5.52037992250933
28. ATAN2(): It returns the arctangent of the x and y coordinates, as an angle and
expressed in radians.

Syntax: SELECT ATAN2(7);

Output: 1.42889927219073
29. TRUNCATE(): It returns 7.53635 truncated to 2 places right of the decimal
point.

Syntax: SELECT TRUNCATE(7.53635, 2);

Output: 7.53
SQL | String functions
String functions
are used to perform an operation on input string and return an output string.
Following are the string functions defined in SQL:
1. ASCII(): This function is used to find the ASCII value of a character.

2. Syntax: SELECT ascii('t');

Output: 116

3. CHAR_LENGTH(): This function is used to find the length of a word.

4. Syntax: SELECT char_length('Hello!');

Output: 6

5. CHARACTER_LENGTH(): This function is used to find the length of a line.

6. Syntax: SELECT CHARACTER_LENGTH('geeks for geeks');

Output: 15

7. CONCAT(): This function is used to add two words or strings.

8. Syntax: SELECT 'Geeks' || ' ' || 'forGeeks' FROM dual;

Output: ‘GeeksforGeeks’

9. CONCAT_WS(): This function is used to add two words or strings with a


symbol as concatenating symbol.

10. Syntax: SELECT CONCAT_WS('_', 'geeks', 'for', 'geeks');

Output: geeks_for_geeks

11. FIND_IN_SET(): This function is used to find a symbol from a set of symbols.
12. Syntax: SELECT FIND_IN_SET('b', 'a, b, c, d, e, f');

Output: 2

13. FORMAT(): This function is used to display a number in the given format.

14. Syntax: Format("0.981", "Percent");

Output: ‘98.10%’

15. INSERT(): This function is used to insert the data into a database.

16. Syntax: INSERT INTO database (geek_id, geek_name) VALUES (5000, 'abc');

Output: successfully updated

17. INSTR(): This function is used to find the occurrence of an alphabet.

18. Syntax: INSTR('geeks for geeks', 'e');

Output: 2 (the first occurrence of ‘e’)


Syntax: INSTR('geeks for geeks', 'e', 1, 2 );
Output: 3 (the second occurrence of ‘e’)

19. LCASE(): This function is used to convert the given string into lower case.

20. Syntax: LCASE ("GeeksFor Geeks To Learn");

Output: geeksforgeeks to learn

21. LEFT(): This function is used to SELECT a sub string from the left of given size
or characters.

22. Syntax: SELECT LEFT('geeksforgeeks.org', 5);

Output: geeks

23. LENGTH(): This function is used to find the length of a word.

24. Syntax: LENGTH('GeeksForGeeks');


Output: 13

25. LOCATE(): This function is used to find the nth position of the given word in a
string.

26. Syntax: SELECT LOCATE('for', 'geeksforgeeks', 1);

Output: 6

27. LOWER(): This function is used to convert the upper case string into lower
case.

28. Syntax: SELECT LOWER('GEEKSFORGEEKS.ORG');

Output: geeksforgeeks.org

29. LPAD(): This function is used to make the given string of the given size by
adding the given symbol.

30. Syntax: LPAD('geeks', 8, '0');


31. Output:

000geeks

32. LTRIM(): This function is used to cut the given sub string from the original
string.

33. Syntax: LTRIM('123123geeks', '123');

Output: geeks

34. MID(): This function is to find a word from the given position and of the given
size.

35. Syntax: Mid ("geeksforgeeks", 6, 2);

Output: for

36. POSITION(): This function is used to find position of the first occurrence of
the given alphabet.
37. Syntax: SELECT POSITION('e' IN 'geeksforgeeks');

Output: 2

38. REPEAT(): This function is used to write the given string again and again till
the number of times mentioned.

39. Syntax: SELECT REPEAT('geeks', 2);

Output: geeksgeeks

40. REPLACE(): This function is used to cut the given string by removing the given
sub string.

41. Syntax: REPLACE('123geeks123', '123');

Output: geeks

42. REVERSE(): This function is used to reverse a string.

43. Syntax: SELECT REVERSE('geeksforgeeks.org');

Output: ‘gro.skeegrofskeeg’

44. RIGHT(): This function is used to SELECT a sub string from the right end of the
given size.

45. Syntax: SELECT RIGHT('geeksforgeeks.org', 4);

Output: ‘.org’

46. RPAD(): This function is used to make the given string as long as the given
size by adding the given symbol on the right.

47. Syntax: RPAD('geeks', 8, '0');

Output: ‘geeks000’

48. RTRIM(): This function is used to cut the given sub string from the original
string.
49. Syntax: RTRIM('geeksxyxzyyy', 'xyz');

Output: ‘geeks’

50. SPACE(): This function is used to write the given number of spaces.

51. Syntax: SELECT SPACE(7);

Output: ‘ ‘

52. STRCMP(): This function is used to compare 2 strings.


 If string1 and string2 are the same, the STRCMP function will return 0.
 If string1 is smaller than string2, the STRCMP function will return -1.
 If string1 is larger than string2, the STRCMP function will return 1.

53. Syntax: SELECT STRCMP('google.com', 'geeksforgeeks.com');

Output: -1

54. SUBSTR(): This function is used to find a sub string from the a string from the
given position.

55. Syntax:SUBSTR('geeksforgeeks', 1, 5);

Output: ‘geeks’

56. SUBSTRING(): This function is used to find an alphabet from the mentioned
size and the given string.

57. Syntax: SELECT SUBSTRING('GeeksForGeeks.org', 9, 1);

Output: ‘G’

58. SUBSTRING_INDEX(): This function is used to find a sub string before the
given symbol.

59. Syntax: SELECT SUBSTRING_INDEX('www.geeksforgeeks.org', '.', 1);

Output: ‘www’
60. TRIM(): This function is used to cut the given symbol from the string.

61. Syntax: TRIM(LEADING '0' FROM '000123');

Output: 123

62. UCASE(): This function is used to make the string in upper case.

63. Syntax: UCASE ("GeeksForGeeks");


64. Output:

GEEKSFORGEEKS
SQL | Advanced Functions
Following are some of the advanced functions defined in SQL:

1. BIN(): It converts a decimal number to a binary number.


Syntax:

2. SELECT BIN(18);

Output:

3. BINARY(): It converts a value to a binary string


Syntax:

SELECT BINARY "GeeksforGeeks";

Output:

4. COALESCE(): It returns the first non-null expression in a list.


Syntax:

5. SELECT COALESCE(NULL,NULL,'GeeksforGeeks',NULL,'Geeks');

Output:

6. CONNECTION_ID(): It returns the unique connection ID for the current


connection.
Syntax:
SELECT CONNECTION_ID();

Output:

7. CURRENT_USER(): It returns the user name and host name for the MySQL
account used by the server to authenticate the current client.
Syntax:

8. SELECT CURRENT_USER();

Output:

9. DATABASE(): It returns the name of the default database.


Syntax:

10. SELECT DATABASE();

Output:

11. IF(): It returns one value if a condition is TRUE, or another value if a condition
is FALSE.
Syntax:

12. SELECT IF(200<500, "YES", "NO");

Output:
13. LAST_INSERT_ID(): It returns the first AUTO_INCREMENT value that was set by
the most recent INSERT or UPDATE statement.
Syntax:

14. SELECT LAST_INSERT_ID();

Output:

15. NULLIF(): It Compares two expressions.


 Syntax:

 SELECT NULLIF(25.11, 25);

Output:

 Syntax:

 SELECT NULLIF(115, 115);

Output:

16. SESSION_USER(): It returns the user name and host name for the current
MySQL user.
Syntax:

SELECT SESSION_USER();
Output:

17. SYSTEM_USER(): It returns the user name and host name for the current
MySQL user.
Syntax:

18. SELECT SYSTEM_USER();

Output:

19. USER(): It returns the user name and host name for the current MySQL user.
Syntax:

20. SELECT USER();

Output:

21. VERSION(): It returns the version of the MySQL database.


Syntax:

22. SELECT VERSION();

Output:
SQL | Date Functions (Set-1)
In SQL, dates are complicated for newbies, since while working with a database, the
format of the date in the table must be matched with the input date in order to
insert. In various scenarios instead of date, datetime (time is also involved with
date) is used.

Some of the important date functions have been already discussed in the
previous post. The basic idea of this post is to know the working or syntax of all the
date functions:
Below are the date functions that are used in SQL:

1. ADDDATE(): It returns a date after a certain time/date interval has been


added.

Syntax: SELECT ADDTIME("2018-07-16 02:52:47", "2");

Output: 2018-07-16 02:52:49


2. ADDTIME(): It returns a time / date time after a certain time interval has been
added.

Syntax: SELECT ADDTIME("2017-06-15 09:34:21", "2");

Output: 2017-06-15 09:34:23


3. CURDATE(): It returns the current date.

Syntax: SELECT CURDATE();

Output: 2018-07-16
4. CURRENT_DATE(): It returns the current date.

Syntax: SELECT CURRENT_DATE();

Output: 2018-07-16
5. CURRENT_TIME(): It returns the current time.

Syntax: SELECT CURRENT_TIME();

Output: 02:53:15
6. CURRENT_TIMESTAMP(): It returns the current date and time.

Syntax: SELECT CURRENT_TIMESTAMP();

Output: 2018-07-16 02:53:21


7. CURTIME(): It returns the current time.

Syntax: SELECT CURTIME();

Output: 02:53:28
8. DATE(): It extracts the date value from a date or date time expression.

Syntax: SELECT DATE("2017-06-15");

Output: 2017-06-15
9. DATEDIFF(): It returns the difference in days between two date values.

Syntax: SELECT DATEDIFF("2017-06-25", "2017-06-15");

Output: 10
10. DATE_ADD(): It returns a date after a certain time/date interval has been
added.

Syntax: SELECT DATE_ADD("2018-07-16", INTERVAL 10 DAY);

Output: 2018-07-16
11. DATE_FORMAT(): It formats a date as specified by a format mask.

Syntax: SELECT DATE_FORMAT("2018-06-15", "%Y");

Output: 2018
12. DATE_SUB(): It returns a date after a certain time/date interval has been
subtracted.

Syntax: SELECT DATE_SUB("2017-06-15", INTERVAL 10 DAY);

Output: 2018-07-16
13. DAY(): It returns the day portion of a date value.

Syntax: SELECT DAY("2018-07-16");

Output: 16
14. DAYNAME(): It returns the weekday name for a date.

Syntax: SELECT DAYNAME('2008-05-15');

Output: Thursday
15. DAYOFMONTH(): It returns the day portion of a date value.
Syntax: SELECT DAYOFMONTH('2018-07-16');

Output: 16
16. DAYWEEK(): It returns the weekday index for a date value.

Syntax: SELECT WEEKDAY("2018-07-16");

Output: 0
17. DAYOFYEAR(): It returns the day of the year for a date value.

Syntax: SELECT DAYOFYEAR("2018-07-16");

Output: 197
18. EXTRACT(): It extracts parts from a date.

Syntax: SELECT EXTRACT(MONTH FROM "2018-07-16");

Output: 7
19. FROM_DAYS(): It returns a date value from a numeric representation of the
day.

Syntax: SELECT FROM_DAYS(685467);

Output: 1876-09-29
20. HOUR(): It returns the hour portion of a date value.

Syntax: SELECT HOUR("2018-07-16 09:34:00");

Output: 9
21. LAST_DAY(): It returns the last day of the month for a given date.

Syntax: SELECT LAST_DAY('2018-07-16');

Output: 2018-07-31
22. LOCALTIME(): It returns the current date and time.

Syntax: SELECT LOCALTIME();

Output: 2018-07-16 02:56:42


23. LOCALTIMESTAMP(): It returns the current date and time.

Syntax: SELECT LOCALTIMESTAMP();

Output: 2018-07-16 02:56:48


24. MAKEDATE(): It returns the date for a certain year and day-of-year value.

Syntax: SELECT MAKEDATE(2009, 138);

Output: 2009-05-18
25. MAKETIME(): It returns the time for a certain hour, minute, second
combination.

Syntax: SELECT MAKETIME(11, 35, 4);

Output: 11:35:04
SQL | Date Functions (Set-2)
In SQL, dates are complicated for newbies, since while working with a database, the
format of the date in the table must be matched with the input date in order to
insert. In various scenarios instead of date, datetime (time is also involved with
date) is used.

Some of the date functions have been already discussed in the Set-1. In this post,
the remaining date functions have been discussed.
Below are the remaining date functions that are used in SQL:

1. MICROSECOND(): It returns the microsecond portion of a date value.

Syntax: SELECT MICROSECOND("2018-07-18 09:12:00.000345");

Output: 345
2. MINUTE(): It returns the minute portion of a date value.

Syntax: SELECT MINUTE("2018-07-18 09:12:00");

Output: 12
3. MONTH(): It returns the month portion of a date value.

Syntax: SELECT MONTH ('2018/07/18')AS MONTH;

Output: 7
4. MONTHNAME(): It returns the full month name for a date.

Syntax: SELECT MONTHNAME("2018/07/18");

Output: JULY
5. NOW(): It returns the current date and time.

Syntax: SELECT NOW();

Output: 2018-07-18 09:14:32


6. PERIOD_ADD(): It takes a period and adds a specified number of months to it.

Syntax: SELECT PERIOD_ADD(201803, 6);

Output: 201809
7. PERIOD_DIFF(): It returns the difference in months between two periods.
Syntax: SELECT PERIOD_DIFF(201810, 201802);

Output: 8
8. QUARTER(): It returns the quarter portion of a date value.

Syntax: SELECT QUARTER("2018/07/18");

Output: 3
9. SECOND(): It returns the second portion of a date value.

Syntax: SELECT SECOND("09:14:00:00032");

Output: 0
10. SEC_TO_TIME(): It converts numeric seconds into a time value.

Syntax: SELECT SEC_TO_TIME(1);

Output: 00:00:01
11. STR_TO_DATE(): It takes a string and returns a date specified by a format
mask.

Syntax: SELECT STR_TO_DATE("JULY 18 2018", "%M %D %Y");

Output: 0018-07-18
12. SUBDATE(): It returns a date after which a certain time/date interval has been
subtracted.

Syntax: SELECT SUBDATE("2017-06-15", INTERVAL 10 DAY);

Output: 2017-06-05
13. SUBTIME(): It returns a time/date time value after a certain time interval has
been subtracted.

Syntax: SELECT SUBDATE("2018/07/18", INTERVAL 10 DAY);

Output: 2018-07-18 09:15:17.542768


14. SYSDATE(): It returns the current date and time.

Syntax: SELECT SYSDATE();

Output: 2018-07-18 09:19:03


15. TIME(): It extracts the time value from a time/date time expression.
Syntax: SELECT TIME("09:16:10");

Output: 09:16:10
16. TIME_FORMAT(): It formats the time as specified by a format mask.

Syntax: SELECT TIME_FORMAT("09:16:10", "%H %I %S");

Output: 09 09 10
17. TIME_TO_SEC(): It converts a time value into numeric seconds.

Syntax: SELECT TIME_TO_SEC("09:16:10");

Output: 33370
18. TIMEDIFF(): It returns the difference between two time/datetime values.

Syntax: SELECT TIMEDIFF("09:16:10", "09:16:04");

Output: 00:00:06
19. TIMESTAMP(): It converts an expression to a date time value and if specified
adds an optional time interval to the value.

Syntax: SELECT TIMESTAMP("2018-07-18", "09:16:10");

Output: 2018-07-18 09:16:10


20. TO_DAYS(): It converts a date into numeric days.

Syntax: SELECT TO_DAYS("2018-07-18");

Output: 737258
21. WEEK(): It returns the week portion of a date value.

Syntax: SELECT WEEK("2018-07-18");

Output: 28
22. WEEKDAY(): It returns the weekday index for a date value.

Syntax: SELECT WEEKDAY("2018-07-18");

Output: 2
23. WEEKOFYEAR(): It returns the week of the year for a date value.

Syntax: SELECT WEEKOFYEAR("2018-07-18");

Output: 29
24. YEAR(): It returns the year portion of a date value.

Syntax: SELECT YEAR("2018-07-18");

Output: 2018
25. YEARWEEK(): It returns the year and week for a date value.

Syntax: SELECT YEARWEEK("2018-07-18");

Output: 201828
SQL SERVER | Conditional Statements
While loop: In SQL SERVER, while loop can be used in similar manner as any other
programming language. A while loop will check the condition first and then execute
the block of SQL Statements within it as long as the condition evaluates true.
Syntax:

WHILE condition

BEGIN

{...statements...}

END;

Parameters:
1. Condition: The condition is tested in each pass through the loop. If condition
evaluates to TRUE, the loop body is executed otherwise the loop is terminated.
2. Statements: The statements that needs to be executed in each pass through the
loop.
Example:
Output:

Break statement: BREAK statement as the name signifies is used to break the flow
of control. It can be used in SQL in similar manner as any other programming
language.
Example: While loop with Break statement
Output:

Note : In the example, when variables value became five, BREAK Statement is
executed and the control gets out from the Loop.
Do-While loop: SQL server does not have the feature of do-while loop but by doing
little modifications in while loop, the same behaviour can be achieved.
Example 1:

Output:
Example 2:

Output:

CASE statement: In SQL Server, the CASE statement has the same functionality as
IF-THEN-ELSE statement.
Syntax:

CASE Expression

WHEN Con_1 THEN Output1

WHEN Con_2 THEN Output2

WHEN Con_3 THEN Output3

WHEN Con_4 THEN Output4

...

WHEN Con_n THEN Outputn


ELSE output

END

Paramaters:
1. Expression: The value to be compared to the list of conditions(Optional).
2. Con_1, Con_2, …Con_n: The conditions are required and are evaluated in the
order they are listed. Once a condition is true, the CASE function will return the
result and not evaluate the conditions any further.
3. Output1, Output2, …Outputn: The output to be printed once the condition
evaluates true.
Example:

Output:
SQL Server | STUFF() Function
There are situations when user want to change some portion of the data inserted.
The reason may be because of the human error or the change in data. For this
purpose, stuff() function comes to action.

STUFF() :
In SQL Server, stuff() function is used to delete a sequence of given length of
characters from the source string and inserting the given sequence of characters
from the specified starting index.
Syntax:

STUFF (source_string, start, length, add_string)

Where:-
1. source_string: Original string to be modified.
2. start: The starting index from where the given length of characters will be deleted
and new sequence of characters will be inserted.
3. length: The numbers of characters to be deleted from the starting index in the
original string.
4. add_string: The new set of characters (string) to be inserted in place of deleted
characters from the starting index.
Note: It is not necessary to have the length of the new string and number of
charaters to be deleted the same.

Example 1:
Output:

Example 2:

Output:

Example 3:
Output:
SQL Server Identity
Identity column of a table is a column whose value increases automatically. The
value in an identity column is created by the server. A user generally cannot insert a
value into an identity column. Identity column can be used to uniquely identify the
rows in the table.

Syntax:

IDENTITY [( seed, increment)]

Seed: Starting value of a column.


Default value is 1.

Increment: Incremental value that is


added to the identity value of the previous
row that was loaded. The default value 1.
Example 1:
Table Content
Note:

The ‘ID’ column of the table starts from 1 as the seed value provided is 1 and is
incremented by 1 at each row.

Example 2:
Table Content
Note:

The ‘ID’ column of the table starts from 1 but is incremented by 2 as the increment
value is passed as 2 while creating the ‘IDENTITY’ Column.
Introduction to Common
Table Expressions
(CTE’s)
Common Table Expressions or CTE’s for short are used within SQL Server to
simplify complex joins and subqueries, and to provide a means to query
hierarchical data such as an organizational chart. In this set of articles, we’ll
introduce you to common table expressions, the two types, and their uses. In this
article we’ll introduce CTE’s. Once you’re familiar, I would encourage you to also
read these articles as well:

 Non recursive CTE’s


 Recursive CTE’s

Introduction to Common Table Expressions

A CTE (Common Table Expression) is temporary result set that you can reference
within another SELECT, INSERT, UPDATE, or DELETE statement. They were
introduced in SQL Server version 2005. They are SQL compliant and part of
the ANSI SQL 99 specification.
A CTE always returns a result set. They are used to simplify queries, for example,
you could use one to eliminate a derived table from the main query body:

Note: All the examples for this lesson are based on Microsoft SQL Server
Management Studio and the AdventureWorks2012 database. You can get started
using these free tools using my Guide Getting Started Using SQL Server.
What is a CTE or Common Table Expression in SQL Server?

A CTE (Common Table Expression) defines a temporary result set which you can
then use in a SELECT statement. It becomes a convenient way to manage
complicated queries.
Common Table Expressions are defined within the statement using the WITH
operator. You can define one or more common table expression in this fashion.
Here is a really simple example of one CTE:

WITH Employee_CTE (EmployeeNumber, Title)

AS

(SELECT NationalIDNumber,

JobTitle

FROM HumanResources.Employee)

SELECT EmployeeNumber,

Title

FROM Employee_CTE

Let’s break this down a bit.


CTE Query Definition
The blue portion is the CTE. Notice it contains a query that can be run on its own in
SQL. This is called the CTE query definition:

SELECT NationalIDNumber,

JobTitle

FROM HumanResources.Employee

When you run it you see results like:

CTE Query Definition Results


Notice that when we define the CTE we give the result a name as well its columns.
In this way a CTE acts like a VIEW. The result and columns are named differently.
This allows you to encapsulate complicated query logic with the common table
expression.

Now going back to the CTE, notice that the WITH statement. There you’ll see the
name and columns are defined. These columns correspond to the columns
returned from the inner query.
CTE Query Definition Column Mappings
Finally notice that our final query references the CTE and columns defined.

From our outer query’s perspective all it “sees” is this definition. It isn’t concerned
how the CTE is constructed, just its name and columns.

As such, the results from the CTE are:

Notice the column names, they’re based on the those defined in the CTE.
I want to point out that you can define more than one CTE within a WITH
statement. This can help you simplify some very complicated queries which are
ultimately joined together. Each complicated piece can include in their own CTE
which is then referred to and joined outside the WITH clause.

Here is an example using of TWO CTE’s, it’s a simple example, but it shows how two
CTE’s are defined, and then used in an INNER JOIN

WITH PersonCTE (BusinessEntityID, FirstName, LastName)


AS (SELECT Person.BusinessEntityID,
FirstName,
LastName
FROM Person.Person
WHERE LastName LIKE 'C%'),
PhoneCTE (BusinessEntityID, PhoneNumber)
AS (SELECT BusinessEntityID,
PhoneNumber
FROM Person.PersonPhone)
SELECT FirstName,
LastName,
PhoneNumber
FROM PersonCTE
INNER JOIN
PhoneCTE
ON PersonCTE.BusinessEntityID = PhoneCTE.BusinessEntityID;
The first common table expression is colored green, the second blue. As you can
see from the SELECT statement the CTE’s are joined as if they were tables.
Hopefully you can see that as your queries become more complicated, CTE’s can
become a really useful way to separate operations; therefore, simplify your final
query.

Why Do you need CTE’s?

There are several reasons why you may want to use a CTE over other methods.
Some of them include:
 Readability – CTE’s promote readability. Rather than lump all you query logic into
one large query, create several CTE’s, which are the combined later in the
statement. This lets you get the chunks of data you need and combine them in a
final SELECT.
 Substitute for a View – You can substitute a CTE for a view. This is handy if you don’t
have permissions to create a view object or you don’t want to create one as it is
only used in this one query.
 Recursion – Use CTE’s do create recursive queries, that is queries that can call
themselves. This is handy when you need to work on hierarchical data such as
organization charts.
 Limitations – Overcome SELECT statement limitations, such as referencing itself
(recursion), or performing GROUP BY using non-deterministic functions.
 Ranking – Whenever you want to use ranking function such as ROW_NUMBER(),
RANK(), NTILE() etc.

Types of CTE’s

Common Table Expressions can be placed into two broad categories: Recursive
CTE’s and Non-Recursive CTE’s.

Recursive CTE’s are common table expressions that reference themselves.


Recursion can be a pretty difficult topic to grasp, I really didn’t get it until I took
a LISP class way back in 1986, but hopefully I can explain it to you.
We’ll go deep into recursion in a separate post, but for now let me introduce to
you recursion using this diagram:
Here you see picture of opposing mirrors. Due to the reflection, it becomes a
picture in a picture.

Recursive queries are like that.

As a recursive query is run, it repeatedly runs on a subset of the data. A recursive


query is basically a query that calls itself. At some point there is an end condition,
so it doesn’t call itself indefinitely.

In a way when you look into the picture you can imagine each picture in a picture is
the picture calling itself. However, unlike the “infinite reflection” in the mirrors,
there comes a point where a recursive query encounters the end condition and
stop calling itself.
At that point, the recursion starts to unwind, collect and calculate data as it reviews
each successive result.

Non-Recursive CTE’s, as the name implies, are don’t use recursion. They don’t
reference themselves. They are easier to understand so we’ll look at them first in
detail in the next article within this series.

Conclusion

Hopefully you now have an appreciation of what CTE’s are and why we may want to
use them. In the next two article we’ll go into much greater detail on CTE’s, and
when to use them.

Until then, I would recommend reviewing my articles on joins and subqueries as


we’ll draw upon these types of queries for our examples.
SQL Server CTE Basics
The CTE was introduced into standard SQL in order to simplify various classes of
SQL Queries for which a derived table just wasn't suitable. For some reason, it can
be difficult to grasp the techniques of using it. Well, that's before Rob Sheldon
explained it all so clearly for us.

Introduced in SQL Server 2005, the common table expression (CTE) is a temporary
named result set that you can reference within a SELECT, INSERT, UPDATE, or
DELETE statement. You can also use a CTE in a CREATE VIEW statement, as part of
the view’s SELECT query. In addition, as of SQL Server 2008, you can add a CTE to
the new MERGE statement.

SQL Server supports two types of CTEs-recursive and nonrecursive. In this article, I
explain how to create both types. The examples I provide are based on a local
instance of SQL Server 2008 and retrieve data from the AdventureWorks2008
sample database.

Working with Common Table Expressions

You define CTEs by adding a WITH clause directly before your SELECT, INSERT,
UPDATE, DELETE, or MERGE statement. The WITH clause can include one or more
CTEs, as shown in the following syntax:

[WITH <common_table_expression> [,...]]

<common_table_expression>::=

cte_name [(column_name [,...])]

AS (cte_query)

…which can be represented like this…


As you can see, if you include more than one CTE in your WITH clause, you must
separate them with commas. In addition, for each CTE, you must provide a name,
the AS keyword, and a SELECT statement. You can also provide column names
(separated by commas), as long as the number of names match the number of
columns returned by the result set.

The SELECT statement in your CTE query must follow the same requirements as
those used for creating a view. For details about those requirements, see the topic
“CREATE VIEW (Transact-SQL)” in SQL Server Books Online. For more details about
CTEs in general, see the topic “WITH common_table_expression (Transact-SQL).”
After you define your WITH clause with the necessary CTEs, you can then reference
those CTEs as you would any other table. However, you can reference a CTE only
within the execution scope of the statement that immediately follows the WITH
clause. After you’ve run your statement, the CTE result set is not available to other
statements.

Creating a Nonrecursive Common Table Expression

A nonrecursive CTE is one that does not reference itself within the CTE.
Nonrecursive CTEs tend to be simpler than recursive CTEs, which is why I’m starting
with this type. In the following example, I create a CTE named cteTotalSales:

WITH

cteTotalSales (SalesPersonID, NetSales)

AS

SELECT SalesPersonID, ROUND(SUM(SubTotal), 2)

FROM Sales.SalesOrderHeader

WHERE SalesPersonID IS NOT NULL

GROUP BY SalesPersonID

SELECT

sp.FirstName + ' ' + sp.LastName AS FullName,

sp.City + ', ' + StateProvinceName AS Location,

ts.NetSales

FROM Sales.vSalesPerson AS sp

INNER JOIN cteTotalSales AS ts


ON sp.BusinessEntityID = ts.SalesPersonID

ORDER BY ts.NetSales DESC

After I specify the CTE name, I provide two column names, SalesPersonID and
NetSales, which are enclosed in parentheses and separated by a comma. That
means the result set returned by the CTE query must return two columns.

Next, I provide the AS keyword, then a set of parentheses that enclose the CTE
query. In this case, the SELECT statement returns the total sales for each sales
person (total sales grouped by salesperson ID). As you can see, the CTE query can
include Transact-SQL functions, GROUP BY clauses, or any elements that the
SELECT statement in a view definition can include.

I can now reference cteTotalSales in the statement that immediately follows. For
this example, I create a SELECT statement that joins the Sales.vSalesPerson view to
cteTotalSales, based on the salesperson ID. I then pull the names and locations
from the view and the net sales from the CTE. The following table shows the results
returned by this statement.

As you saw earlier in the syntax, you can include multiple CTEs in a WITH clause.
The following WITH clause includes two CTEs, one named cteTotalSales and one
named cteTargetDiff:

WITH
cteTotalSales (SalesPersonID, NetSales)

AS

SELECT SalesPersonID, ROUND(SUM(SubTotal), 2)

FROM Sales.SalesOrderHeader

WHERE SalesPersonID IS NOT NULL

AND OrderDate BETWEEN '2003-01-01 00:00:00.000'

AND '2003-12-31 23:59:59.000'

GROUP BY SalesPersonID

),

cteTargetDiff (SalesPersonID, SalesQuota, QuotaDiff)

AS

SELECT ts.SalesPersonID,

CASE

WHEN sp.SalesQuota IS NULL THEN 0

ELSE sp.SalesQuota

END,

CASE

WHEN sp.SalesQuota IS NULL THEN ts.NetSales

ELSE ts.NetSales - sp.SalesQuota

END
FROM cteTotalSales AS ts

INNER JOIN Sales.SalesPerson AS sp

ON ts.SalesPersonID = sp.BusinessEntityID

SELECT

sp.FirstName + ' ' + sp.LastName AS FullName,

sp.City,

ts.NetSales,

td.SalesQuota,

td.QuotaDiff

FROM Sales.vSalesPerson AS sp

INNER JOIN cteTotalSales AS ts

ON sp.BusinessEntityID = ts.SalesPersonID

INNER JOIN cteTargetDiff AS td

ON sp.BusinessEntityID = td.SalesPersonID

ORDER BY ts.NetSales DESC

The first CTE-cteTotalSales-is similar to the one in the preceding example, except
that the WHERE clause has been further qualified to include sales only from 2003.
After I define cteTotalSales, I add a comma, and then define cteTargetDiff, which
calculates the difference between the sales total and the sales quota.

The new CTE definition specifies three columns for the result set: SalesPersonID,
SalesQuota, and QuotaDiff. As you would expect, the CTE query returns three
columns. The first is the salesperson ID. The second is the sales quota. However,
because a sales quota is not defined for some salespeople I use a CASE statement.
If the value is null, that value is set to 0, otherwise the actual SalesQuota value is
used.

The final column returned is the difference between the net sales and sales quota.
Again, I use a CASE statement. If the SalesQuota value is null, then the NetSales
value is used, otherwise the sales quota is subtracted from the net sales to arrive at
the difference.

Something interesting to note about the second CTE query is that I’ve joined the
Sales.SalesPerson table to the first CTE-cteTotalSales-so I could calculate the
difference between total sales and the sales quota. Whenever you define multiple
CTEs in a single WITH clause, you can reference preceding CTEs (but not the other
way around).

Once I’ve defined my CTEs, I can reference them in the first statement that follows
the CTE, as you saw in the previous example. In this case, I join the
Sales.vSalesPerson view to cteTotalSales and then join to cteTargetDiff, all based on
the salesperson ID. My SELECT list then includes columns from all three sources.
The statement returns the results shown in the following table.

As you can see, sales data is provided for all salespeople, including the city in which
they reside, their net sales, their sales quota, and the calculated difference between
the two figures. In this case, everyone well exceeds the quota, where a quota has
been defined.
Creating a Recursive Common Table Expression

A recursive CTE is one that references itself within that CTE. The recursive CTE is
useful when working with hierarchical data because the CTE continues to execute
until the query returns the entire hierarchy.

A typical example of hierarchical data is a table that includes a list of employees.


For each employee, the table provides a reference to that person’s manager. That
reference is itself an employee ID within the same table. You can use a recursive
CTE to display the hierarchy of employee data, as it would appear within the
organizational chart.

Note that a CTE created incorrectly could enter an infinite loop. To prevent this, you
can include the MAXRECURSION hint in the OPTION clause of the primary SELECT,
INSERT, UPDATE, DELETE, or MERGE statement. For information about using query
hints, see the topic “Query Hints (Transact-SQL)” in SQL Server Books Online.

To demonstrate how the recursive CTE works, I used the following Transact-SQL
statements to create and populate the Employees table in the
AdventureWorks2008 database:

IF OBJECT_ID('Employees', 'U') IS NOT NULL

DROP TABLE dbo.Employees

GO

CREATE TABLE dbo.Employees

EmployeeID int NOT NULL PRIMARY KEY,

FirstName varchar(50) NOT NULL,

LastName varchar(50) NOT NULL,

ManagerID int NULL

)
GO

INSERT INTO Employees VALUES (101, 'Ken', 'Sánchez', NULL)

INSERT INTO Employees VALUES (102, 'Terri', 'Duffy', 101)

INSERT INTO Employees VALUES (103, 'Roberto', 'Tamburello', 101)

INSERT INTO Employees VALUES (104, 'Rob', 'Walters', 102)

INSERT INTO Employees VALUES (105, 'Gail', 'Erickson', 102)

INSERT INTO Employees VALUES (106, 'Jossef', 'Goldberg', 103)

INSERT INTO Employees VALUES (107, 'Dylan', 'Miller', 103)

INSERT INTO Employees VALUES (108, 'Diane', 'Margheim', 105)

INSERT INTO Employees VALUES (109, 'Gigi', 'Matthew', 105)

INSERT INTO Employees VALUES (110, 'Michael', 'Raheem', 106)

As you might realize, the AdventureWorks2008 database already includes the


HumanResources.Employee table. However, that table now uses the hierarchyid
data type to store hierarchical data, which would introduce unnecessary complexity
when trying to demonstrate a recursive CTE. For that reason, I created my own
table. However, if you want to try out a recursive CTE without creating and
populating a new table, you can use the AdventureWorks sample database that
shipped with SQL Server 2005. The HumanResources.Employee table in that
database stores the data in a way similar to the table I create above.

After I created the Employees table, I created the following SELECT statement,
which is preceded by a WITH clause that includes a CTE named cteReports:

WITH

cteReports (EmpID, FirstName, LastName, MgrID, EmpLevel)

AS

(
SELECT EmployeeID, FirstName, LastName, ManagerID, 1

FROM Employees

WHERE ManagerID IS NULL

UNION ALL

SELECT e.EmployeeID, e.FirstName, e.LastName, e.ManagerID,

r.EmpLevel + 1

FROM Employees e

INNER JOIN cteReports r

ON e.ManagerID = r.EmpID

SELECT

FirstName + ' ' + LastName AS FullName,

EmpLevel,

(SELECT FirstName + ' ' + LastName FROM Employees

WHERE EmployeeID = cteReports.MgrID) AS Manager

FROM cteReports

ORDER BY EmpLevel, MgrID

As you can see, the CTE returns five columns: EmpID, FirstName, LastName, MgrID,
and EmpLevel. The EmpLevel column refers to the level in the hierarchy in which
the employees fit. The highest level of the hierarchy is 1, the next level is 2, followed
by 3, and so on.

The CTE query is itself made up of two SELECT statements, connected with the
UNION ALL operator. A recursive CTE query must contain at least two members
(statements), connected by the UNION ALL, UNION, INTERSECT, or EXCEPT
operator. In this example, the first SELECT statement is the anchor member, and
the second statement is the recursive member. All anchor members must precede
the recursive members, and only the recursive members can reference the CTE
itself. In addition, all members must return the same number of columns with
corresponding data types.

Now lets look closer at the statements themselves. The first statement, the anchor
member, retrieves the employee ID, first name, last name, and manager ID from
the Employees table, where the manager ID is null. This would be the employee at
the top of the hierarchy, which means this person reports to no one. Consequently,
the manager ID value is null. To reflect that this person is at the top of the
hierarchy, I assign a value of 1 to the EmpLevel column.

The second statement in the CTE query-the recursive member-also retrieves the
employee ID, first name, last name, and manager ID for employees in the
Employees table. However, notice that I join the Employees table to the CTE itself. In
addition, the join is based on the manager ID in the Employees table and the
employee ID in the CTE. By doing this, the CTE will loop through the Employees
table until it returns the entire hierarchy.

One other item to notice about the second statement is that, for the EmpLevel
column, I add the value 1 to the EmpLevel value as it appears in the CTE. That way,
each time the statement loops through the hierarchy, the next correct level is
applied to the employees at the level.

After I define my WITH clause, I create a SELECT statement that retrieves the data
from the CTE. Note, however, that for the Manager column, I retrieve the first and
last name of the employee associated with the manager ID in the CTE. This allows
me to display the full name of the manager for each employee. The following table
shows the result set returned by the SELECT statement and its CTE.
As you can see, the CTE, whether recursive or nonrecursive, can be a useful tool
when you need to generate temporary result sets that can be accessed in a SELECT,
INSERT, UPDATE, DELETE, or MERGE statement. In a sense, a CTE is like a derived
table: it’s not stored as an object and is valid only during the execution of the
primary statement. However, unlike the derived table, a CTE can be referenced
multiple times within a query and it can be self-referencing. And best of all, CTEs
are relatively easy to implement.

You must have heard CTE before. If you don’t know much about it, then don’t worry
at all. I will be giving you some heads up:

 The Common Table Expression (CTE) was introduced earlier in the SQL
Server 2005.
 The CTE defines about a temporary view, which can be referenced in the
same query just as a view .
 The CTE’s can be used and compiled in exactly the same ways that simple
Subqueries are being used.
 It can be used instead of temp table or table variables in the stored
procedures in the circumstances.
 CTE’s can also recursively refer to the same table using a union or union all,
and this works great for searching an adjacency pairs pattern hierarchy.
 The CTE uses the WITH clause, so the syntax can be shown as:

1 WITH CTEName (Column aliases)


2 AS (Subquery)
3 SELECT statement
4 FROM CTEName;

 Here the Select statement must be very next to the CTE. The name is
mandatory and the argument is an optional. This can be used to give the
alias to the retrieve field of the CTE.
 The WITH keyword not only begins a CTE, it also adds a hint to a table
reference. This is why the statement before a CTE must be terminated with
a semicolon.
 The following example will make you understand what actually is the CTE;

I have two tables; Students1 and Students2-

Now, we will create a CTE named as ‘CTE1’ which will select SID column from
Students2 table. So, the CTE1 can be called anywhere in the outer query where it
needs. Like it is being called in the WHERE clause here, because we need to retrieve
the Names of Students1 table, where SID is being equal to CTE1:

1 WITH CTE1 (SID)


2 AS (SELECT SID FROM Students2 WHERE Name = 'Robin')
3 SELECT Name FROM Students1
4 WHERE SID = (SELECT SID FROM CTE1);
The result can be seen as:
Suppose, if want to retrieve data from multiple tables, then it’s better to use CTE
with multiple references. This will become clearer, if you follow up the example:

For this, we will also have to include the third table Persons;

Now, if I want to retrieve all the details from these three tables about all the name
of the students from the Students1 table, then write the query like this:

1 WITH CTESTUD1
2 AS (SELECT SID,Name,City,State FROM Students1),
3 CTESTUD2
4 AS (SELECT SID,Cell_No FROM Students2),
5 CTEPER
6 AS (SELECT P_Id,Address,M_Id FROM Persons)
7 SELECT CTESTUD1.SID, Name, Address, Cell_No, City, State
8 FROM CTESTUD1
9 LEFT JOIN CTESTUD2 ON CTESTUD1.SID = CTESTUD2.SID
10 LEFT JOIN CTEPER ON CTESTUD2.SID = CTEPER.P_Id;
The result set will be;
There are two disadvantages involved with this:

 Firstly, CTEs cannot be nested like Subqueries.


 Secondly, CTEs cannot reference the main query; they are self-contained like
the simple Subqueries. They may reference to any of the CTEs defined before
it or even to itself.
SQL Server Common Table Expressions
(CTE) usage and examples
Problem

Many organizations have some type of hierarchy for business processes. When it
comes to large organizations, the hierarchy can get very complex and large, so
building a hierarchy in a RDBMS is a tedious task. We have to create views, cursors
and so on, but using a CTE in SQL Server is a better solution to retrieve hierarchy-
based data and in this tip, I will show you how.

Solution

Common Table Expressions (CTE) have two types, recursive and non-recursive. We
will see how the recursive CTE works with examples in this tip.

A recursive CTE can be explained in three parts:

 Anchor Query: This is the first statement which is executed. This query will
give the base data for the CTE.
 Separator: This is the middle part where in we generally use a UNION ALL
and few more operators.
 Recursive Query: This is the main part, this is the CTE query which refers to
the same CTE by recursion.

Let’s us create an example of CTE

Let’s take a scenario of an organization (org) chart. In this example the organization
chart would start from "CEO" and end up at the “Purchase Department”. Each
department/person is linked to the predecessor as nodes. Let's see how a CTE can
be used to achieve this in SQL Server. We will also touch base on how to use
MAXRECURSION when using a CTE.
Let's create a sample table.

IF OBJECT_ID ('MyDepartment','U') IS NOT NULL


DROP TABLE MyDepartment;
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[MyDepartment]


(
[DepartmentID] [smallint] NOT NULL,
[DepartmentName] [nvarchar](30) NOT NULL,
[ParentID] [nvarchar](40) NULL,
CONSTRAINT [PK_DepartmentID] PRIMARY KEY CLUSTERED ( [DepartmentID] ASC
)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY =
OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

Now the table is created and we can populate the table with values the table
“MyDepartment”. The below insert statements can be executed to insert the data
into “MyDepartment” table.

INSERT INTO [dbo].[MyDepartment]


([DepartmentID],[DepartmentName],[ParentID])
VALUES
('1','CEO',null),
('2','President','1'),
('3','Chairman','1'),
('4','Vice President','2'),
('5','Associate Vice President','4'),
('6','Senior Manager','4'),
('7','Delivery Manager','4'),
('8','Program Manager','4'),
('9','Project Manager','5'),
('10','Planning Manager','5'),
('11','Execution Manager','5'),
('12','Project Leader','6'),
('13','Project Planner','6'),
('14','Senior Project Lead','12'),
('15','Team Lead','12'),
('16','Sprint Lead','12'),
('17','Statistics Department','6'),
('18','Logistics Department','6'),
('19','Sales Account','7'),
('20','Customer Service','7'),
('21','Product Support B','8'),
('22','Sales Department','21'),
('23','Purchase Department','21'),
('24','Group Manager','8'),
('25','Overseas Department','24'),
('26','Domestic Department','24');
go
The ParentID for the top-most tree is set to NULL indicating that there is no parent
for this row. Now that we have loaded the data we can code a query to walk the
hierarchy using a Common Table Expression.

We need to report on the entire organizational structure under the CEO. The
following recursive code using a CTE will get us the output:

WITH OrgTree (DepartmentID, DepartmentName, ParentID, Tree)


AS
(
SELECT DepartmentID, DepartmentName, ParentID , 0 AS Tree
FROM MyDepartment
WHERE ParentID IS NULL
UNION ALL
SELECT MyDepartment.DepartmentID, MyDepartment.DepartmentName,
MyDepartment.ParentID , OrgTree.Tree + 1
FROM MyDepartment
JOIN OrgTree ON MyDepartment.ParentID = OrgTree.DepartmentID
)

SELECT * FROM OrgTree ORDER BY Tree

Below is the output from the above query execution.

DepartmentID DepartmentName ParentID Tree

1 CEO NULL 0

2 President 1 1

3 Chairman 1 1

4 Vice President 2 2

5 Associate Vice President 4 3


6 Senior Manager 4 3

7 Delivery Manager 4 3

8 Program Manager 4 3

21 Product Support B 8 4

24 Group Manager 8 4

19 Sales Account 7 4

20 Customer Service 7 4

12 Project Leader 6 4

13 Project Planner 6 4

17 Statistics Department 6 4

18 Logistics Department 6 4

9 Project Manager 5 4

10 Planning Manager 5 4

11 Execution Manager 5 4

14 Senior Project Lead 12 5

15 Team Lead 12 5
16 Sprint Lead 12 5

25 Overseas Department 24 5

26 Domestic Department 24 5

22 Sales Department 21 5

23 Purchase Department 21 5

Anchor Query

Creating tables is one piece of it, inserting data is another group in the example.
The important part is implementing the CTE using the WITH clause. For our
example the name of the CTE is named as “OrgTree”. The first select in the CTE is
used to extract the first node of the Tree which is “CEO” and the Parent ID is set as
NULL. The below query will get the first node in our example.

SELECT DepartmentID, DepartmentName, ParentID , 0 AS Tree


FROM MyDepartment
WHERE ParentID IS NULL

DepartmentID DepartmentName ParentID Tree

1 CEO NULL 0

Below I explain the data. The left side has the parent data and the right side has
the child data. If you notice DepartmentID 1 (left side) is the parent for
DepartmentID (right side) 2 and 3. If you look further each DepartmentID is
connected with the ParentID in the child table. Below is the image representation of
the query that was generated above. The arrow connects the DepartmentID and
ParentID for our reference.
Separator and Recursive Query

The next section is the INNER JOIN combining the CTE where in recursion comes
into picture, which intern refers to itself. The INNER JOIN retrieves the data by
splitting the “MyDepartment” table into two parts using the OrgTree CTE and does a
join and creates the CTE for us to query the CTE.

SELECT MyDepartment.DepartmentID, MyDepartment.DepartmentName,


MyDepartment.ParentID , OrgTree.Tree + 1
FROM MyDepartment
JOIN OrgTree ON MyDepartment.ParentID = OrgTree.DepartmentID
Query Designer

The below Query Designer screen print is available for us to see the query in the
Designer. The right-side is the CTE - “OrgTree”, since CTE will be created after
execution the Query Designer does not show the columns, if you notice the
“MyDepartment” table has the column and the INNER JOIN reference.

MAXRECURSION

When it comes to using a CTE one of the problems faced is an infinite loop while
forming the CTE. In general, when the parent and child query returns the same or
equal value, the CTE may go into an infinite loop and the transaction may go into an
infinite loop. To avoid this there is an option clause which can be used at the end of
CTE SELECT command with the key word MAXRECURSION and the row count. Using
0 has no restriction, but in our example I have used a value of 10.

WITH OrgTree (DepartmentID, DepartmentName, ParentID, Tree)


AS
(
SELECT DepartmentID, DepartmentName, ParentID, 0 AS Tree
FROM MyDepartment
WHERE ParentID IS NULL
UNION ALL
SELECT MyDepartment.DepartmentID, MyDepartment.DepartmentName,
MyDepartment.ParentID, OrgTree.Tree + 1
FROM MyDepartment
JOIN OrgTree ON MyDepartment.ParentID = OrgTree.DepartmentID
)
SELECT * FROM OrgTree OPTION (MAXRECURSION 10)

Example Queries

Try these example queries to find the data and see if you can come up with other
scenarios and how to query the data.

-- return everyone under Program Manager (ParentID = 8)


WITH OrgTree (DepartmentID, DepartmentName, ParentID, Tree)
AS
(
SELECT DepartmentID, DepartmentName, ParentID , 0 AS Tree
FROM MyDepartment
WHERE ParentID = 8
UNION ALL
SELECT MyDepartment.DepartmentID, MyDepartment.DepartmentName,
MyDepartment.ParentID , OrgTree.Tree + 1
FROM MyDepartment
JOIN OrgTree ON MyDepartment.ParentID = OrgTree.DepartmentID
)
SELECT * FROM OrgTree;

-- return Vice President (DepartmentID = 4) and direct reports (ParentID = 4)


WITH OrgTree (DepartmentID, DepartmentName, ParentID, Tree)
AS
(
SELECT DepartmentID, DepartmentName, ParentID , 0 AS Tree
FROM MyDepartment
WHERE DepartmentID = 4
UNION ALL
SELECT MyDepartment.DepartmentID, MyDepartment.DepartmentName,
MyDepartment.ParentID , OrgTree.Tree + 1
FROM MyDepartment
JOIN OrgTree ON MyDepartment.ParentID = OrgTree.DepartmentID
WHERE MyDepartment.ParentID = 4
)
SELECT * FROM OrgTree;

-- return everyone above Senior Manager (DepartmentID = 6)


WITH OrgTree(DepartmentName,ParentID,ReportsTo)AS
(
SELECT T1.DepartmentName,T2.DepartmentID,T2.DepartmentName
FROM MyDepartment T1
INNER JOIN MyDepartment T2 ON T1.ParentID=T2.DepartmentID
WHERE T1.DepartmentID=6
UNION ALL
SELECT OT.ReportsTo,T2.DepartmentID,T2.DepartmentName
FROM OrgTree OT
INNER JOIN MyDepartment T1 ON OT.ParentID=T1.DepartmentID
INNER JOIN MyDepartment T2 ON T1.ParentID=T2.DepartmentID
)
SELECT * FROM OrgTree;

-- return list with of people with no direct reports


WITH OrgTree(ParentID, DepartmentID, DepartmentName, DepartmentLevel) AS
(
SELECT ParentID, DepartmentID, DepartmentName, 0 AS DepartmentLevell
FROM MyDepartment
WHERE ParentID IS NULL
UNION ALL
SELECT e.ParentID, e.DepartmentID, e.DepartmentName, DepartmentLevel + 1
FROM MyDepartment AS e
INNER JOIN OrgTree AS d ON e.ParentID = d.DepartmentID
)
SELECT * FROM OrgTree WHERE DepartmentLevel = 5;
Next Steps
 CTEs are a powerful feature in SQL Server. The syntax is easy to use and we
can build any kind of hierarchical tables and data based on our needs using a
CTE.
Recursive Queries using Common Table
Expressions (CTE) in SQL Server
Problem
In SQL Server 2000, you need to implement recursive queries to retrieve data which
is presented in a hierarchical format. We normally resort to implementing views,
cursors or derived tables and perform queries against them. The problem arises
when the hierarchy level increases as SQL Server is limited to 32 levels of recursion.
We need a better way to implement recursive queries in SQL Server 2005. How do
we do it?

Solution
Common Table Expression (CTE) was introduced in SQL Server 2005 and can be
thought of as a temporary result set that is defined within the execution scope of a
single SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW statement. You can think
of CTE as an improved version of derived tables that more closely resemble a non-
persistent type of view. Look at CTEs as your derived tables in SQL Server 2000. A
CTE can be used in many of the same ways you use a derived table. CTEs can also
contain references to themselves. This allows the developer to write complex
queries simpler. CTEs can also be used in place of views. The use of CTEs provides
two main advantages. One is that queries with derived table definitions become
more simple and readable. While traditional T-SQL constructs that are used to work
with derived tables normally requires a separate definition for the derived data
such as a temporary table or a table-valued function, using CTEs make it easier to
see the definition of the derived table with the code that uses it. The other thing is
that CTEs significantly reduces the amount of code required for a query that
traverses recursive hierarchies.

To understand what a CTE is all about, let's first take a look at the syntax to create it
in SQL Server 2005.

Syntax
In general form a recursive CTE has the following syntax:

WITH cte_alias (column_aliases)


AS
(
cte_query_definition --initialization
UNION ALL
cte_query_definition2 --recursive execution
)
SELECT * FROM cte_alias

You provide the CTE with an alias and an optional list of aliases for its result
columns following the keyword WITH which usually defines the derived table based
on the query definition; write the body of the CTE; and refer to it from the outer
query.

To put this in the right perspective, let's come up with a simple example which uses
recursion. We'll look at the Employees table in the Northwind database and see
that a particular employee reports to another employee. One question we can
come up with is, "Who reports to whom?" The Employees table is designed in such
a way that the ReportsTo column is a foreign key field that refers to the primary key
field EmployeeID. Thus, we can create a query to answer our question. A sample
query using CTE will look something like this.

WITH Managers AS
(
--initialization
SELECT EmployeeID, LastName, ReportsTo
FROM Employees
WHERE ReportsTo IS NULL
UNION ALL
--recursive execution
SELECT e.employeeID,e.LastName, e.ReportsTo
FROM Employees e INNER JOIN Managers m
ON e.ReportsTo = m.employeeID
)
SELECT * FROM Managers
Code Walkthrough

1. The recursive CTE, Managers, defines an initialization query and a recursive


execution query
2. The initialization query returns the base result and is the highest level in the
hierarchy. This is identified by the ReportsTo value of NULL, which means
that the particular Employee does not report to anybody. Depending on how
the table is designed, the value can be anything as long as it represents the
highest level in the hierarchy
3. The recursive execution query is then joined to the initialization query using
the UNION ALL keyword. The result set is based on the direct subordinate as
returned by the initialization query, which then appears as the next level in
the hierarchy. Recursion occurs because of the query referencing the CTE
itself based on the Employee in the Managers CTE as input. The join then
returns the employees who have their managers as the previous record
returned by the recursive query. The recursive query is repeated until it
returns an empty result set.
4. The final result set is returned by querying the Managers CTE

The sample query contains the elements that a recursive CTE must contain. What's
more is that the code is a lot more readable. This enables the developers to write
complex queries with ease.

You can also use a query hint to stop a statement after a defined number of loops.
This can stop a CTE from going into an infinite loop on a poorly coded statement.
You do this by including the MAXRECURSION keyword in the SELECT query referring
to the CTE. To use it in the previous example

SELECT * FROM Managers OPTION (MAXRECURSION 4)

To create a similar yet non-recursive query that produces the same result in SQL
Server 2000, you might come up with something similar to this code:

DECLARE @rowsAdded INT

--table variable to hold accumulated results


DECLARE @managers TABLE --initialize @managers who do not have managers
(EmpID INT, MgrID INT, processed INT DEFAULT(0))

INSERT @managers
SELECT EmployeeID, ReportsTo, 0
FROM Employees
WHERE ReportsTo IS NULL

SET @rowsAdded=@@rowcount

--do this while new employees are added in the previous iteration
WHILE @rowsAdded > 0
BEGIN

--mark employee records going to be found in this iteration with --processed=1


UPDATE @managers SET processed=1 WHERE processed=0

--insert employees who report to employees not yet processed


INSERT @managers
SELECT EmployeeID, ReportsTo, 0
FROM Employees e
INNER JOIN @managers r ON e.ReportsTo = r.EmpID
WHERE ReportsTo <> EmployeeID AND r.processed = 1

SET @rowsAdded = @@rowcount

--mark employee records found in this iteration as processed


UPDATE @managers SET processed=2 WHERE processed=1

END

SELECT * FROM @managers

Next Steps
Given the example above, hierarchical data structures, organizational charts and
other parent-child table relationship reports can easily benefit from the use of
recursive CTEs. Common Table Expression is just one of those T-SQL enhancements
available for SQL Server 2005. CTEs bring us the chance to create much more
complex queries while retaining a much simpler syntax. They also can lessen the
administrative burden of creating and testing views for situations where the view
will not be reused.
How to use SQL Server CTEs to make
your T-SQL code readable by humans
Problem

If you're the sort of person who can effortlessly write complicated queries in SQL
using a single SELECT statement, please click away from this article now! However,
if ( like me ) your brain spins in proportion to the complexity of the query you're
writing, read on to see how to use CTEs (Common Table Expressions) to break up
complex queries into several distinct steps.

Solution

Let's start with a sample library database. I've deliberately kept this as simple as
possible. It consists of just two tables:

Each author can have one or more books in the tblBook table, with
the AuthorId column being used as a foreign key. If you want to reproduce this
yourself, run this script:

-- create a database to hold OUR books


CREATE DATABASE Library
GO
USE Library
GO
-- create a table of authors
CREATE TABLE tblAuthor(
AuthorId int PRIMARY KEY,
FirstName varchar(50),
LastName varchar(50)
)
GO
-- add some authors
INSERT tblAuthor (AuthorId, FirstName, LastName) VALUES (1, 'John', 'Wyndham')
INSERT tblAuthor (AuthorId, FirstName, LastName) VALUES (2, 'Barbara',
'Kingsolver')
INSERT tblAuthor (AuthorId, FirstName, LastName) VALUES (3, 'Jane', 'Austen')
-- create a table of books
CREATE TABLE tblBook(
BookId int PRIMARY KEY,
BookName varchar(100),
AuthorId int,
Rating int
)
-- add some books
INSERT tblBook (BookId, BookName, AuthorId, Rating) VALUES (1, 'The Day of the
Triffids', 1, 10)
INSERT tblBook (BookId, BookName, AuthorId, Rating) VALUES (2, 'The Chrysalids',
1, 8)
INSERT tblBook (BookId, BookName, AuthorId, Rating) VALUES (3, 'The Lacuna', 2,
10)
INSERT tblBook (BookId, BookName, AuthorId, Rating) VALUES (4, 'The Poisonwood
Bible', 2, 8)
INSERT tblBook (BookId, BookName, AuthorId, Rating) VALUES (5, 'Pride and
Prejudice', 3, 9)

You should now have 3 authors and 5 books.

A single-query solution

Suppose that you want to list out in alphabetical order the authors who have
written more than 1 book. You could do this with a single query:

-- list authors who have written more than one book


SELECT
a.FirstName + ' ' + a.LastName AS Author,
COUNT(*) AS 'Number of books'
FROM
tblAuthor AS a
INNER JOIN tblBook AS b ON a.AuthorId=b.AuthorId
GROUP BY
a.FirstName + ' ' + a.LastName
HAVING
COUNT(*) > 1
ORDER BY
Author

There's nothing wrong with this approach. Indeed for relatively simple queries like
this one it's probably the best one, but as your queries get more complicated, it'll
become ever harder to keep the whole picture in your head. The reason I like CTEs
so much is that they allow you to break down a problem into different parts (always
the holy grail in computing). To see how this works, we'll solve the above problem
again - but more slowly.

A CTE solution

The following solution uses a common table expression, giving the following
advantages:

 It avoids the need to repeat expressions in HAVING or GROUP BY clauses;


 It reads more logically and more intuitively.

To get things started, we need to get a list showing each author's id, together with
the number of books they've written:

USE Library;
-- list authors with the number of books they've written
WITH cteBooksByAuthor AS (
SELECT AuthorId, COUNT(*) AS CountBooks
FROM tblBook
GROUP BY AuthorId
)
-- use this CTE
SELECT * FROM BooksByAuthor

Notice that the statement immediately before the CTE has to end with a semi-colon
where I have "USE Library;", but this would be for any statement that is prior to the
CTE.
What this query does is to create a temporary table-like object
called cteBooksByAuthor, then immediately refers to it in the following
statement. Note that CTEs are like cheese souffles: they can only be used as soon
as they've been created. If we issued another query after this the CTE can no
longer be referenced.

Now that you've created a CTE, we can join it - as for any other table - to another
table to get at the authors' names. So our final query is:

USE Library;
-- list authors with the number of books they've written
WITH cteBooksByAuthor AS (
SELECT AuthorId, COUNT(*) AS CountBooks
FROM tblBook
GROUP BY AuthorId
)
-- use this CTE to show authors who have written
-- more than 1 book
SELECT
a.FirstName + ' ' + a.LastName AS Author,
cte.CountBooks AS 'Number of books'
FROM
cteBooksByAuthor AS cte
INNER JOIN tblAuthor AS a ON cte.AuthorId=a.AuthorId
WHERE cte.CountBooks > 1

Not convinced? A slightly more complicated example ...

If the above doesn't convince you, consider this slightly more complicated
query. Suppose that you want to show for each author their book with the highest
rating. You could easily accomplish this with a single correlated subquery, but many
SQL programmers will find it easy to break the task into two parts. First get a list
for each author of their highest rating:
You can now link this to the books table, to get the books shown highlighted below:

Here's our CTE to return the right results:

USE Library
GO
-- get a "temporary table" (a CTE) of highest score for each author
-- (don't need a semi-colon as this is now first statement in batch)
WITH HighestRatings AS (
SELECT
author.AuthorId,
MAX(book.Rating) AS HighestRating
FROM
tblBook AS book
INNER JOIN tblAuthor AS author ON book.AuthorId=author.AuthorId
GROUP BY
author.AuthorId
)
-- get the name of book and name of author
SELECT
author.FirstName + ' ' + author.LastName AS Author,
book.BookName AS Title,
hr.HighestRating AS Rating
FROM
HighestRatings AS hr
INNER JOIN tblBook AS book ON hr.HighestRating=book.Rating and
hr.AuthorId=book.AuthorId
INNER JOIN tblAuthor AS author ON book.AuthorId=author.AuthorId

This would return the following set of rows:


Whether you think that the CTE solution is easier to write is a matter for debate; but
conceptually it is easier to read, I'd claim!
SQL Server CTE and XML Recursion
Script
Problem

In SQL Server we normally use a Common Table Expression (CTE) for recursion
data. In my scenario, I need to get every parent node against each child node. How
can we solve this problem in SQL Server using a CTE and XML?

Solution

Let's start off with an example to demonstrate the CTE and XML solution.

Here is an example of the mapping for my employee hierarchy:

 ManagerA > (reports to no one)


 ManagerB > (reports to no one)
 ManagerRA > ManagerA
 ManagerRB > ManagerA
 ManagerRC > ManagerB
 ManagerRD > ManagerB
 ManagerRLA > ManagerRA > ManagerA
 ManagerRLB > ManagerRB > ManagerA
 ManagerRLC > ManagerRC > ManagerB
 ManagerRLD > ManagerRD > ManagerB

Below is a script for an employee table and sample data to run in your test
environment.

CREATE TABLE employee


(
id INT,
empName NVARCHAR(200),
designation VARCHAR(50),
fk_parentEMP INT
)
GO
INSERT INTO employee
SELECT 1,'ManagerA','GM',0
UNION ALL
SELECT 2,'ManagerB','GM',0
UNION All
SELECT 3,'ManagerRA','RM',1
UNION ALL
SELECT 4,'ManagerRB','RM',1
UNION All
SELECT 5,'ManagerRC','RM',2
UNION ALL
SELECT 6,'ManagerRD','RM',2
UNION All
SELECT 7,'ManagerRLA','LM',3
UNION ALL
SELECT 8,'ManagerRLB','LM',4
UNION All
SELECT 9,'ManagerRLC','LM',5
UNION ALL
SELECT 10,'ManagerRLD','LM',6
GO

Now the employee table has been created and here is our mapping. The values in
the parentheses show the map path to the ID column in the table.

 ManagerA > (reports to no one) = (1 > 0)


 ManagerB > (reports to no one) = (2 > 0)
 ManagerRA > ManagerA = (3 > 1)
 ManagerRB > ManagerA = (4 > 1)
 ManagerRC > ManagerB = (5 > 2)
 ManagerRD > ManagerB = (6 > 2)
 ManagerRLA > ManagerRA > ManagerA = (7 > 3 > 1)
 ManagerRLB > ManagerRB > ManagerA = (8 > 4 > 1)
 ManagerRLC > ManagerRC > ManagerB = (9 > 5 > 2)
 ManagerRLD > ManagerRD > ManagerB = (10 > 6 > 2)

This is what the data looks like in the table:


Here is the expected output that has the mapping that we need:

So how would I build a query to produce these results?

SQL Server CTE and XML Recursion Script

First I will prepare a query using a CTE for recursion:

;WITH EmployeeCTE
AS (
SELECT
CAST(ISNULL(em.id,'0') AS VARCHAR(MAX)) AS vPath,
em.id,
em.empName AS empName,
ISNULL(em.fk_parentEMP,'0') fk_parentEMP,
em.Designation
FROM dbo.EMPLOYEE (NOLOCK) em
WHERE ISNULL(em.fk_parentEMP, 0) = 0
UNION ALL
SELECT
CAST(ee.vPath + '/' + CAST( em.id AS VARCHAR(12)) AS VARCHAR(MAX))AS
vPath,
em.id,
em.empName AS empName ,
ISNULL(em.fk_parentEMP,'0') fk_parentEMP,
em.Designation
FROM dbo.EMPLOYEE (NOLOCK) em
INNER JOIN EmployeeCTE ee ON ee.id = em.fk_parentEMP
)
SELECT * FROM EmployeeCTE

The vPath column shows the entire path for the each position. For the ManagerA
and ManagerB since they do not report to anyone I am showing that the vPath is
just their ID. For the additional positions, the vPath matches the information above
in the mapping of each position.

Below is the final query to convert the vPath values to the output we want.

;WITH EmployeeCTE
AS (
SELECT
CAST(ISNULL(em.id,'0') AS VARCHAR(MAX)) AS vPath,
em.id,
em.empName AS empName,
ISNULL(em.fk_parentEMP,'0') fk_parentEMP,
em.Designation
FROM dbo.EMPLOYEE (NOLOCK) em
WHERE ISNULL(em.fk_parentEMP, 0) = 0
UNION ALL
SELECT
CAST(ee.vPath + '/' + CAST( em.id AS VARCHAR(12)) AS VARCHAR(MAX)) AS
vPath,
em.id,
em.empName AS empName ,
ISNULL(em.fk_parentEMP,'0') fk_parentEMP,
em.Designation
FROM dbo.EMPLOYEE (NOLOCK) em
INNER JOIN EmployeeCTE ee ON ee.id = em.fk_parentEMP
)

SELECT
id,
empName,
fk_parentEMP,
Designation
FROM
(
SELECT
edm.id id,
edm.empName,
edm.fk_parentEMP,
vPath,
Designation
FROM EmployeeCTE edm
WHERE ISNULL(edm.fk_parentEMP,'0') = '0'
UNION
SELECT
id AS id,
empName,
tra.a.value('.', 'varchar(50)') AS fk_parentEMP,
vPath,
Designation
FROM (SELECT CAST('<Emp><Child>' + REPLACE(vPath, '/', '</Child><Child>') +
'</Child></Emp>' AS XML) AS list ,
id,
empName,
fk_parentEMP,
vPath,
Designation
FROM EmployeeCTE
)a
CROSS APPLY LIST.nodes('/Emp/Child') AS tra ( A )
) t1
WHERE t1.id <> t1.fk_parentEMP
ORDER BY vPath ASC

Now I am able to generate the result as expected:


Fix SQL Server CTE Maximum Recursion
Exhausted Error
Problem

Common Table Expression, also known as a CTE, can be thought of as a derived


table that is defined within the query execution scope, without being stored
physically in the database and survives only for the running query duration. A CTE
allows us to write more readable, maintainable complex queries, by dividing these
queries into small blocks that can be gathered together to build the final complex
query. The CTE can be easily included within stored
procedures, views, triggers and functions.

One of the most useful benefits of the CTE is the ability to create a recursive query
within it. This means that the CTE can be self-referenced within the same query. But
if it is not designed carefully, it may result in an infinite loop. To prevent that, SQL
Server set the default value of the recursion level to 100. In specific cases, you may
exceed that default value of recursion. In this case the query will fail showing that
you can’t exceed this 100 limitation. How could we tune the recursion value to fit
our query?

Solution

Limiting the number of recursions allowed for a specific query in SQL Server with
the 100 default value prevents the cause of an infinite loop situation due to a
poorly designed recursive CTE query. But it also leaves the choice for you to tune
that value to fit your query, where you can easily increase or decrease that value at
the query level using the MAXRECURSION query hint in the OPTION clause. The
MAXRECURSION value specifies the number of times that the CTE can recur before
throwing an error and terminating.

You can provide the MAXRECURSION hint with any value between 0 and 32,767
within your T-SQL query, with MAXRECURSION value equal to 0 means that no limit
is applied to the recursion level. This opens up the risk of an infinite loop with
poorly written queries.

Let's start our demo to understand how it works practically. Assume that we have a
user-defined function that is used to split the strings depending on the provided
delimiter. The function is written using the recursive CTE mechanism. One of the
ways that can be used to write a function is shown below:

USE MSSQLTipsDemo
GO
CREATE FUNCTION [dbo].[SplitString]
(
@String NVARCHAR(4000),
@Delimiter NCHAR(1)
)
RETURNS TABLE
AS
RETURN
(
WITH Split(stpos,endpos)
AS(
SELECT 0 AS stpos, CHARINDEX(@Delimiter,@String) AS endpos
UNION ALL
SELECT endpos+1, CHARINDEX(@Delimiter,@String,endpos+1)
FROM Split
WHERE endpos > 0
)
SELECT 'Value' =
SUBSTRING(@String,stpos,COALESCE(NULLIF(endpos,0),LEN(@String)+1)-stpos)
FROM Split
)

This type of function is sometimes used for splitting strings in some systems. For
example, the below stored procedure takes a list of comma separated entities as a
parameter and returns these entities as individual entities:

USE MSSQLTipsDemo
GO
CREATE PROC REC_Entity (@Entity AS NVARCHAR(MAX))
AS
BEGIN

CREATE TABLE #Entity (RetValue NVARCHAR (3))


INSERT INTO #Entity SELECT * from [SplitString] (@Entity, ',')
SELECT * FROM #Entity
DROP TABLE #Entity

END

Now, we will declare two entities lists; @ENTITY1 and @ENTITY2, @ENTITY1 contains
about 24 comma separated entities and @ENTITY2 contains about 110 comma
separated entities. We will pass these two parameters to the previously created
stored procedure to split its values using the T-SQL script below:

DECLARE @ENTITY1 AS NVARCHAR(MAX)


DECLARE @ENTITY2 AS NVARCHAR(MAX)

SET
@ENTITY1='AZZ,AZT,AZS,AZR,AZP,AZO,AZN,AZL,AZI,AZG,AZD,AZB,AZA,AYY,AYW,AYU,
AYT,AYS,AYR,AYQ,AYP,AYO,AYN,AYM'
SET
@ENTITY2='AYL,AYK,AYI,AYG,AYD,AYC,AYA,AXX,AXV,AXU,AXT,AXS,AXR,AXP,AXN,AXM,
AXL,AXK,AXJ,AXG,AXF,AXE,AXD,AXC,AXB,AXA,AWZ,AWR,AWP,AWN,AWM,AWK,AWE,A
WD,AWB,AWA,AVX,AVW,AVV,AVU,AVP,AVO,AVN,AVL,AVK,AVI,AVG,AVB,AVA,AUZ,AUY,
AUX,AUW,AUV,AUU,AUT,AUS,AUR,AUQ,AUP,AUO,AUN,AUM,AUL,AUK,AUJ,AUI,AUH,A
UG,AUF,AUE,AUD,AUC,AUA,ATZ,ATY,ATX,ATW,ATV,ATU,ATT,ATS,ATR,ATQ,ATP,ATO,AT
N,ATM,ATL,ATK,ATJ,ATI,ATH,ATG,ATF,ATE,ATD,ATC,ATB,ATA,ASZ,ASY,ASX,ASW,ASV,AS
U,AST,ASR,ASQ,ASP'

EXEC REC_Entity @ENTITY1


EXEC REC_Entity @ENTITY2

Running the previous query, you will see from the result that splitting the first
parameter that contains 24 comma separated entities will be completed
successfully, and splitting the second entities list will fail as shown in the result
below:
Checking the error message returned from the query execution, you will see that
splitting the second entities list failed due to exceeding the maximum recursion
level default value of 100. The first entities list requires 24 recursions to be split,
which is less than the 100 maximum number of recursions. Splitting the second
entities list requires 110 recursions, exceeding the 100 default value of recursions.
Recall that this recursion limitation is mainly used to protect the system from the
infinite loop issue resulting from the poorly written queries. The error will be as
shown below:

As we mentioned previously, although this limit will protect you from the infinite
loop issue, you can easily tune the MAXRECURSION value to fit your query. You can
use the MAXRECURSION query hint within the previously defined stored procedure
in the part that calls the string splitting function to fit this query only, with
MAXRECURSION value equal to 110, using the modified stored procedure below:

USE MSSQLTipsDemo
GO
ALTER PROC REC_Entity (@Entity AS NVARCHAR(MAX))
AS
BEGIN

CREATE TABLE #Entity (RetValue NVARCHAR (3))


INSERT INTO #Entity SELECT * from [SplitString] (@Entity, ',') OPTION
(MAXRECURSION 110)
SELECT * FROM #Entity
DROP TABLE #Entity

END

Executing the modified stored procedure again to split the same two entities lists
using the T-SQL script below:

DECLARE @ENTITY1 AS NVARCHAR(MAX)


DECLARE @ENTITY2 AS NVARCHAR(MAX)
SET
@ENTITY1='AZZ,AZT,AZS,AZR,AZP,AZO,AZN,AZL,AZI,AZG,AZD,AZB,AZA,AYY,AYW,AYU,
AYT,AYS,AYR,AYQ,AYP,AYO,AYN,AYM'
SET
@ENTITY2='AYL,AYK,AYI,AYG,AYD,AYC,AYA,AXX,AXV,AXU,AXT,AXS,AXR,AXP,AXN,AXM,
AXL,AXK,AXJ,AXG,AXF,AXE,AXD,AXC,AXB,AXA,AWZ,AWR,AWP,AWN,AWM,AWK,AWE,A
WD,AWB,AWA,AVX,AVW,AVV,AVU,AVP,AVO,AVN,AVL,AVK,AVI,AVG,AVB,AVA,AUZ,AUY,
AUX,AUW,AUV,AUU,AUT,AUS,AUR,AUQ,AUP,AUO,AUN,AUM,AUL,AUK,AUJ,AUI,AUH,A
UG,AUF,AUE,AUD,AUC,AUA,ATZ,ATY,ATX,ATW,ATV,ATU,ATT,ATS,ATR,ATQ,ATP,ATO,AT
N,ATM,ATL,ATK,ATJ,ATI,ATH,ATG,ATF,ATE,ATD,ATC,ATB,ATA,ASZ,ASY,ASX,ASW,ASV,AS
U,AST,ASR,ASQ,ASP'

EXEC REC_Entity @ENTITY1


EXEC REC_Entity @ENTITY2

You will see that the two stored procedure calls are executed successfully and the
two comma separated entities lists are split completely without showing any error
as shown in the result below:
To be more dynamic, it is better to tune the MAXRECURSION value in the previous
stored procedure with the maximum number of entities that can be passed to that
stored procedure. For example, if you are dealing with countries that will not have
more than 500 entities, you can replace the previous query hint with OPTION
(MAXRECURSION 500), setting 500 as the maximum allowed recursion level for that
query, and at the same time protecting your system from the infinite loop issue, by
terminating the query if it exceeds that number of recursions.

If your query requires recursion level greater than the maximum allowed
MAXRECURSION value, which is 32,767, you can achieve that by breaking the
MAXRECURSION limitation by setting the MAXRECURSION value to 0 using the
OPTION (MAXRECURSION 0) query hint. In this way, you will take the risk of falling in
the infinite loop problem if the CTE recursion query is not written well.
SQL | Query Processing
Query Processing includes translations on high level Queries into low level
expressions that can be used at physical level of file system, query optimization and
actual execution of query to get the actual result.
Block Diagram of Query Processing is as:

Detailed Diagram is drawn as:


It is done in the following steps:

 Step-1:
Parser: During parse call, the database performs the following checks- Syntax
check, Semantic check and Shared pool check, after converting the query into
relational algebra.

Parser performs the following checks as (refer detailed diagram):

1. Syntax check – concludes SQL syntactic validity. Example:

SELECT * FORM employee

Here error of wrong spelling of FROM is given by this check.

2. Semantic check – determines whether the statement is meaningful or


not. Example: query contains a tablename which does not exist is
checked by this check.
3. Shared Pool check – Every query possess a hash code during its
execution. So, this check determines existence of written hash code in
shared pool if code exists in shared pool then database will not take
additional steps for optimization and execution.
Hard Parse and Soft Parse –
If there is a fresh query and its hash code does not exist in shared pool then
that query has to pass through from the additional steps known as hard
parsing otherwise if hash code exists then query does not passes through
additional steps. It just passes directly to execution engine (refer detailed
diagram). This is known as soft parsing.
Hard Parse includes following steps – Optimizer and Row source generation.
 Step-2:
Optimizer: During optimization stage, database must perform a hard parse
atleast for one unique DML statement and perform optimization during this
parse. This database never optimizes DDL unless it includes a DML
component such as subquery that require optimization.
It is a process in which multiple query execution plan for satisfying a query
are examined and most efficient query plan is satisfied for execution.
Database catalog stores the execution plans and then optimizer passes the
lowest cost plan for execution.

Row Source Generation –


The Row Source Generation is a software that receives a optimal execution
plan from the optimizer and produces an iterative execution plan that is
usable by the rest of the database. the iterative plan is the binary program
that when executes by the sql engine produces the result set.
 Step-3:
Execution Engine: Finally runs the query and display the required result.
QUESTIONS
What is SQL?

SQL stands for Structured Query Language. It is a language used to interact with
the database, i.e to create a database, to create a table in the database, to retrieve
data or update a table in the database etc. SQL is an ANSI(American National
Standards Institute) standard. Using SQL, we can do many things, for example – we
can execute queries, we can insert records in a table, we can update records, we
can create a database, we can create a table, we can delete a table etc.

What is a Database?

A Database is defined as a structured form of data which is stored in a computer or


data in an organised manner and can be accessed in various ways. It is also the
collection of schemas, tables, queries, views etc. Database helps us in easily storing,
accessing and manipulation of data held in a computer. The Database Management
System allows a user to interact with the database.

Does SQL support programming language features ?

It is true that SQL is a language but it does not support programming as it is not a
programming language, it is a command language. We do not have conditional
statements in SQL like for loops or if..else, we only have commands which we can
use to query, update , delete etc. data in the database. SQL allows us to manipulate
data in a database.

What are the differences between SQL and PL/SQL?

SQL PL/SQL

SQL is a query execution or commanding language PL/SQL is a complete programming language

SQL is data oriented language PL/SQL is a procedural language

SQL is very declarative in nature PL/SQL has a procedural nature


It is used for manipulating data It is used for creating applications

We can execute one statement at a time in SQL We can execute block of statements in PL/SQL

SQL tells database, what to do? PL/SQL tells database how to do

We can embed SQL in PL/SQL We can not embed PL/SQL in SQL

What is the difference between BETWEEN and IN operators in SQL?

BETWEEN
The BETWEEN operator is used to fetch rows based on a range of values.

For example,

SELECT * FROM Students

WHERE ROLL_NO BETWEEN 20 AND 30;

This query will select all those rows from the table Students where the value of the
field ROLL_NO lies between 20 and 30.

IN
The IN operator is used to check for values contained in specific sets.
For example,

SELECT * FROM Students


WHERE ROLL_NO IN (20,21,23);

This query will select all those rows from the table Students where the value of the
field ROLL_NO is either 20 or 21 or 23.

Write an SQL query to find names of employee start with ‘A’?

The LIKE operator of SQL is used for this purpose. It is used to fetch filtered data by
searching for a particular pattern in where clause.
The Syntax for using LIKE is,
SELECT column1,column2 FROM table_name WHERE column_name LIKE pattern;

LIKE: operator name


pattern: exact value extracted from the pattern to get related data in
result set.

The required query is:

SELECT * FROM Employees WHERE EmpName like 'A%' ;

You may refer to this article on WHERE clause for more details on LIKE operator.

What is the difference between CHAR and VARCHAR2 datatype in SQL?

Both of these datatypes are used for characters but varchar2 is used for character
strings of variable length whereas char is used for character strings of fixed length.
For example, if we specify the type as char(5) then we will not be allowed to store
string of any other length in this variable but if we specify the type of this variable
as varchar2(5) then we will be allowed to store strings of variable length, we can
store a string of length 3 or 4 or 2 in this variable.

Name different types of case manipulation functions available in SQL.

There are three types of case manipulation functions available in SQL. They are,
 LOWER: The purpose of this function is to return the string in lowercase. It
takes a string as argument and returns the string by converting it into lower
case.
Syntax:

 LOWER('string')

 UPPER:The purpose of this function is to return the string in uppercase. It


takes a string as argument and returns the string by converting it into
uppercase.
Syntax:

 UPPER('string')
 INITCAP:The purpose of this function is to return the string with first letter in
uppercase and rest of the letters in lowercase.
Syntax:

INITCAP('string')

What do you mean by data definition language?

Data definition language or DDL allows executing queries like CREATE, DROP and
ALTER. That is, those queries which define the data.

What do you mean by data manipulation language?

Data manipulation Language or DML is used to access or manipulate data in the


database.
It allows us to perform below listed functions:
 Insert data or rows in database
 Delete data from database
 Retrieve or fetch data
 Update data in database.

What is the difference between primary key and unique constraints?

Primary key cannot have NULL value, the unique constraints can have NULL values.
There is only one primary key in a table, but there can be multiple unique
constrains. The primary key creates the cluster index automatically but the Unique
key does not.

What is a view in SQL?

Views in SQL are kind of virtual tables. A view also has rows and columns as they
are in a real table in the database. We can create a view by selecting fields from one
or more tables present in the database. A View can either have all the rows of a
table or specific rows based on certain condition.

The CREATE VIEW statement of SQL is used for creating Views.


Basic Syntax:

1. CREATE VIEW view_name AS

2. SELECT column1, column2.....

3. FROM table_name

4. WHERE condition;

5.

6. view_name: Name for the View


7. table_name: Name of the table
8. condition: Condition to select rows

For more details on how to create and use view, please refer to this article.

What do you mean by foreign key?

A Foreign key is a field which can uniquely identify each row in another table. And
this constraint is used to specify a field as Foreign key. That is, this field points to
primary key of another table. This usually creates a kind of link between the two
tables.

Consider the two tables as shown below:


Orders
O_ID ORDER_NO C_ID

1 2253 3

2 3325 3

3 4521 2
4 8532 1

Customers
C_ID NAME ADDRESS

1 RAMESH DELHI

2 SURESH NOIDA

3 DHARMESH GURGAON

As we can see clearly that the field C_ID in Orders table is the primary key in
Customers table, i.e. it uniquely identifies each row in the Customers table.
Therefore, it is a Foreign Key in Orders table.
Syntax:

CREATE TABLE Orders

O_ID int NOT NULL,

ORDER_NO int NOT NULL,

C_ID int,

PRIMARY KEY (O_ID),

FOREIGN KEY (C_ID) REFERENCES Customers(C_ID)

What is a join in SQL? What are the types of joins?


An SQL Join statement is used to combine data or rows from two or more tables
based on a common field between them. Different types of Joins are:
 INNER JOIN: The INNER JOIN keyword selects all rows from both the tables as
long as the condition satisfies. This keyword will create the result-set by
combining all rows from both the tables where the condition satisfies i.e value
of the common field will be same.
 LEFT JOIN:This join returns all the rows of the table on the left side of the join
and matching rows for the table on the right side of join. The rows for which
there is no matching row on right side, the result-set will contain null. LEFT
JOIN is also known as LEFT OUTER JOIN
 RIGHT JOIN:RIGHT JOIN is similar to LEFT JOIN. This join returns all the rows of
the table on the right side of the join and matching rows for the table on the
left side of join. The rows for which there is no matching row on left side, the
result-set will contain null. RIGHT JOIN is also known as RIGHT OUTER JOIN.
 FULL JOIN: FULL JOIN creates the result-set by combining result of both LEFT
JOIN and RIGHT JOIN. The result-set will contain all the rows from both the
tables. The rows for which there is no matching, the result-set will contain
NULL values.

To know about each of these joins in details, refer this.

What is an index?

A database index is a data structure that improves the speed of data retrieval
operations on a database table at the cost of additional writes and the use of more
storage space to maintain the extra copy of data. Data can be stored only in one
order on disk. To support faster access according to different values, faster search
like binary search for different values is desired. For this purpose, indexes are
created on tables. These indexes need extra space on disk, but they allow faster
search according to different frequently searched values.
SQL Interview Questions | Set 1
Que-1: Difference between blocking and deadlocking.
 Blocking:
Blocking occurs is a transaction tries to acquire an incompatible lock on a
resource that another transaction has already locked. The blocked
transaction remain blocked until the blocking transaction releases the lock.
 Deadlocking:
Deadlocking occurs when two or more transactions have a resource locked,
and each transaction requests a lock on the resource that another
transaction has already locked. Neither of the transactions here can more
forward, as each one is waiting for the other to release the lock.
Que-2: Delete duplicate data from table only first data remains constant.
Managers –

ID NAME SALARY

1 Harpreet 20000

2 Ravi 30000

3 Vinay 10000

4 Ravi 30000

5 Harpreet 20000

6 Vinay 10000
7 Rajeev 40000

8 Vinay 10000

9 Ravi 30000

10 Sanjay 50000

Query –

DELETE M1

From managers M1, managers M2

Where M2.Name = M1.Name AND M1.Id>M2.Id;

Output –

ID NAME SALARY

1 Harpreet 20000

2 Ravi 30000

3 Vinay 10000

7 Rajeev 40000
10 Sanjay 50000

Que-3: Find the Name of Employees.


Finding the name of Employees where First Name, Second Name and Last Name is
given in table. Some Name is missing such as First Name, Second Name and may
be Last Name. Here we will use COALESCE() function which will return first Non Null
values.

Employees –

ID FNAME SNAME LNAME SALARY

1 Har preet Singh 30000

2 Ashu NULL Rana 50000

3 NULL Vinay Thakur 40000

4 NULL Vinay NULL 10000

5 NULL NULL Rajveer 60000

6 Manjeet Singh NULL 60000

Query –

SELECT ID, COALESCE(FName, SName, LName) as Name

FROM employees;

Output –
Que-4: Find the Employees who hired in the Last n months.
Finding the Employees who have been hire in the last n months. Here we get desire
output by using TIMESTAMPDIFF() mysql function.

Employees –

ID FNAME LNAME GENDER SALARY HIREDATE

1 Rajveer Singh Male 30000 2017/11/05

2 Manveer Singh Male 50000 2017/11/05

3 Ashutosh Kumar Male 40000 2017/12/12

4 Ankita Sharma Female 45000 2017/12/15

5 Vijay Kumar Male 50000 2018/01/12


ID FNAME LNAME GENDER SALARY HIREDATE

6 Dilip Yadav Male 25000 2018/02/26

7 Jayvijay Singh Male 30000 2018/02/18

8 Reenu Kumari Female 40000 2017/09/19

9 Ankit Verma Male 25000 2018/04/04

10 Harpreet Singh Male 50000 2017/10/10

Query –

Select *, TIMESTAMPDIFF (month, Hiredate, current_date()) as DiffMonth

From employees

Where TIMESTAMPDIFF (month, Hiredate, current_date())

Between 1 and 5 Order by Hiredate desc;

Note – Here in query 1 and 5 are indicates 1 to n months.which show the


Employees who have hired last 1 to 5 months. In this query DiffMonth is a extra
column for our understanding which show the Nth months.
Output –
Que-5: Find the Employees who hired in the Last n days.
Finding the Employees who have been hire in the last n days. Here we get desire
output by using DATEDIFF() mysql function.

Employees –

ID FNAME LNAME GENDER SALARY HIREDATE

1 Rajveer Singh Male 30000 2017/11/05

2 Manveer Singh Male 50000 2017/11/05

3 Ashutosh Kumar Male 40000 2017/12/12

4 Ankita Sharma Female 45000 2017/12/15

5 Vijay Kumar Male 50000 2018/01/12


ID FNAME LNAME GENDER SALARY HIREDATE

6 Dilip Yadav Male 25000 2018/02/26

7 Jayvijay Singh Male 30000 2018/02/18

8 Reenu Kumari Female 40000 2017/09/19

9 Ankit Verma Male 25000 2018/04/04

10 Harpreet Singh Male 50000 2017/10/10

Query –

Select *, DATEDIFF (current_date(), Hiredate) as DiffDay

From employees

Where DATEDIFF (current_date(), Hiredate) between 1 and 100 order by Hiredate


desc;

Note – Here in query 1 and 100 are indicates 1 to n days.which show the Employees
who have hired last 1 to 100 days. In this query DiffDay is a extra column for our
understanding which show the Nth days.
Output –
Que-6: Find the Employees who hired in the Last n years.
Finding the Employees who have been hire in the last n years. Here we get desire
output by using TIMESTAMPDIFF() mysql function.

Employees –

ID FNAME LNAME GENDER SALARY HIREDATE

1 Rajveer Singh Male 30000 2010/11/05

2 Manveer Singh Male 50000 2017/11/05

3 Ashutosh Kumar Male 40000 2015/12/12

4 Ankita Sharma Female 45000 2016/12/15

5 Vijay Kumar Male 50000 2017/01/12

6 Dilip Yadav Male 25000 2011/02/26


ID FNAME LNAME GENDER SALARY HIREDATE

7 Jayvijay Singh Male 30000 2012/02/18

8 Reenu Kumari Female 40000 2013/09/19

9 Ankit Verma Male 25000 2017/04/04

10 Harpreet Singh Male 50000 2017/10/10

Query –

Select *, TIMESTAMPDIFF (year, Hiredate, current_date()) as DiffYear

From employees

Where TIMESTAMPDIFF (year, Hiredate, current_date()) between 1 and 4 order by


Hiredate desc;

Note – Here in query 1 and 4 are indicates 1 to n years.which show the Employees
who have hired last 1 to 4 years. In this query DiffYear is a extra column for our
understanding which show the Nth years.
Output –
Que-7: Select all names that start with a given letter.
Here we get desire output by using three different query.

Employees –

ID FNAME LNAME GENDER SALARY HIREDATE

1 Rajveer Singh Male 30000 2010/11/05

2 Manveer Singh Male 50000 2017/11/05

3 Ashutosh Kumar Male 40000 2015/12/12

4 Ankita Sharma Female 45000 2016/12/15

5 Vijay Kumar Male 50000 2017/01/12

6 Dilip Yadav Male 25000 2011/02/26


ID FNAME LNAME GENDER SALARY HIREDATE

7 Jayvijay Singh Male 30000 2012/02/18

8 Reenu Kumari Female 40000 2013/09/19

9 Ankit Verma Male 25000 2017/04/04

10 Harpreet Singh Male 50000 2017/10/10

Query –

Select *

From employees

Where Fname like 'A%';

Select *

From employees

Where left(FName, 1)='A';

Select *

From employees

Where substring(FName, 1, 1)='A';

Note – Here every query will give same output and the list of Employees who’s
FName start with letter A.
What is DBMS?

A Database Management System (DBMS) is a program that controls creation,


maintenance and use of a database. DBMS can be termed as File Manager that
manages data in a database rather than saving it in file systems.

2. What is RDBMS?

RDBMS stands for Relational Database Management System. RDBMS store the data
into the collection of tables, which is related by common fields between the
columns of the table. It also provides relational operators to manipulate the data
stored into the tables.

Example: SQL Server.

3. What is SQL?

SQL stands for Structured Query Language , and it is used to communicate with the
Database. This is a standard language used to perform tasks such as retrieval,
updation, insertion and deletion of data from a database.

Standard SQL Commands are Select.

4. What is a Database?

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.

Example: School Management Database, Bank Management Database.

5. What are tables and Fields?

A table is a set of data that are organized in a model with Columns and Rows.
Columns can be categorized as vertical, and Rows are horizontal. A table has
specified number of column called fields but can have any number of rows which is
called record.

Example:.

Table: Employee.
Field: Emp ID, Emp Name, Date of Birth.

Data: 201456, David, 11/15/1960.

6. What is a primary key?

A primary key is a combination of fields which uniquely specify a row. This is a


special kind of unique key, and it has implicit NOT NULL constraint. It means,
Primary key values cannot be NULL.

7. What is a unique key?

A Unique key constraint uniquely identified each record in the database. This
provides uniqueness for the column or set of columns.

A Primary key constraint has automatic unique constraint defined on it. But not, in
the case of Unique Key.

There can be many unique constraint defined per table, but only one Primary key
constraint defined per table.

8. What is a foreign key?

A foreign key is one table which can be related to the primary key of another table.
Relationship needs to be created between two tables by referencing foreign key
with the primary key of another table.

9. What is a join?

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.

10. What are the types of join and explain each?

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.

11. What is normalization?

Normalization is the process of minimizing redundancy and dependency by


organizing fields and table of a database. The main aim of Normalization is to add,
delete or modify field that can be made in a single table.

12. What is Denormalization.

DeNormalization is a technique used to access the data from higher to lower


normal forms of database. It is also process of introducing redundancy into a table
by incorporating data from the related tables.

13. What are all the different normalizations?

The normal forms can be divided into 5 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 (3NF):.

Meeting all the requirements of third normal form and it should not have multi-
valued dependencies.

14. What is a View?

A view is a virtual table which consists of a subset of data contained in a table.


Views are not virtually present, and it takes less space to store. View can have data
of one or more tables combined, and it is depending on the relationship.

15. What is an Index?

An index is performance tuning method of allowing faster retrieval of records from


the table. An index creates an entry for each value and it will be faster to retrieve
data.

16. What are all the different types of indexes?

There are three types of indexes -.

 Unique Index.

This indexing does not allow the field to have duplicate values if the column is
unique indexed. Unique index can be applied automatically when primary key is
defined.

 Clustered Index.

This type of index reorders the physical order of the table and search based on the
key values. Each table can have only one clustered index.
 NonClustered Index.

NonClustered Index does not alter the physical order of the table and maintains
logical order of data. Each table can have 999 nonclustered indexes.

17. What is a Cursor?

A database Cursor is a control which enables traversal over the rows or records in
the table. This can be viewed as a pointer to one row in a set of rows. Cursor is very
much useful for traversing such as retrieval, addition and removal of database
records.

18. What is a relationship and what are they?

Database Relationship is defined as the connection between the tables in a


database. There are various data basing relationships, and they are as follows:.

 One to One Relationship.


 One to Many Relationship.
 Many to One Relationship.
 Self-Referencing Relationship.

19. What is a query?

A DB query is a code written in order to get the information back from the
database. Query can be designed in such a way that it matched with our
expectation of the result set. Simply, a question to the Database.

20. What is subquery?

A subquery is a query within another query. The outer query is called as main
query, and inner query is called subquery. SubQuery is always executed first, and
the result of subquery is passed on to the main query.

21. What are the types of subquery?

There are two types of subquery – Correlated and Non-Correlated.

A correlated subquery cannot be considered as independent query, but it can refer


the column in a table listed in the FROM the list of the main query.
A Non-Correlated sub query can be considered as independent query and the
output of subquery are substituted in the main query.

22. What is a stored procedure?

Stored Procedure is a function consists of many SQL statement to access the


database system. Several SQL statements are consolidated into a stored procedure
and execute them whenever and wherever required.

23. What is a trigger?

A DB trigger is a code or programs that automatically execute with response to


some event on a table or view in a database. Mainly, trigger helps to maintain the
integrity of the database.

Example: When a new student is added to the student database, new records
should be created in the related tables like Exam, Score and Attendance tables.

24. What is the difference between DELETE and TRUNCATE commands?

DELETE command is used to remove rows from the table, and WHERE clause can be
used for conditional set of parameters. Commit and Rollback can be performed
after delete statement.

TRUNCATE removes all rows from the table. Truncate operation cannot be rolled
back.

25. What are local and global variables and their differences?

Local variables are the variables which can be used or exist inside the function.
They are not known to the other functions and those variables cannot be referred
or used. Variables can be created whenever that function is called.

Global variables are the variables which can be used or exist throughout the
program. Same variable declared in global cannot be used in functions. Global
variables cannot be created whenever that function is called.

26. What is a constraint?


Constraint can be used to specify the limit on the data type of table. Constraint can
be specified while creating or altering the table statement. Sample of constraint
are.

 NOT NULL.
 CHECK.
 DEFAULT.
 UNIQUE.
 PRIMARY KEY.
 FOREIGN KEY.

27. What is data Integrity?

Data Integrity defines the accuracy and consistency of data stored in a database. It
can also define integrity constraints to enforce business rules on the data when it is
entered into the application or database.

28. What is Auto Increment?

Auto increment keyword allows the user to create a unique number to be


generated when a new record is inserted into the table. AUTO INCREMENT keyword
can be used in Oracle and IDENTITY keyword can be used in SQL SERVER.

Mostly this keyword can be used whenever PRIMARY KEY is used.

29. What is the difference between Cluster and Non-Cluster Index?

Clustered index is used for easy retrieval of data from the database by altering the
way that the records are stored. Database sorts out rows by the column which is
set to be clustered index.

A nonclustered index does not alter the way it was stored but creates a complete
separate object within the table. It point back to the original table rows after
searching.

30. What is Datawarehouse?

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.
31. What is Self-Join?

Self-join is set to be query used to compare to itself. This is used to compare values
in a column with other values in the same column in the same table. ALIAS ES can
be used for the same table comparison.

32. What is Cross-Join?

Cross join defines as Cartesian product where number of rows in the first table
multiplied by number of rows in the second table. If suppose, WHERE clause is used
in cross join then the query will work like an INNER JOIN.

33. What is user defined functions?

User defined functions are the functions written to use that logic whenever
required. It is not necessary to write the same logic several times. Instead, function
can be called or executed whenever needed.

34. What are all types of user defined functions?

Three types of user defined functions are.

 Scalar Functions.
 Inline Table valued functions.
 Multi statement valued functions.

Scalar returns unit, variant defined the return clause. Other two types return table
as a return.

35. What is collation?

Collation is defined as set of rules that determine how character data can be sorted
and compared. This can be used to compare A and, other language characters and
also depends on the width of the characters.

ASCII value can be used to compare these character data.

36. What are all different types of collation sensitivity?

Following are different types of collation sensitivity -.


 Case Sensitivity – A and a and B and b.
 Accent Sensitivity.
 Kana Sensitivity – Japanese Kana characters.
 Width Sensitivity – Single byte character and double byte character.

37. Advantages and Disadvantages of Stored Procedure?

Stored procedure can be used as a modular programming – means create once,


store and call for several times whenever required. This supports faster execution
instead of executing multiple queries. This reduces network traffic and provides
better security to the data.

Disadvantage is that it can be executed only in the Database and utilizes more
memory in the database server.

38. What is Online Transaction Processing (OLTP)?

Online Transaction Processing (OLTP) manages transaction based applications


which can be used for data entry, data retrieval and data processing. OLTP makes
data management simple and efficient. Unlike OLAP systems goal of OLTP systems
is serving real-time transactions.

Example – Bank Transactions on a daily basis.

39. What is CLAUSE?

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.

40. What is recursive stored procedure?

A stored procedure which calls by itself until it reaches some boundary condition.
This recursive function or procedure helps programmers to use the same set of
code any number of times.

41. What is Union, minus and Interact commands?


UNION operator is used to combine the results of two tables, and it eliminates
duplicate rows from the tables.

MINUS operator is used to return rows from the first query but not from the
second query. Matching records of first and second query and other rows from the
first query will be displayed as a result set.

INTERSECT operator is used to return rows returned by both the queries.

42. What is an ALIAS command?

ALIAS name can be given to a table or column. This alias name can be referred in
WHERE clause to identify the table or column.

Example-.

Select st.StudentID, Ex.Result from student st, Exam as Ex where st.studentID = Ex.
StudentID

Here, st refers to alias name for student table and Ex refers to alias name for exam
table.

43. What is the difference between TRUNCATE and DROP statements?

TRUNCATE removes all the rows from the table, and it cannot be rolled back. DROP
command removes a table from the database and operation cannot be rolled back.

44. What are aggregate and scalar functions?

Aggregate functions are used to evaluate mathematical calculation and return


single values. This can be calculated from the columns in a table. Scalar functions
return a single value based on the input value.

Example -.

Aggregate – max(), count - Calculated with respect to numeric.

Scalar – UCASE(), NOW() – Calculated with respect to strings.

45. How can you create an empty table from an existing table?
Example will be -.

Select * into studentcopy from student where 1=2

Here, we are copying student table to another table with the same structure with
no rows copied.

46. How to fetch common records from two tables?

Common records result set can be achieved by -.

Select studentID from student. <strong>INTERSECT </strong> Select StudentID from


Exam

47. How to fetch alternate records from a table?

Records can be fetched for both Odd and Even row numbers -.

To display even numbers-.

Select studentId from (Select rowno, studentId from student) where


mod(rowno,2)=0

To display odd numbers-.

Select studentId from (Select rowno, studentId from student) where


mod(rowno,2)=1

from (Select rowno, studentId from student) where mod(rowno,2)=1.[/sql]

48. How to select unique records from a table?

Select unique records from a table by using DISTINCT keyword.

Select DISTINCT StudentID, StudentName from Student.

49. What is the command used to fetch first 5 characters of the string?

There are many ways to fetch first 5 characters of the string -.


Select SUBSTRING(StudentName,1,5) as studentname from student
Select RIGHT(Studentname,5) as studentname from student

50. Which operator is used in query for pattern matching?

LIKE operator is used for pattern matching, and it can be used as -.

1. % - Matches zero or more characters.


2. _(Underscore) – Matching exactly one character.

Example -.

Select * from Student where studentname like 'a%'


Select * from Student where studentname like 'ami_'
Question #1) What is SQL?
Structured Query Language is a database tool which is used to create and access
database to support software application.

Question #2) What are tables in SQL?


The table is a collection of record and its information at a single view.

Question #3) What are different types of statements supported by SQL?

There are 3 types of SQL statements


1) DDL (Data Definition Language): It is used to define the database structure such
as tables. It includes three statements such as Create, Alter, and Drop.
Some of the DDL Commands are listed below
 CREATE: It is used for creating the table.
CREATE TABLE&amp;amp;amp;nbsp;table_name

column_name1 data_type(size),

column_name2 data_type(size),

column_name3 data_type(size),

 ALTER: The ALTER table is used for modifying the existing table object in the
database.
ALTER TABLE table_name
ADD column_name datatype
OR

ALTER TABLE table_name


DROP COLUMN column_name
2) DML (Data Manipulation Language): These statements are used to manipulate
the data in records. Commonly used DML statements are Insert, Update, and
Delete.
The Select statement is used as partial DML statement that is used to select all or
relevant records in the table.

3) DCL (Data Control Language): These statements are used to set privileges such as
Grant and Revoke database access permission to the specific user.
Question #4) How do we use DISTINCT statement? What is its use?
DISTINCT statement is used with the SELECT statement. If the records contain
duplicate values then DISTINCT is used to select different values among duplicate
records.

Syntax: SELECT DISTINCT column_name(s)


FROM table_name;
Question #5) What are different Clauses used in SQL?

 WHERE Clause: This clause is used to define the condition, extract and
display only those records which fulfill the given condition
Syntax: SELECT column_name(s)
FROM table_name
WHERE condition;
 GROUP BY Clause: It is used with SELECT statement to group the result of the
executed query using the value specified in it. It matches the value with the
column name in tables and groups the end result accordingly.
Syntax: SELECT column_name(s)
FROM table_name
GROUP BY column_name;
 HAVING clause: This clause is used in association with GROUP BY clause. It is
applied to the each group of result or the entire result as single group and
much similar as WHERE clause, the only difference is you cannot use it
without GROUP BY clause
Syntax: SELECT column_name(s)
FROM table_name
GROUP BY column_name
HAVING condition;
 ORDER BY clause: This clause is to define the order of the query output
either in ascending (ASC) or in descending (DESC) order. Ascending (ASC) is
the default one but descending (DESC) is set explicitly.
Syntax: SELECT column_name(s)
FROM table_name
WHERE condition
ORDER BY column_name ASC|DESC;
 USING clause: USING clause comes in use while working with SQL Joins. It is
used to check equality based on columns when tables are joined. It can be
used instead ON clause in Joins.
Syntax: SELECT column_name(s)
FROM table_name
JOIN table_name
USING (column_name);
Question #6) Why do we use SQL constraints? Which constraints we can use while
creating database in SQL?
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 CREATE TABLE
statement or even after the table is created once with 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
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
columns to identify the particular record with a unique identity.
 FOREIGN KEY: It is used to ensure the referential integrity of data in the table
and also matches the value in one table with another using Primary Key
 CHECK: It is used to ensure whether the value in columns fulfills the specified
condition
Question #7) What are different JOINS used in SQL?

There are 4 major types of joins made to use while working on multiple tables in
SQL databases

 INNER JOIN: It is also known as SIMPLE JOIN which returns all rows from
BOTH tables when it has at least one column matched
Syntax: SELECT column_name(s)
FROM table_name1
INNER JOIN table_name2
ON column_name1=column_name2;
Example
In this example, we have a table Employee with the following data

The second Table is joining


Enter the following SQL statement

SELECT Employee.Emp_id, Joining.Joining_Date

FROM Employee

INNER JOIN Joining

ON Employee.Emp_id = Joining.Emp_id

ORDER BY Employee.Emp_id;

There will be 4 records selected. These are the results that you should see

Employee and orders tables where there is a matching customer_id value in both
the Employee and orders tables
 LEFT JOIN (LEFT OUTER JOIN): This join returns all rows from a LEFT table and
its matched
rows from a RIGHT table.
Syntax: SELECT column_name(s)
FROM table_name1
LEFT JOIN table_name2
ON column_name1=column_name2;
Example
In this example, we have a table Employee with the following data:

Second Table is joining


Enter the following SQL statement

SELECT Employee.Emp_id, Joining.Joining_Date

FROM Employee

LEFT OUTER JOIN Joining

ON Employee.Emp_id = Joining.Emp_id

ORDER BY Employee.Emp_id;

There will be 4 records selected. These are the results that you should see:

 RIGHT JOIN (RIGHT OUTER JOIN): This joins returns all rows from the RIGHT
table and its matched rows from a LEFT table.
Syntax: SELECT column_name(s)
FROM table_name1
RIGHT JOIN table_name2
ON column_name1=column_name2;
Example
In this example, we have a table Employee with the following data
The second Table is joining

Enter the following SQL statement

SELECT Employee.Emp_id, Joining.Joining_Date

FROM Employee

LEFT OUTER JOIN Joining

ON Employee.Emp_id = Joining.Emp_id

ORDER BY Employee.Emp_id;

There will be 4 records selected. These are the results that you should see

 FULL JOIN (FULL OUTER JOIN): This joins returns all when there is a match
either in the RIGHT table or in the LEFT table.
Syntax: SELECT column_name(s)
FROM table_name1
FULL OUTER JOIN table_name2
ON column_name1=column_name2;
Example
In this example, we have a table Employee with the following data:

Second Table is joining

Enter the following SQL statement:

SELECT Employee.Emp_id, Joining.Joining_Date

FROM Employee

FULL OUTER JOIN Joining

ON Employee.Emp_id = Joining.Emp_id

ORDER BY Employee.Emp_id;

There will be 8 records selected. These are the results that you should see
Question #8) What are transaction and its controls?
A transaction can be defined as the sequence task that is performed on databases
in a logical manner to gain certain results. Operations performed like Creating,
updating, deleting records in the database comes from transactions.

In simple word, we can say that a transaction means a group of SQL queries
executed on database records.

There are 4 transaction controls such as

 COMMIT: It is used to save all changes made through the transaction


 ROLLBACK: It is used to roll back the transaction such as all changes made by
the transaction are reverted back and database remains as before
 SET TRANSACTION: Set the name of transaction
 SAVEPOINT: It is used to set the point from where the transaction is to be
rolled back
Question #9) What are properties of the transaction?
Properties of transaction are known as ACID properties, such as
 Atomicity: Ensures the completeness of all transactions performed. Checks
whether every transaction is completed successfully if not then transaction is
aborted at the failure point and the previous transaction is rolled back to its
initial state as changes undone
 Consistency: Ensures that all changes made through successful transaction
are reflected properly on database
 Isolation: Ensures that all transactions are performed independently and
changes made by one transaction are not reflected on other
 Durability: Ensures that the changes made in database with committed
transactions persist as it is even after system failure
Question #10) How many Aggregate Functions are available there in SQL?
SQL Aggregate Functions calculates values from multiple columns in a table and
returns a single value.

There are 7 aggregate functions we use in SQL

 AVG(): Returns the average value from specified columns


 COUNT(): Returns number of table rows
 MAX(): Returns 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
Question #11) What are Scalar Functions in SQL?
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 upper case


 LCASE(): Converts the specified field in lower case
 MID(): Extracts and returns character from text field
 FORMAT(): Specifies the display format
 LEN(): Specifies the length of text field
 ROUND(): Rounds up the decimal field value to a number
Question #12) What are triggers?
Triggers in SQL is kind of stored procedures used to create a response to a specific
action performed on the table such as Insert, Update or Delete. You can invoke
triggers explicitly on the table in the database.

Action and Event are two main components of SQL triggers when certain actions
are performed the event occurs in response to that action.

Syntax: CREATE TRIGGER name {BEFORE|AFTER} (event [OR..]}


ON table_name [FOR [EACH] {ROW|STATEMENT}]
EXECUTE PROCEDURE functionname {arguments}
Question #13) What is View in SQL?
A View can be defined as a virtual table that contains rows and columns with fields
from one or more table.

Syntax: CREATE VIEW view_name AS


SELECT column_name(s)
FROM table_name
WHERE condition
Question #14) How we can update the view?
SQL CREATE and REPLACE can be used for updating the view.

Following query syntax is to be executed to update the created view

Syntax: CREATE OR REPLACE VIEW view_name AS


SELECT column_name(s)
FROM table_name
WHERE condition
Question #15) Explain the working of SQL Privileges?
SQL GRANT and REVOKE commands are used to implement privileges in SQL
multiple user environments. The administrator of the database can grant or revoke
privileges to or from users of database object like SELECT, INSERT, UPDATE, DELETE,
ALL etc.

GRANT Command: This command is used provide database access to user apart
from an administrator.
Syntax: GRANT privilege_name
ON object_name
TO {user_name|PUBLIC|role_name}
[WITH GRANT OPTION];
In above syntax WITH GRANT OPTIONS indicates that the user can grant the access
to another user too.

REVOKE Command: This command is used provide database deny or remove


access to database objects.
Syntax: REVOKE privilege_name
ON object_name
FROM {user_name|PUBLIC|role_name};
Question #16) How many types of Privileges are available in SQL?
There are two types of privileges used in SQL, such as
 System Privilege: System privileges deal with an object of a particular type
and specifies the right to perform one or more actions on it which include
Admin allows a user to perform 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.
Question #17) What is SQL Injection?
SQL Injection is a type of database attack technique where malicious SQL
statements are inserted into an entry field of database such that once it is executed
the database is opened for an attacker. This technique is usually used for attacking
Data-Driven Applications to have an access to sensitive data and perform
administrative tasks on databases.

For Example: SELECT column_name(s) FROM table_name WHERE condition;


Question #18) What is SQL Sandbox in SQL Server?
SQL Sandbox is the safe place in SQL Server Environment where untrusted scripts
are executed. There are 3 types of SQL sandbox, such as

 Safe Access Sandbox: Here a user can perform SQL operations such as
creating stored procedures, triggers etc. but cannot have access to the
memory and cannot create files.
 External Access Sandbox: User can have access to files without having a right
to manipulate the memory allocation.
 Unsafe Access Sandbox: This contains untrusted codes where a user can
have access to memory.
Question #19) What is the difference between SQL and PL/SQL?
SQL is a structured query language to create and access databases whereas PL/SQL
comes with procedural concepts of programming languages.

Question #20) What is the difference between SQL and MySQL?


SQL is a structured query language that is used for manipulating and accessing the
relational database, on the other hand, MySQL itself is a relational database that
uses SQL as the standard database language.

Question #21) What is the use of NVL function?


NVL function is used to convert the null value to its actual value.
Question #22) What is the Cartesian product of table?
The output of Cross Join is called as a Cartesian product. It returns rows combining
each row from the first table with each row of the second table. For Example, if we
join two tables having 15 and 20 columns the Cartesian product of two tables will
be 15×20=300 Rows.

Question #23) What do you mean by Subquery?


Query within another query is called as Subquery. A subquery is called inner query
which returns output that is to be used by another query.

Question #24) How many row comparison operators are used while working with a
subquery?
There are 3-row comparison operators which are used in subqueries such as IN,
ANY and ALL.

Question #25) What is the difference between clustered and non-clustered


indexes?
 One table can have only one clustered index but multiple nonclustered
indexes.
 Clustered indexes can be read rapidly rather than non-clustered indexes.
 Clustered indexes store data physically in the table or view and non-
clustered indexes do not store data in table as it has separate structure from
data row
Question #26) What is the difference between DELETE and TRUNCATE?
 The basic difference in both is DELETE is DML command and TRUNCATE is
DDL
 DELETE is used to delete a specific row from the table whereas TRUNCATE is
used to remove all rows from the table
 We can use DELETE with WHERE clause but cannot use TRUNCATE with it
Question #27) What is the difference between DROP and TRUNCATE?
TRUNCATE removes all rows from the table which cannot be retrieved back, DROP
removes the entire table from the database and it cannot be retrieved back.

Question #28) How to write a query to show the details of a student from Students
table whose
name starts with K?
SELECT * FROM Student WHERE Student_Name like ‘%K’;
Here ‘like’ operator is used for pattern matching.
Question #29) What is the difference between Nested Subquery and Correlated
Subquery?
Subquery within another subquery is called as Nested Subquery. If the output of a
subquery is depending on column values of the parent query table then the query
is called Correlated Subquery.

SELECT adminid(SELEC Firstname+’ ‘+Lastname FROM Employee WHERE


empid=emp. adminid)AS EmpAdminId FROM Employee
This query gets details of an employee from Employee table.

Question #30) What is Normalization? How many Normalization forms are there?
Normalization is used to organize the data in such manner that data redundancy
will never occur in the database and avoid insert, update and delete anomalies.

There are 5 forms of Normalization


 First Normal Form (1NF): It removes all duplicate columns from the table.
Creates table for related data and identifies unique column values
 First Normal Form (2NF): Follows 1NF and creates and places data subsets in
an individual table and defines relationship between tables using primary
key
 Third Normal Form (3NF): Follows 2NF and removes those columns which are
not related through primary key
 Fourth Normal Form (4NF): Follows 3NF and do not define multi-valued
dependencies. 4NF also known as BCNF

Question #31) What is Relationship? How many types of Relationship are there?
The relationship can be defined as the connection between more than one tables in
the database.

There are 4 types of relationships


 One to One Relationship
 Many to One Relationship
 Many to Many Relationship
 One to Many Relationship

Question #32) What do you mean by Stored Procedures? How do we use it?
A stored procedure is a collection of SQL statements which can be used as a
function to access the database. We can create these stored procedures previously
before using it and can execute these them wherever we require and also apply
some conditional logic to it. Stored procedures are also used to reduce network
traffic and improve the performance.

Syntax: CREATE Procedure Procedure_Name


(
//Parameters
)
AS
BEGIN
SQL statements in stored procedures to update/retrieve records
END

Question #33) State some properties of Relational databases?


 In relational databases, each column should have a unique name
 Sequence of rows and columns in relational databases are insignificant
 All values are atomic and each row is unique

Question #34) What are Nested Triggers?


Triggers may implement data modification logic by using INSERT, UPDATE, and
DELETE statement. These triggers that contain data modification logic and find
other triggers for data modification are called Nested Triggers.

Question #35) What is Cursor?


A cursor is a database object which is used to manipulate data in a row-to-row
manner.

Cursor follows steps as given below

 Declare Cursor
 Open Cursor
 Retrieve row from the Cursor
 Process the row
 Close Cursor
 Deallocate Cursor
Question #36) What is Collation?
Collation is set of rules that check how the data is sorted by comparing it. Such as
Character data is stored using correct character sequence along with case
sensitivity, type, and accent.

Question #37) What do we need to check in Database Testing?


Generally, in Database Testing following thing is need to be tested

 Database Connectivity
 Constraint Check
 Required Application Field and its size
 Data Retrieval and Processing With DML operations
 Stored Procedures
 Functional flow

Question #38) What is Database White Box Testing?


Database White Box Testing involves
 Database Consistency and ACID properties
 Database triggers and logical views
 Decision Coverage, Condition Coverage, and Statement Coverage
 Database Tables, Data Model, and Database Schema
 Referential integrity rules

Question #39) What is Database Black Box Testing?


Database Black Box Testing involves
 Data Mapping
 Data stored and retrieved
 Use of Black Box techniques such as Equivalence Partitioning and Boundary
Value Analysis (BVA)
Question #40) What are Indexes in SQL?
The index can be defined as the way to retrieve the data more quickly. We can
define indexes using CREATE statements.

Syntax: CREATE INDEX index_name


ON table_name (column_name)
Further, we can also create Unique Index using following syntax;

Syntax: CREATE UNIQUE INDEX index_name


ON table_name (column_name)
******************

UPDATE: Added more questions for your practice.


Q#41. What does SQL stand for?
Ans. SQL stands for Structured Query Language.
Q#42. How to select all records from the table?
Ans. To select all the records from the table we need to use the following syntax:
Select * from table_name;

Q#43. Define join and name different types of joins?


Ans. Join keyword is used to fetch data from related two or more tables. It returns
rows where there is at least one match in both the tables included in the join. Read
more here.
Type of joins are:
1. Right Join
2. Outer Join
3. Full Join
4. Cross Join
5. Self Join.
Q#44. What is the syntax to add a record to a table?
Ans. To add a record in a table INSERT syntax is used.
Ex: INSERT into table_name VALUES (value1, value2..);

Q#45. How do you add a column to a table?


Ans. To add another column in the table following command has been used.
ALTER TABLE table_name ADD (column_name);

Q#46. Define SQL Delete statement.


Ans. Delete is used to delete a row or rows from a table based on the specified
condition.
The basic syntax is as follows:
DELETE FROM table_name

WHERE <Condition>

Q#47. Define COMMIT?


Ans. COMMIT saves all changes made by DML statements.
Q#48. What is a primary key?
Ans. A Primary key is a column whose values uniquely identify every row in a table.
Primary key values can never be reused.
Q#49. What are foreign keys?
Ans. When a one table’s primary key field is added to related tables in order to
create the common field which relates the two tables, it called a foreign key in other
tables.
Foreign Key constraints enforce referential integrity.
Q#50. What is CHECK Constraint?
Ans. A CHECK constraint is used to limit the values or type of data that can be
stored in a column. They are used to enforce domain integrity.
Q#51. Is it possible for a table to have more than one foreign key?
Ans. Yes, a table can have many foreign keys and only one primary key.
Q#52. What are the possible values for the BOOLEAN data field?
Ans. For a BOOLEAN data field, two values are possible: -1(true) and 0(false).
Q#53. What is a stored procedure?
Ans. A stored procedure is a set of SQL queries which can take input and send back
output.
Q#54. What is identity in SQL?
Ans. An identity column in the SQL automatically generates numeric values. We can
define a start and increment value of identity column.
Q#55. What is Normalization?
Ans. The process of table design to minimize the data redundancy is called
normalization. We need to divide a database into two or more table and define
relationships between them.
Q#56. What is Trigger?
Ans. Trigger allows us to execute a batch of SQL code when a table event occurs
(Insert, update or delete command executed against a specific table)
Q#57. How to select random rows from a table?
Ans. Using SAMPLE clause we can select random rows.
Example:
SELECT * FROM table_name SAMPLE(10);

Q#58. Which TCP/IP port does SQL Server run?


Ans. By default SQL Server runs on port 1433.
Q#59. Write a SQL SELECT query that only returns each name only once from a
table?
Ans. To get the each name only once, we need to use the DISTINCT keyword.
SELECT DISTINCT name FROM table_name;
Q#60. Explain DML and DDL?
Ans. DML stands for Data Manipulation Language. INSERT, UPDATE and DELETE are
DML statements.
DDL stands for Data Definition Language. CREATE , ALTER, DROP, RENAME are DDL
statements.

Q#61. Can we rename a column in the output of SQL query?


Ans. Yes using the following syntax we can do this.
SELECT column_name AS new_name FROM table_name;

Q#62. Give the order of SQL SELECT?


Ans. Order of SQL SELECT clauses is: SELECT, FROM, WHERE, GROUP BY, HAVING,
ORDER BY. Only the SELECT and FROM clause are mandatory.
Q#63. Suppose a Student column has two columns, Name and Marks. How to get
name and marks of top three students.
Ans. SELECT Name, Marks FROM Student s1 where 3 <= (SELECT COUNT(*) FROM
Students s2 WHERE s1.marks = s2.marks)
Q#64. What is SQL comments?
Ans. SQL comments can be put by two consecutive hyphens (–).
Q#65. Difference between TRUNCATE, DELETE and DROP commands?
Ans. DELETE removes some or all rows from a table based on the condition. It can
be rolled back.
TRUNCATE removes ALL rows from a table by de-allocating the memory pages. The
operation cannot be rolled back

DROP command removes a table from the database completely.

Q#66. What are the properties of a transaction?


Ans. Generally, these properties are referred as ACID properties. They are:
1. Atomicity
2. Consistency
3. Isolation
4. Durability.
Q#67. What do you mean by ROWID?
Ans. It’s an 18 character long pseudo column attached with each row of a table.
Q#68. Define UNION, MINUS, UNION ALL, INTERSECT ?
Ans. 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.

INTERSECT – returns all distinct rows selected by both queries.

Q#69. What is a transaction?


Ans. A transaction is a sequence of code that runs against a database. It takes the
database from one consistent state to another.
Q#70. What is the difference between UNIQUE and PRIMARY KEY constraints?
Ans. A table can have only one PRIMARY KEY whereas there can be any number of
UNIQUE keys.
The primary key cannot contain Null values whereas Unique key can contain Null
values.

Q#71. What is a composite primary key?


Ans. Primary key created on more than one column is called composite primary
key.
Q#72. What is an Index?
Ans. An Index is a special structure associated with a table speed up the
performance of queries. The index can be created on one or more columns of a
table.
Q#73. What is the Subquery?
Ans. A Subquery is a subset of select statements whose return values are used in
filtering conditions of the main query.
Q#74. What do you mean by query optimization?
Ans. Query optimization is a process in which database system compares different
query strategies and select the query with the least cost.
Q#75. What is Collation?
Ans. Set of rules that define how data is stored, how case sensitivity and Kana
character can be treated etc.
Q#76. What is Referential Integrity?
Ans. Set of rules that restrict the values of one or more columns of the tables based
on the values of the primary key or unique key of the referenced table.
Q#77. What is Case Function?
Ans. Case facilitates if-then-else type of logic in SQL. It evaluates a list of conditions
and returns one of multiple possible result expressions.
Q#78. Define a temp table?
Ans. A temp table is a temporary storage structure to store the data temporarily.
Q#79. How can we avoid duplicating records in a query?
Ans. By using DISTINCT keyword duplicating records in a query can be avoided.
Q#80. Explain the difference between Rename and Alias?
Ans. Rename is a permanent name given to a table or column whereas Alias is a
temporary name given to a table or column.
Q#81. What is a View?
Ans. A view is a virtual table which contains data from one or more tables. Views
restrict data access of table by selecting only required values and make complex
queries easy.
Q#82. What are the advantages of Views?
Ans. Advantages of Views:
1. Views restrict access to the data because the view can display selective
columns from the table.
2. Views can be used to make simple queries to retrieve the results of
complicated queries. For example, views can be used to query information
from multiple tables without the user knowing.
Q#83. List the various privileges that a user can grant to another user?
Ans. SELECT, CONNECT, RESOURCES.
Q#84. What is schema?
Ans. A schema is a collection of database objects of a User.
Q#85. What is Table?
Ans. A table is the basic unit of data storage in the database management system.
Table data is stored in rows and columns.
Q#86. Do View contain Data?
Ans. No, Views are virtual structure.
Q#87. Can a View based on another View?
Ans. Yes, A View is based on another View.
Q#88. What is the difference between Having clause and Where clause?
Ans. Both specify a search condition but Having clause is used only with the SELECT
statement and typically used with GROUP BY clause.
If GROUP BY clause is not used then Having behaves like WHERE clause only.
Q#89. What is the difference between Local and Global temporary table?
Ans. If defined in inside a compound statement a local temporary table exists only
for the duration of that statement but a global temporary table exists permanently
in the DB but its rows disappear when the connection is closed.
Q#90. What is CTE?
Ans. A CTE or common table expression is an expression which contains temporary
result set which is defined in a SQL statement.
1. Compare SQL & PL/SQL

Criteria SQL PL/SQL

What it is Single query or Full programming language


command execution

What it Data source for Application language to build,


comprises reports, web pages format and display report, web
pages

Characteristic Declarative in nature Procedural in nature

Used for Manipulating data Creating applications

2. What is BCP? When is it used?

It is a tool used to duplicate enormous quantity of information from tables and


views. It does not facsimile the structures same as foundation to target.
BULK INSERT command helps to bring in a data folder into a record, table or view in
a user-specific arrangement.

Learn for free ! Subscribe to our youtube Channel.


3. When is the UPDATE_STATISTICS command used?

This command is used, ones the processing of large data is done.


When we delete a large number of files, alteration or reproduction takes place in
the tables, to be concerned of these changes we need to restructure the indexes
This is done UPDATE_STATISTICS.

4. Explain the steps needed to Create the scheduled job?

Steps to create a Scheduled Job :

1. Connect to the database of SQL server in SQL Server Management Studio.


On the SQL Server Agent, we will find a Jobs folder.
2. Right click on jobs and choose Add New.
3. A New Job window will come into view. Give an associated name for the
same.
4. Click next on the “Steps” in the left list of options. An SQL job can have
multiple steps either in the form of SQL declaration or a stored practice
call.
5. Click on the “Schedules” in the left list of options. An SQL job can comprise
of one or supplementary schedules. It is basically the instance at which
SQL job will jog itself. We can spell out returning schedules also.

Become SQL Certified in 16 hrs.


GET CERTIFIED

5. What are the different types of constraints? Explain primary key, foreign key,
unique key & not null constraints?

6. When are we going to use truncate and delete?

1. TRUNCATE is a DDL command, whereas DELETE is a DML command.


2. We can’t execute a trigger in case of TRUNCATE whilst with DELETE, we can
accomplish a trigger.
3. TRUNCATE is quicker than DELETE, for the reason that when we use
DELETE to delete the data, at that time it store the whole statistics in the
rollback gap on or after where we can get the data back after removal. In
case of TRUNCATE, it will not store data in rollback gap and will
unswervingly rub it out. TRUNCATE do not recover the deleted data.
4. We can use any condition in WHERE clause using DELETE but it is not
possible with TRUNCATE.5.If a table is referenced by any foreign key
constraints, then TRUNCATE won’t work.

Go through this SQL tutorial to learn more about SQL commands.

7. Explain correlated query work?

It’s most important to be attentive of the arrange of operations in an interrelated


subquery.
First, a row is processed in the outer doubt.
Then, for that exacting row, the subquery is executed – as a result for each row
processed by the outer query, the subquery will also be processed. In correlated
subquery, each time a line is worked for Emp1, the subquery will also make a
decision on the exacting row’s value for Emp1.Salary and run. And the outer query
will move on to the next row, and the subquery will execute for that row’s value of
Emp1.Salary.
It will persist in anticipation of the “WHERE (1) = (… )” state is pleased.

Read this insightful tutorial to learn usage of SQL Clauses.

8. When is the Explicit Cursor Used ?

If the developer needs to perform the row by row operations for the result set
containing more than one row, then he unambiguously declares a pointer with a
name. They are managed by OPEN, FETCH and CLOSE.%FOUND, %NOFOUND,
%ROWCOUNT and %ISOPEN characteristics are used in all types of pointers.
9. Find What is Wrong in this Query?
SELECT subject_code, AVG (marks) FROM students WHERE AVG(marks) > 75 GROUP
BY subject_code; The WHERE clause cannot be used to restrict groups. Instead, the
HAVING clause should be used.

SELECT subject_code, AVG (marks)

FROM students

HAVING AVG(marks) > 75

GROUP BY subject_code;

10. Write the Syntax for STUFF function in an SQL server?

STUFF (String1, Position, Length, String2)

String1 - String to be overwritten

Position - Starting location for overwriting

Length - Length of substitute string

String2- String to overwrite.

11. Name some commands that can be used to manipulate text in T-SQL code. For
example, a command that obtains only a portion of the text or replace a text string,
etc.

 CHARINDEX( findTextData, textData, [startingPosition] ) – Returns the


starting position of the specified expression in a character string. The
starting position is optional.
 LEFT( character_expression , integer_expression ) – Returns the left part of
a character string with the specified number of characters.
 LEN( textData ) – Returns integer value of the length of the string,
excluding trailing blanks.
 LOWER ( character_expression ) – Returns a character expression after
converting uppercase character data to lowercase.
 LTRIM( textData) – Removes leading blanks. PATINDEX( findTextData,
textData ) – Returns integer value of the starting position of text found in
the string.
 REPLACE( textData, findTextData, replaceWithTextData ) – Replaces
occurrences of text found in the string with a new value.
 REPLICATE( character_expression , integer_expression ) – Repeats a
character expression for a specified number of times.
 REVERSE( character_expression ) – Returns the reverse of a character
expression.
 RTRIM( textData) – Removes trailing blanks. SPACE( numberOfSpaces ) –
Repeats space value specified number of times.
 STUFF( textData, start , length , insertTextData ) – Deletes a specified
length of characters and inserts another set of characters at a specified
starting point.
 SUBSTRING( textData, startPosition, length ) – Returns portion of the
string.
 UPPER( character_expression ) – Returns a character expression with
lowercase character data converted to uppercase.

12. What are the three ways that Dynamic SQL can be executed?

 Writing a query with parameters.


 Using EXEC.
 Using sp_executesql.

Get a clear understanding of SQL in this riveting blog.

13. In what version of SQL Server were synonyms released? How do synonyms
work and explain its use cases? Synonyms were released with SQL Server 2005.

 Synonyms enable the reference of another object (View, Table, Stored


Procedure or Function) potentially on a different server, database or
schema in your environment. In simple words, the original object that is
referenced in the whole code is using a completely different underlying
object, but no coding changes are necessary. Think of this as an alias as a
means to simplify migrations and application testing without the need to
make any dependent coding changes.
 Synonyms can offer a great deal of value when converting underlying
database objects without breaking front end or middle tier code. This
could be useful during a re-architecture or upgrade project.

Become Master of SQL by going through this SQL training course.


14. If you are a SQL Developer, how can you delete duplicate records in a table with
no primary key?

Use the SET ROWCOUNT command. For instance,


if you have 2 duplicate rows, you would SET ROWCOUNT 1, execute DELETE
command and then SET ROWCOUNT 0.

15. Is it possible to import data directly from T-SQL commands without using SQL
Server Integration Services? If so, what are the commands?

Yes, six commands are available to import data directly in the T-SQL language.
These commands include :

 BCP : The bulk copy (bcp) command of Microsoft SQL Server provides you
with the ability to insert large numbers of records directly from the
command line. In addition to being a great tool for command-line
aficionados, bcp is a powerful tool for those seeking to insert data into a
SQL Server database from within a batch file or other programmatic
method.
 Bulk Insert : The BULK INSERT statement was introduced in SQL Server 7
and allows you to interact with bcp (bulk copy program) via a script.
 OpenRowSet : The OPENROWSET function can be referenced in the FROM
clause of a query as if it were a table name. The OPENROWSET function
can also be referenced as the target table of an INSERT, UPDATE, or
DELETE statement, subject to the capabilities of the OLE DB provider.
Although the query might return multiple result sets, OPENROWSET
returns only the first one.
 OPENDATASOURCE : Provides ad hoc connection information as part of a
four-part object name without using a linked server name.
 OPENQUERY : Executes the specified pass-through query on the specified
linked server. This server is an OLE DB data source. OPENQUERY can be
referenced in the FROM clause of a query as if it were a table name.
 Linked Servers : Configure a linked server to enable the SQL Server
Database Engine to execute commands against OLE DB data sources
outside of the instance of SQL Server. Typically linked servers are
configured to enable the Database Engine to execute a Transact-SQL
statement that includes tables in another instance of SQL Server, or
another database product such as Oracle.

16. What is the native system stored procedure to execute a command against all
databases?
 The sp_MSforeachdb system stored procedure accepts
the @Command parameter which can be exetecuted against all
databases. The ‘?’ is used as a placeholder for the database name to
execute the same command.
 The alternative is to use a cursor to process specific commands against
each database.

17. How can a SQL Developer prevent T-SQL code from running on a production
SQL Server?

Use IF logic with the @@SERVERNAME function compared against a string with a
RETURN command before any other logic.

18. How do you maintain database integrity where deletions from one table will
automatically cause deletions in another table?

You can create a trigger that will automatically delete elements in the second table
when elements from the first table are removed.

19. What port does SQL server run on?

1433 is the standard port for SQL server.

Go through this SQL Video to get clear understanding of SQL.

20. What is the SQL CASE statement used for? Explain with an example?

It allows you to embed an if-else like clause in the SELECT clause.

SELECT Employee_Name, CASE Location

WHEN 'alex' THEN Bonus * 2

WHEN 'robin' THEN Bonus *, 5

ELSE Bonus

END

"New Bonus"

FROM Intellipaat_employee;
Read this blog to learn why SQL Optimization has always been a important aspect
of database management.

21. What are the risks of storing a hibernate-managed object in cache? How do you
overcome the problems?

The primary problem here is that the object will outlive the session it came from.
Lazily loaded properties won’t get loaded if needed later. To overcome the problem,
perform cache on the object’s id and class and then retrieve the object in the
current session context.

22. When is the use of UPDATE_STATISTICS command ?

Updating statistics ensures that queries compile with up-to-date statistics.


However, updating statistics causes queries to recompile. We recommend not
updating statistics too often because there is a performance tradeoff between
improving query plans and the time it takes to recompile queries. The specific
tradeoffs depend on your application. UPDATE STATISTICS can use tempdb to sort
the sample of rows for building statistics.

Syntax

UPDATE STATISTICS table_or_indexed_view_name

{ index_or_statistics__name }

| ( { index_or_statistics_name } [ ,...n ] )

[ WITH

FULLSCAN

| SAMPLE number { PERCENT | ROWS }

| RESAMPLE
[ ON PARTITIONS ( { | } [, …n] ) ]

| [ ,...n ]

[ [ , ] [ ALL | COLUMNS | INDEX ]

[ [ , ] NORECOMPUTE ]

[ [ , ] INCREMENTAL = { ON | OFF } ]

];

::=

[ STATS_STREAM = stats_stream ]

[ ROWCOUNT = numeric_constant ]

[ PAGECOUNT = numeric_contant ]

23. What is SQL Profiler?

Microsoft SQL Server Profiler is a graphical user interface to SQL Trace for
monitoring an instance of the Database Engine or Analysis Services. You can
capture and save data about each event to a file or table to analyze later.

Use SQL Profiler to monitor only the events in which you are interested.

If traces are becoming too large, you can filter them based on the information you
want, so that only a subset of the event data is collected. Monitoring too many
events adds overhead to the server and the monitoring process and can cause the
trace file or trace table to grow very large, especially when the monitoring process
takes place over a long period of time.

24. What command using Query Analyzer will give you the version of SQL server
and operating system?

SELECT SERVERPROPERTY (‘productversion’), SERVERPROPERTY (‘productlevel’),


SERVERPROPERTY (‘edition’).
25. What does it mean to have QUOTED_IDENTIFIER ON? What are the implications
of having it OFF?

When SET QUOTED_IDENTIFIER is ON, identifiers can be delimited by double


quotation marks, and literals must be delimited by single quotation marks.
When SET QUOTED_IDENTIFIER is OFF, identifiers cannot be quoted and must
follow all Transact-SQL rules for identifiers.

26. What is the STUFF function and how does it differ from the REPLACE function in
SQL?

Stuff function : – This function is used to replace string from the given start position,
passed as 2nd argument with string passed as last argument. In Stuff function, 3rd
argument defines the number of characters which are going to be replaced.
Syntax :-

STUFF ( character_expression , start , length , replaceWith_expression )

For example :-

Select Stuff ('Intellipaat', 3, 3, 'abc')

This query will return the string "Iabcllipaat". In this example, Stuff function
replaces the string "Intellipaat" onwards the 3rd position('nte') with 'abc'.

Replace Function :– Replace function is used to replace all occurrence of a specified


with the string passed as last argument.
Syntax :-

REPLACE ( string_expression , string_pattern , string_replacement )

For example :-

Select Replace ('Abcabcabc', 'bc', 'xy')

This query will return the string Axyaxyaxy. In this example, Replace function
replaces the occurrence of each 'bc' string with 'xy'.

Learn SQL from Experts! Enrol Today


27. How to get @@ERROR and @@ROWCOUNT at the same time?

If @@Rowcount is checked after Error checking statement then it will have 0 as the
value of @@Recordcount as it would have been reset. And if @@Recordcount is
checked before the error-checking statement then @@Error would get reset. To get
@@error and @@rowcount at the same time do both in same statement and store
them in local variable.

SELECT @RC = @@ROWCOUNT, @ER = @@ERROR

28. What is de-normalization in SQL database administration? Give examples

De-normalization is used to optimize the readability and performance of the


database by adding redundant data. It covers the inefficiencies in the relational
database software.
De-normalization logical data design tend to improve the query responses by
creating rules in the database which are called as constraints.
Examples include the following :

 Materialized views for implementation purpose such as :


 Storing the count of “many” objects in one-to-many relationship.
 Linking attribute of one relation with other relations.
 To improve the performance and scalability of web applications.

29. Can you explain about buffer cash and log Cache in SQL Server?

 Buffer Cache : Buffer cache is a memory pool in which data pages are
read. The ideal performance of the buffer cache is indicated as: 95%
indicates that pages that were found in the memory are 95% of time.
Another 5% is need physical disk access.
If the value falls below 90%, it is the indication of more physical memory
requirement on the server.
 Log Caches : Log cache is a memory pool used to read and write the log
pages. A set of cache pages are available in each log cache. The
synchronization is reduced between log and data buffers by managing log
cache separately from the buffer cache.

30. Describe how to use Linked Server.


MS SQL Server supports the connection to different OLE DB on an ad hoc basis.
This persistent connection is referred as Linked Server.
Following are the steps to use Linked Server for any OLE DB. You can refer this to
use an MS-Excel workbook.

1. Open SQL Server Management Studio in SQL Server.


2. Expand Server Objects in Object Explorer.
3. Right-click on Linked Servers. Click on New Linked Server.
4. Select General page in the left pane and
1. Type any name for the linked server in the first text box.
2. Select the Other Data Source option.
3. Click on Microsoft Jet 4.0 OLE DB Provider from the
Provider list.
4. Type the Excel as the name of the OLE DB data source.
5. Type the full path and file name of the Excel file in Data
Source box.
6. Type the Excel version no. (7.0, 8.0 etc) in the Provider
String. Use Excel 8.0 for Excel 2000, Excel 2002 or Excel 97.
7. To create a linked server click on OK.

31. How to find second highest salary of an Employee?

There are many ways to find second highest salary of Employees in SQ. You can
either use SQL Join or Subquery to solve this problem.
Here is SQL query using Subquery :

Select MAX(Salary) from Intellipaat_emplyee WHERE Salary NOT IN ( select


MAX(Salary) from Intellipaat_employee.

32. Explain how to send email from SQL database.

SQL Server has a feature for sending mails. Stored procedures can also be used for
sending mail on demand. With SQL Server 2005, MAPI client is not needed for
sending mails.
The following is the process for sending emails from database.

 Make sure that the SQL Server Mail account is configured correctly and
enable Database Mail.
 Write a script to send an e-mail. The following is the script.
 USE [YourDB]

 EXEC msdb.dbo.sp_send_dbmail

 @recipients = 'xyz@intellipaat.com;
abc@intellipaat.com;pqr@intellipaat.com’

 @body = ' A warm wish for your future endeavor',

 @subject = 'This mail was sent using Database Mail' ;

GO

33. How to make remote connection in database?

The following is the process to make a remote connection in database :

1. Use SQL Server Surface Area Configuration Tool for enabling the remote
connection in database.
2. Click on Surface Area Configuration for Services and Connections.
3. Click on SQLEXPRESS/Database Engine/RemoteConnections.
4. Select the radio button: Local and Remote Connections and select ‘Using
TCP/IP only’ under Local and Remote Connections.
5. Click on OK button / Apply button

34. What is the purpose of OPENXML clause SQL server stored procedure?

OPENXML parses the XML data in SQL Server in an efficient manner. It’s primary
ability is to insert XML data to the RDB. It is also possible to query the data by using
OpenXML. The path of the XML element needs to be specified by using ‘xpath’.
The following is a procedure for retrieving xml data:

DECLARE @index int

DECLARE @xmlString varchar(8000)

SET @xmlString ='

abc
9343463943/PhoneNo>

xyz

9342673212

'

EXEC sp_xml_preparedocument @index OUTPUT, @xmlString

SELECT * FROM OPENXML (@index, 'Persons/Person') WITH (id varchar(10), Name


varchar(100) 'Name' , PhoneNo varchar(50) 'PhoneNo')

EXEC sp_xml_removedocument @index

The above code snippet results the following:

15201 abc 9343463943

15202 xyz 9342673212

35. How to store pdf file in SQL Server?

Create a column as type ‘blob’ in a table. Read the content of the file and save in
‘blob’ type column in a table.
Or
Store them in a folder and establish the pointer to link them in the database.

36. Explain the use of keyword WITH ENCRYPTION. Create a Store Procedure with
Encryption.

It is a way to convert the original text of the stored procedure into encrypted form.
The stored procedure gets obfuscated and the output of this is not visible to

CREATE PROCEDURE Abc

WITH ENCRYPTION

AS
<< SELECT statement>>

GO

WITH ENCRYPTION indicates that SQL Server will convert the original text of CREATE
PROCEDURE statement to an encrypted format. Users that do not have no access to
system tables or database files cannot retrieve the encrypted text. However, the
text will be available to privileged users.

Example:

CREATE PROCEDURE salary_sum


WITH ENCRYTION
AS
SELECT sum(salary)
FROM employee
WHERE emp_dept LIKE Develop

37. What is lock escalation?

Lock escalation is used to convert row locks and page locks into table locks thereby
“escalating” the smaller or finer locks. This increases the system performance as
each lock is nothing but a memory structure. Too many locks would mean more
consumption of memory. Hence, escalation is used.
Lock escalation from SQL Server 7.0 onwards is dynamically managed by SQL
Server. It is the process of converting a lot of low level locks into higher level locks.

38. What is Failover clustering overview?

Failover clustering is mainly used for data availability. Typically, in a failover cluster,
there are two machines.

 One machine provides the basic services and the second is available to run
the service when the primary system fails.
 The primary system is monitored periodically to check if it works. This
monitoring may be performed by the failover computer or an
independent system also called as cluster controller. In an event of failure
of primary computer, the failover system takes control.

39. What is Builtin/Administrator?


The Builtin/Administrator account is basically used during some setup to join some
machine in the domain. It should be disabled immediately thereafter. For any
disaster recovery, the account will be automatically enabled. It should not be used
for normal operations.

40. What XML support does the SQL server extend?

SQL Server (server-side) supports 3 major elements :

1. Creation of XML fragments: This is done from the relational data using
FOR XML to the select query.
2. Ability to shred xml data to be stored in the database.
3. Finally, storing the xml data.

Client-side XML support in SQL Server is in the form of SQLXML. It can be described
in terms of :

 XML Views : providing bidirectional mapping between XML schemas and


relational tables.
 Creation of XML Templates : allows creation of dynamic sections in XML.

SQL server can return XML document using FOR XML clause. XML documents can
be added to SQL Server database and you can use the OPENXML clause to display
the data from the document as a relational result set. SQL Server 2000 supports
XPath queries.
SQL Interview Questions

Q1. What is the difference between DELETE and TRUNCATE statements?

TE vs TRUNCATE

DELETE TRUNCATE

Delete command is used to delete a row Truncate is used to delete all the rows
in a table. from a table.

You can rollback data after using delete


You cannot rollback data.
statement.

It is a DML command. It is a DDL command.

It is slower than truncate statement. It is faster.

Q2. What are the different subsets of SQL?

 DDL (Data Definition Language) – It allows you to perform various operations


on the database such as CREATE, ALTER and DELETE objects.
 DML ( Data Manipulation Language) – It allows you to access and manipulate
data. It helps you to insert, update, delete and retrieve data from the
database.
 DCL ( Data Control Language) – It allows you to control access to the
database. Example – Grant, Revoke access permissions.
Q3. What do you mean by DBMS? What are its different types?

A database is a structured collection of data.

A Database Management System (DBMS) is a software application that interacts

with the user, applications and the database itself to capture and analyze data.

A DBMS allows a user to interact with the database. The data stored in the

database can be modified, retrieved and deleted and can be of any type like strings,

numbers, images etc.

There are two types of DBMS:

 Relational Database Management System: The data is stored in relations


(tables). Example – MySQL.
 Non-Relational Database Management System: There is no concept of
relations, tuples and attributes. Example – Mongo

Q4. What do you mean by table and field in SQL?

A table refers to a collection of data in an organised manner in form of rows and

columns. A field refers to the number of columns in a table. For example:

Table: StudentInformation

Field: Stu Id, Stu Name, Stu Marks


Q5. What are joins in SQL?

A JOIN clause is used to combine rows from two or more tables, based on a related

column between them. It is used to merge two tables or retrieve data from there.

There are 4 joins in SQL namely:

 Inner Join
 Right Join
 Left Join
 Full Join

Q6. What is the difference between CHAR and VARCHAR2 datatype in SQL?

Both Char and Varchar2 are used for characters datatype but varchar2 is used for

character strings of variable length whereas Char is used for strings of fixed length.

For example, char(10) can only store 10 characters and will not be able to store a

string of any other length whereas varchar2(10) can store any length i.e 6,8,2 in this

variable.

Q7. What is a Primary key?

 A Primary key is a column (or collection of


columns) or a set of columns that uniquely identifies each row in the table.
 Uniquely identifies a single row in the table
 Null values not allowed

Example- In the Student table, Stu_ID is the primary key.


Q8. What are Constraints?

Constraints are used to specify the limit on the data type of the table. It can be

specified while creating or altering the table statement. The sample of constraints

are:

 NOT NULL
 CHECK
 DEFAULT
 UNIQUE
 PRIMARY KEY
 FOREIGN KEY

Q9. What is the difference between SQL and MySQL?

SQL is a standard language which stands for Structured Query Language based on

the English language whereas MySQL is a database management system. SQL is the

core of relational database which is used for accessing and managing database,

MySQL is an RDMS (Relational Database Management System) such as SQL Server,

Informix etc.

Q10. What is a Unique key?

 Uniquely identifies a single row in the table.


 Multiple values allowed per table.
 Null values allowed.

Apart from this SQL Interview Questions blog, if you want to get trained from

professionals on this technology, you can opt for a structured training from

edureka! Click below to know more.

Have a Ridiculously Committed Mentor at work?NOMINATE THEM FOR AN AWARD


Q11. What is a Foreign key?

 Foreign key maintains referential integrity by enforcing a link between the


data in two tables.
 The foreign key in the child table references the primary key in the parent
table.
 The foreign key constraint prevents actions that would destroy links between
the child and parent tables.

Q12. What do you mean by data integrity?

Data Integrity defines the accuracy as well as the consistency of the data stored in a

database. It also defines integrity constraints to enforce business rules on the data

when it is entered into an application or a database.

Q13. What is the difference between clustered and non clustered index in SQL?

The differences between the clustered and non clustered index in SQL are :

1. Clustered index is used for easy retrieval of data from the database and its
faster whereas reading from non clustered index is relatively slower.
2. Clustered index alters the way records are stored in a database as it sorts out
rows by the column which is set to be clustered index whereas in a non
clustered index, it does not alter the way it was stored but it creates a
separate object within a table which points back to the original table rows
after searching.
3. One table can only have one clustered index whereas it can have many non
clustered index.

Q14. Write a SQL query to display the current date?

In SQL, there is a built-in function called GetDate() which helps to return the current

timestamp/date.
Q15. List the different type of joins?

There are various types of joins which are used to retrieve data between the tables.

There are four types of joins, namely:

Inner

join: Inner Join in MySQL is the most common type of join. It is used to return all the

rows from multiple tables where the join condition is satisfied.

Left Join: Left Join in MySQL is used to return all the rows from the left table but

only the matching rows from the right table where the join condition is fulfilled.

Right Join: Right Join in MySQL is used to return all the rows from the right table but

only the matching rows from the left table where the join condition is fulfilled.

Full Join: Full join returns all the records when there is a match in any of the tables.

Therefore, it returns all the rows from the left-hand side table and all the rows from

the right-hand side table.


Q16. What do you mean by Denormalization?

Denormalization refers to a technique which is used to access data from higher to

lower forms of a database. It helps the database managers to increase the

performance of the entire infrastructure as it introduces redundancy into a table. It

adds the redundant data into a table by incorporating database queries

that combine data from various tables into a single table.

Q17. What are Entities and Relationships?

Entities: A person, place, or thing in the real world about which data can be stored

in a database. Tables store data that represents one type of entity. For example – A

bank database has a customer table to store customer information. Customer table

stores this information as a set of attributes (columns within the table) for each

customer.

Relationships: Relation or links between entities that have something to do with

each other. For example – The customer name is related to the customer account

number and contact information, which might be in the same table. There can also

be relationships between separate tables (for example, customer to accounts).

Q18. What is an Index?

An index refers to a performance tuning method of allowing faster retrieval of

records from the table. An index creates an entry for each value and hence it will be

faster to retrieve data.

Q19. Explain different types of index.

There are three types of index namely:


Unique Index:

This index does not allow the field to have duplicate values if the column is unique

indexed. If a primary key is defined, a unique index can be applied automatically.

Clustered Index:

This index reorders the physical order of the table and searches based on the basis

of key values. Each table can only have one clustered index.

Non-Clustered Index:

Non-Clustered Index does not alter the physical order of the table and maintains a

logical order of the data. Each table can have many nonclustered indexes.

Q20. What is Normalization and what are the advantages of it?

Normalization is the process of organizing data to avoid duplication and

redundancy. Some of the advantages are:

 Better Database organization


 More Tables with smaller rows
 Efficient data access
 Greater Flexibility for Queries
 Quickly find the information
 Easier to implement Security
 Allows easy modification
 Reduction of redundant and duplicate data
 More Compact Database
 Ensure Consistent data after modification

Apart from this SQL Interview Questions Blog, if you want to get trained from

professionals on this technology, you can opt for a structured training from

edureka! Click below to know more.


Learn from Industry Experts

Q21. What is the difference between DROP and TRUNCATE commands?

DROP command removes a table and it cannot be rolled back from the database

whereas TRUNCATE command removes all the rows from the table.

Q22. Explain different types of Normalization.

There are many successive levels of normalization. These are called normal

forms. Each consecutive normal form depends on the previous one.The first three

normal forms are usually adequate.

 First Normal Form (1NF) – No repeating groups within rows


 Second Normal Form (2NF) – Every non-key (supporting) column value is
dependent on the whole primary key.
 Third Normal Form (3NF) – Dependent solely on the primary key and no
other non-key (supporting) column value.

Q23. What is ACID property in a database?

ACID stands for Atomicity, Consistency, Isolation, Durability. It is used to ensure that

the data transactions are processed reliably in a database system.

Atomicity: Atomicity refers to the transactions that are completely done or failed

where transaction refers to a single logical operation of a data. It means if one part

of any transaction fails, the entire transaction fails and the database state is left

unchanged.

Consistency: Consistency ensures that the data must meet all the validation rules.

In simple words, you can say that your transaction never leaves the database

without completing its state.


Isolation: The main goal of isolation is concurrency control.

Durability: Durability means that if a transaction has been committed, it will occur

whatever may come in between such as power loss, crash or any sort of error.

Q24. What do you mean by “Trigger” in SQL?

Trigger in SQL is are a special type of stored procedures that are defined to execute

automatically in place or after data modifications. It allows you to execute a batch

of code when an insert, update or any other query is executed against a specific

table.

Q25. What are the different operators available in SQL?

There are three operators available in SQL, namely:

1. Arithmetic Operators
2. Logical Operators
3. Comparison Operators

Apart from this SQL Interview Questions blog, if you want to get trained from

professionals on this technology, you can opt for a structured training from

edureka! Click below to know more.

Q26. Are NULL values same as that of zero or a blank space?

A NULL value is not at all same as that of zero or a blank space. NULL value

represents a value which is unavailable, unknown, assigned or not applicable

whereas a zero is a number and blank space is a character.


Q27. What is the difference between cross join and natural join?

The cross join produces the cross product or Cartesian product of two tables

whereas the natural join is based on all the columns having the same name and

data types in both the tables.

Q28. What is subquery in SQL?

A subquery is a query inside another query where a query is defined to retrieve

data or information back from the database. In a subquery, the outer query is

called as the main query whereas the inner query is called subquery. Subqueries

are always executed first and the result of the subquery is passed on to the main

query. It can be nested inside a SELECT, UPDATE or any other query. A subquery

can also use any comparison operators such as >,< or =.

Q29. What are the different types of a subquery?

There are two types of subquery namely, Correlated and Non-Correlated.

Correlated subquery: These are queries which select the data from a table

referenced in the outer query. It is not considered as an independent query as it

refers to another table and refers the column in a table.

Non-Correlated subquery: This query is an independent query where the output of

subquery is substituted in the main query.

Q30. List the ways to get the count of records in a table?

To count the number of records in a table, you can use the below commands:

SELECT * FROM table1


SELECT COUNT(*) FROM table1

SELECT rows FROM sysindexes WHERE id = OBJECT_ID(table1) AND indid < 2

Apart from this SQL Interview Questions Blog, if you want to get trained from

professionals on this technology, you can opt for a structured training from

edureka! Click below to know more.

Be MySQL Certified Now!

Q31. Write a SQL query to find the names of employees that begin with ‘A’?

To display name of the employees that begin with ‘A’, type in the below command:

SELECT * FROM Table_name WHERE EmpName like 'A%'

Q32. Write a SQL query to get the third highest salary of an employee from
employee_table?

SELECT TOP 1 salary

FROM(

SELECT TOP 3 salary

FROM employee_table

ORDER BY salary DESC) AS emp

ORDER BY salary ASC;

Q33. What is the need for group functions in SQL?


Group functions work on the set of rows and returns one result per group. Some of

the commonly used group functions are: AVG, COUNT, MAX, MIN, SUM, VARIANCE.

Q34 . What is a Relationship and what are they?

Relation or links are between entities that have something to do with each other.

Relationships are defined as the connection between the tables in a database.

There are various relationships, namely:

 One to One Relationship.


 One to Many Relationship.
 Many to One Relationship.
 Self-Referencing Relationship.

Q35. How can you insert NULL values in a column while inserting the data?

NULL values can be inserted in the following ways:

 Implicitly by omitting column from column list.


 Explicitly by specifying NULL keyword in the VALUES clause

Q36. What is the main difference between ‘BETWEEN’ and ‘IN’ condition operators?

BETWEEN operator is used to display rows based on a range of values in a row

whereas the IN condition operator is used to check for values contained in a

specific set of values.

Example of BETWEEN:

SELECT * FROM Students where ROLL_NO BETWEEN 10 AND 50;

Example of IN:
SELECT * FROM students where ROLL_NO IN (8,15,25);

Q37. Why are SQL functions used?

SQL functions are used for the following purposes:

 To perform some calculations on the data

 To modify individual data items

 To manipulate the output

 To format dates and numbers

 To convert the data types

Q38. What is the need of MERGE statement?

This statement allows conditional update or insertion of data into a table. It

performs an UPDATE if a row exists, or an INSERT if the row does not exist.

Q39. What do you mean by recursive stored procedure?

Recursive stored procedure refers to a stored procedure which calls by itself until it

reaches some boundary condition. This recursive function or procedure helps the

programmers to use the same set of code n number of times.

Q40. What is CLAUSE in SQL?

SQL clause helps to limit the result set by providing a condition to the query. A

clause helps to filter the rows from the entire set of records.

For example – WHERE, HAVING clause.


Apart from this SQL Interview Questions Blog, if you want to get trained from

professionals on this technology, you can opt for a structured training from

edureka! Click below to know more.

Learn From professionals!

Q41. What is the difference between ‘HAVING’ CLAUSE and a ‘WHERE’ CLAUSE?

HAVING clause can be used only with SELECT statement. It is usually used in a

GROUP BY clause and whenever GROUP BY is not used, HAVING behaves like a

WHERE clause.

Having Clause is only used with the GROUP BY function in a query whereas WHERE

Clause is applied to each row before they are a part of the GROUP BY function in a

query.

Q42. List the ways in which Dynamic SQL can be executed?

Following are the ways in which dynamic SQL can be executed:

 Write a query with parameters.

 Using EXEC.

 Using sp_executesql.

Q43. What are the various levels of constraints?

Constraints are the representation of a column to enforce data entity and

consistency. There are two levels of a constraint, namely:

 column level constraint


 table level constraint
Q44. How can you fetch common records from two tables?

You can fetch common records from two tables using INTERSECT. For example:

Select studentID from student. <strong>INTERSECT </strong> Select StudentID


1
from Exam

Q45. List some case manipulation functions in SQL?

There are three case manipulation functions in SQL, namely:

 LOWER: This function returns the string in lowercase. It takes a string as an


argument and returns it by converting it into lower case. Syntax:

LOWER(‘string’)

 UPPER: This function returns the string in uppercase. It takes a string as an


argument and returns it by converting it into uppercase. Syntax:

UPPER(‘string’)

 INITCAP: This function returns the string with the first letter in uppercase and
rest of the letters in lowercase. Syntax:

INITCAP(‘string’)

Apart from this SQL Interview Questions blog, if you want to get trained from

professionals on this technology, you can opt for a structured training from

edureka! Click below to know more.

Q46. What are the different set operators available in SQL?

Some of the available set operators are – Union, Intersect or Minus operators.
Q47. What is an ALIAS command?

ALIAS name can be given to any table or a column. This alias name can be referred

in WHERE clause to identify a particular table or a column.

For example-

Select emp.empID, dept.Result from employee emp, department as dept where


emp.empID=dept.empID

In the above example, emp refers to alias name for employee table and dept refers

to alias name for department table.

Q48. What are aggregate and scalar functions?

Aggregate functions are used to evaluate mathematical calculation and returns a

single value. These calculations are done from the columns in a table. For example-

max(),count() are calculated with respect to numeric.

Scalar functions return a single value based on the input value. For example –

UCASE(), NOW() are calculated with respect to string.

Q49. How can you fetch alternate records from a table?

You can fetch alternate records i.e both odd and even row numbers. For example-

To display even numbers, use the following command:

Select studentId from (Select rowno, studentId from student) where

mod(rowno,2)=0

Now, to display odd numbers:


Select studentId from (Select rowno, studentId from student) where
mod(rowno,2)=1

Q50. Name the operator which is used in the query for pattern matching?

LIKE operator is used for pattern matching, and it can be used as -.

1. % – It matches zero or more characters.

For example- select * from students where studentname like ‘a%’

_ (Underscore) – it matches exactly one character.

For example- select * from student where studentname like ‘abc_’

Apart from this SQL Interview Questions Blog, if you want to get trained from

professionals on this technology, you can opt for a structured training from

edureka! Click below to know more.

Learn MySQL From Experts

Q51. How can you select unique records from a table?

You can select unique records from a table by using the DISTINCT keyword.

Select DISTINCT studentID from Student

Using this command, it will print unique student id from the table Student.

Q52. How can you fetch first 5 characters of the string?

There are a lot of ways to fetch characters from a string. For example:

Select SUBSTRING(StudentName,1,5) as studentname from student


Q53. What is the main difference between SQL and PL/SQL?

SQL is a query language that allows you to issue a single query or execute a single

insert/update/delete whereas PL/SQL is Oracle’s “Procedural Language” SQL, which

allows you to write a full program (loops, variables, etc.) to accomplish multiple

operations such as selects/inserts/updates/deletes.

Q54. What is a View?

A view is a virtual table which consists of a subset of data contained in a table. Since

views are not present, it takes less space to store. View can have data of one or

more tables combined and it depends on the relationship.

Q55. What are Views used for?

A view refers to a logical snapshot based on a table or another view. It is used for

the following reasons:

 Restricting access to data.


 Making complex queries simple.
 Ensuring data independence.
 Providing different views of same data.

Q56. What is a Stored Procedure?

A Stored Procedure is a function which consists of many SQL statements to access

the database system. Several SQL statements are consolidated into a stored

procedure and execute them whenever and wherever required which saves time

and avoid writing code again and again.


Q57. List some advantages and disadvantages of Stored Procedure?

Advantages:

A Stored Procedure can be used as a modular programming which means create

once, store and call for several times whenever it is required. This supports faster

execution. It also reduces network traffic and provides better security to the data.

Disadvantage:

The only disadvantage of Stored Procedure is that it can be executed only in the

database and utilizes more memory in the database server.

Q58. List all the types of user-defined functions?

There are three types of user-defined functions, namely:

 Scalar Functions
 Inline Table-valued functions
 Multi-statement valued functions

Scalar returns the unit, variant defined the return clause. Other two types of

defined functions return table.

Q59. What do you mean by Collation?

Collation is defined as a set of rules that determine how data can be sorted as well

as compared. Character data is sorted using the rules that define the correct

character sequence along with options for specifying case-sensitivity, character

width etc.

Q60. What are the different types of Collation Sensitivity?

Following are the different types of collation sensitivity:


 Case Sensitivity: A and a and B and b.
 Kana Sensitivity: Japanese Kana characters.
 Width Sensitivity: Single byte character and double-byte character.
 Accent Sensitivity.

Apart from this SQL Interview Questions Blog, if you want to get trained from

professionals on this technology, you can opt for a structured training from

edureka! Click below to know more.

Get Certified Now!

Q61. What are Local and Global variables?

Local variables:

These variables can be used or exist only inside the function. These variables are

not used or referred by any other function.

Global variables:

These variables are the variables which can be accessed throughout the program.

Global variables cannot be created whenever that function is called.

Q62. What is Auto Increment in SQL?

Auto increment keyword allows the user to create a unique number to get

generated whenever a new record is inserted into the table.

This keyword is usually required whenever PRIMARY KEY is used.

AUTO INCREMENT keyword can be used in Oracle and IDENTITY keyword can be

used in SQL SERVER.


Q63. What is a Datawarehouse?

Datawarehouse refers to a central repository of data where the data is assembled

from multiple sources of information. Those data are consolidated, transformed

and made available for the mining as well as online processing. Warehouse data

also have a subset of data called Data Marts.

Q64. What are the different authentication modes in SQL Server? How can it be
changed?

Windows mode and Mixed Mode – SQL and Windows. You can go to the below

steps to change authentication mode in SQL Server:

 Click Start> Programs> Microsoft SQL Server and click SQL Enterprise
Manager to run SQL Enterprise Manager from the Microsoft SQL Server
program group.

 Then select the server from the Tools menu.

 Select SQL Server Configuration Properties, and choose the Security page.

Q65. What are STUFF and REPLACE function?

STUFF Function: This function is used to overwrite existing character or inserts a


string into another string. Syntax:

STUFF(string_expression,start, length, replacement_characters)

where,
string_expression: it is the string that will have characters substituted

start: This refers to the starting position


length: It refers to the number of characters in the string which are substituted.

replacement_string: They are the new characters which are injected in the string.
REPLACE function: This function is used to replace the existing characters of all the
occurrences. Syntax:

REPLACE (string_expression, search_string, replacement_string)

Here every search_string in the string_expression will be replaced with the


replacement_string.

So this brings us to the end of the SQL interview questions blog. I hope this set of
SQL Interview Questions will help you ace your job interview. All the best for your
interview!

Apart from this SQL Interview Questions Blog, if you want to get trained from
professionals on this technology, you can opt for a structured training from
edureka! Click below to know more.
Basic & Advanced SQL Interview
Questions And Answers:
Congratulations! You got the interview! In this post, we have put together both
basic and advanced SQL Interview Questions and Answers. This post contains SQL
Interview Questions for Experienced as well as Freshers.

I have segregated this “SQL Server Interview Questions” post into two types.

1. Common SQL Interview Questions


2. Practical SQL Interview Questions.

I don’t want to take much time of yours but I couldn’t move further without
mentioning about this inevitable job interview question which every hiring manager
asks you in any interview i.e., Tell Me About Yourself. Answering this questions is
very easy if you follow the link. It contains sample answers for both freshers and
experienced. Now, Let’s move on to the actual post.

General SQL Interview Questions:

1. What is a Database?
A database is a collection of information in an organized form for faster and better
access, storage and manipulation. It can also be defined as a collection of tables,
schema, views and other database objects.

2. What is Database Testing?


It is AKA back-end testing or data testing.
Database testing involves in verifying the integrity of data in the front end with the
data present in the back end. It validates the schema, database tables, columns,
indexes, stored procedures, triggers, data duplication, orphan records, junk
records. It involves in updating records in a database and verifying the same on the
front end.
3. What is the difference between GUI Testing and Database Testing?

 GUI Testing is AKA User Interface Testing or Front-end testing


Database Testing is AKA back-end testing or data testing.
 GUI Testing deals with all the testable items that are open to the user to
interaction such as Menus, Forms etc.
Database Testing deals with all the testable items that are generally hidden
from the user.
 The tester who is performing GUI Testing doesn’t need to know Structured
Query Language
The tester who is performing Database Testing needs to know Structured
Query Language
 GUI Testing includes invalidating the text boxes, check boxes, buttons, drop-
downs, forms etc., majorly the look and feel of the overall application
Database Testing involves in verifying the integrity of data in the front end
with the data present in the back end. It validates the schema, database
tables, columns, indexes, stored procedures, triggers, data duplication,
orphan records, junk records. It involves in updating records in a database
and verifying the same on the front end.

4. What is a Table in a Database?


A table is a database object used to store records in a field in the form of columns
and rows that holds data.

5. What is a Field in a Database?


A field in a Database table is a space allocated to store a particular record within a
table.

6. What is a Record in a Database?


A record (also called a row of data) is an ordered set of related data in a table.

7. What is a column in a Table?


A column is a vertical entity in a table that contains all information associated with a
specific field in a table.
8. What is DBMS?
Database Management System is a collection of programs that enables a user to
store, retrieve, update and delete information from a database.

9. What is RDBMS?
RDBMS stands for Relational Database Management System. RDBMS is a database
management system (DBMS) that is based on the relational model. Data from
relational database can be accessed using Structured Query Language (SQL)

10. What are the popular Database Management Systems in the IT Industry?
Oracle, MySQL, Microsoft SQL Server, PostgreSQL, Sybase, MongoDB, DB2, and
Microsoft Access etc.,

11. What is SQL?


SQL Overview: SQL stands for Structured Query Language. It is an American
National Standard Institute (ANSI) standard. It is a standard language for accessing
and manipulating databases. Using SQL, some of the action we could do are to
create databases, tables, stored procedures (SP’s), execute queries, retrieve, insert,
update, delete data against a database.

12. What are the different types of SQL commands?


SQL commands are segregated into following types:

 DDL – Data Definition Language


 DML – Data Manipulation Language
 DQL – Data Query Language
 DCL – Data Control Language
 TCL – Transaction Control Language

View Complete Post


13. What are the different DDL commands in SQL?
DDL commands are used to define or alter the structure of the database.

 CREATE: To create databases and database objects


 ALTER: To alter existing database objects
 DROP: To drop databases and databases objects
 TRUNCATE: To remove all records from a table but not its database structure
 RENAME: To rename database objects

14. What are the different DML commands in SQL?


DML commands are used for managing data present in the database.

 SELECT: To select specific data from a database


 INSERT: To insert new records into a table
 UPDATE: To update existing records
 DELETE: To delete existing records from a table

15. What are the different DCL commands in SQL?


DCL commands are used to create roles, grant permission and control access to the
database objects.

 GRANT: To provide user access


 DENY: To deny permissions to users
 REVOKE: To remove user access

16. What are the different TCL commands in SQL?


TCL commands are used to manage the changes made by DML statements.

 COMMIT: To write and store the changes to the database


 ROLLBACK: To restore the database since the last commit

17. What is an Index?


An index is used to speed up the performance of queries. It makes faster retrieval
of data from the table. The index can be created on one column or a group of
columns.

18. What is a View?


A view is like a subset of a table which is stored logically in a database. A view is a
virtual table. It contains rows and columns similar to a real table. The fields in the
view are fields from one or more real tables. Views do not contain data of their
own. They are used to restrict access to the database or to hide data complexity.
CREATE VIEW view_name AS SELECT column_name1, column_name2 FROM
1
table_name WHERE CONDITION;

19. What are the advantages of Views?


Some of the advantages of Views are

1. Views occupy no space


2. Views are used to simply retrieve the results of complicated queries that
need to be executed often.
3. Views are used to restrict access to the database or to hide data complexity.

20. What is a Subquery ?


A Subquery is a SQL query within another query. It is a subset of a Select statement
whose return values are used in filtering the conditions of the main query.

21. What is a temp table?


Ans. A temp table is a temporary storage structure to store the data temporarily.

22. How to avoid duplicate records in a query?


The SQL SELECT DISTINCT query is used to return only unique values. It eliminates
all the duplicated values.
View Detailed Post

23. What is the difference between Rename and Alias?


‘Rename’ is a permanent name given to a table or column
‘Alias’ is a temporary name given to a table or column.

24. What is a Join?


Join is a query, which retrieves related columns or rows from multiple tables.
25. What are the different types of joins?
Types of Joins are as follows:

 INNER JOIN
 LEFT JOIN
 RIGHT JOIN
 OUTER JOIN

View Complete Post


26. What is the difference between an inner and outer join?
An inner join returns rows when there is at least some matching data between two
(or more) tables that are being compared.
An outer join returns rows from both tables that include the records that are
unmatched from one or both the tables.

27. What are SQL constraints?


SQL constraints are the set of rules that enforced some restriction while inserting,
deleting or updating of data in the databases.

28. What are the constraints available in SQL?


Some of the constraints in SQL are – Primary Key, Foreign Key, Unique Key, SQL Not
Null, Default, Check and Index constraint.

29. What is a Unique constraint?


A unique constraint is used to ensure that there are no duplication values in the
field/column.

30. What is a Primary Key?


A PRIMARY KEY constraint uniquely identifies each record in a database table. All
columns participating in a primary key constraint must not contain NULL values.

31. Can a table contain multiple PRIMARY KEY’s?

The short answer is no, a table is not allowed to contain multiple primary keys but it
allows to have one composite primary key consisting of two or more columns.
32. What is a Composite PRIMARY KEY?
Composite PRIMARY KEY is a primary key created on more than one column
(combination of multiple fields) in a table.

33. What is a FOREIGN KEY?


A FOREIGN KEY is a key used to link two tables together. A FOREIGN KEY in a table is
linked with the PRIMARY KEY of another table.

34. Can a table contain multiple FOREIGN KEY’s?


A table can have many FOREIGN KEY’s.

35. What is the difference between UNIQUE and PRIMARY KEY constraints?
There should be only one PRIMARY KEY in a table whereas there can be any
number of UNIQUE Keys.
PRIMARY KEY doesn’t allow NULL values whereas Unique key allows NULL values.

36. What is a NULL value?


A field with a NULL value is a field with no value. A NULLvalue is different from a
zero value or a field that contains spaces. A field with a NULL value is one that has
been left blank during record creation. Assume, there is a field in a table is optional
and it is possible to insert a record without adding a value to the optional field then
the field will be saved with a NULL value.

37. What is the difference between NULL value, Zero, and Blank space?
As I mentioned earlier, Null value is field with no value which is different from zero
value and blank space.
Null value is a field with no value.
Zero is a number
Blank space is the value we provide. The ASCII value of space is CHAR(32).

38. How to Test for NULL Values?


A field with a NULL value is a field with no value. NULLvalue cannot be compared
with other NULL values. Hence, It is not possible to test for NULL values with
comparison operators, such as =, <, or <>. For this, we have to use the IS
NULL and IS NOT NULL operators.
1 SELECT column_names FROM table_name WHERE column_name IS NULL;

1 SELECT column_names FROM table_name WHERE column_name IS NOT NULL;

39. What is SQL NOT NULL constraint?


NOT NULL constraint is used to ensure that the value in the filed cannot be a NULL

40. What is a CHECK constraint?


A CHECK constraint is used to limit the value that is accepted by one or more
columns.

E.g. ‘Age’ field should contain only the value greater than 18.

CREATE TABLE EMP_DETAILS(EmpID int NOT NULL, NAME VARCHAR (30) NOT
1
NULL, Age INT CHECK (AGE &gt; 18), PRIMARY KEY (EmpID));

41. What is a DEFAULT constraint?


DEFAULT constraint is used to include a default value in a column when no value is
supplied at the time of inserting a record.
42. What is Normalization?
Normalization is the process of table design to minimize the data redundancy.
There are different types of Noramalization forms in SQL.

 First Normal Form


 Second Normal Form
 Third Normal Form
 Boyce and Codd Normal Form

43. What is Stored procedure?


A Stored Procedure is a collection of SQL statements that have been created and
stored in the database to perform a particular task. The stored procedure accepts
input parameters and processes them and returns a single value such as a number
or text value or a result set (set of rows).

44. What is a Trigger?


A Trigger is a SQL procedure that initiates an action in response to an event (Insert,
Delete or Update) occurs. When a new Employee is added to an Employee_Details
table, new records will be created in the relevant tables such as Employee_Payroll,
Employee_Time_Sheet etc.,

45. Explain SQL Data Types?


In SQL Server, each column in a database table has a name and a data type. We
need to decide what type of data to store inside each and every column of a table
while creating a SQL table.

View Detailed Post

46. What are the possible values that can be stored in a BOOLEAN data field?
TRUE and FALSE

47. What is the largest value that can be stored in a BYTE data field?
The largest number that can be represented in a single byte is 11111111 or 255.
The number of possible values is 256 (i.e. 255 (the largest possible value) plus 1
(zero), or 28).
48. What are Operators available in SQL?
SQL Operator is a reserved word used primarily in an SQL statement’s WHERE
clause to perform operations, such as arithmetic operations and comparisons.
These are used to specify conditions in an SQL statement.

There are three types of Operators.

1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators

View Detailed Post

49. Which TCP/IP port does SQL Server run?


By default it is 1433

50. List out the ACID properties and explain?


Following are the four properties of ACID. These guarantees that the database
transactions are processed reliably.

 Atomicity
 Consistency
 Isolation
 Durability

51. Define the SELECT INTO statement.


The SELECT INTO statement copies data from one table into a new table. The new
table will be created with the column-names and types as defined in the old table.
You can create new column names using the AS clause.
1 SELECT * INTO newtable FROM oldtable WHERE condition;

52. What is the difference between Delete, Truncate and Drop command?
The difference between the Delete, Truncate and Drop command is

 Delete command is a DML command, it is used to delete rows from a table. It


can be rolled back.
 Truncate is a DDL command, it is used to delete all the rows from the table
and free the space containing the table. It cant be rolled back.
 Drop is a DDL command, it removes the complete data along with the table
structure(unlike truncate command that removes only the rows). All the
tables’ rows, indexes, and privileges will also be removed.

53. What is the difference between Delete and Truncate?


The difference between the Delete, and Truncate are

DELETE TRUNCATE

Delete statement is used to delete rows from Truncate statement is used to delete all the

a table. It can be rolled back. rows from the table and free the space

containing the table. It cant be rolled back.

We can use WHERE condition in DELETE We cant use WHERE condition in TRUNCATE

statement and can delete required rows statement. So we cant delete required rows

alone
DELETE TRUNCATE

We can delete specific rows using DELETE We can only delete all the rows at a time

using TRUNCATE

Delete is a DML command Truncate is a DDL command

Delete maintains log and performance is Truncate maintains minimal log and

slower than Truncate performance wise faster

We need DELETE permission on Table to use We need at least ALTER permission on the

DELETE command table to use TRUNCATE command

54. What is the difference between Union and Union All command?
This is one of the tricky SQL Interview Questions. Interviewer may ask you this
question in another way as what are the advantages of Union All over Union.

Both Union and Union All concatenate the result of two tables but the way these
two queries handle duplicates are different.

Union: It omits duplicate records and returns only distinct result set of two or more
select statements.
Union All: It returns all the rows including duplicates in the result set of different
select statements.
Performance wise Union All is faster than Union, Since Union All doesn’t remove
duplicates. Union query checks the duplicate values which consumes some time to
remove the duplicate records.

Assume: Table1 has 10 records, Table2 has 10 records. Last record from both the
tables are same.

If you run Union query.

1 SELECT * FROM Table1

2 UNION

3 SELECT * FROM Table2

Output: Total 19 records

If you run Union query.

1 SELECT * FROM Table1

2 UNION ALL
3 SELECT * FROM Table2

Output: Total 20 records

Data type of all the columns in the two tables should be same.

55. What is the difference between Having and Where clause?


Where clause is used to fetch data from a database that specifies particular criteria
whereas a Having clause is used along with ‘GROUP BY’ to fetch data that meets
particular criteria specified by the Aggregate functions. Where clause cannot be
used with Aggregate functions, but the Having clause can.

56. What are aggregate functions in SQL?


SQL aggregate functions return a single value, calculated from values in a
column. Some of the aggregate functions in SQL are as follows

 AVG() – This function returns the average value


 COUNT() – This function returns the number of rows
 MAX() – This function returns the largest value
 MIN() – This function returns the smallest value
 ROUND() – This function rounds a numeric field to the number of decimals
specified
 SUM() – This function returns the sum

View Detailed Post

57. What are string functions in SQL?


SQL string functions are used primarily for string manipulation. Some of the widely
used SQL string functions are

 LEN() – It returns the length of the value in a text field


 LOWER() – It converts character data to lower case
 UPPER() – It converts character data to upper case
 SUBSTRING() – It extracts characters from a text field
 LTRIM() – It is to remove all whitespace from the beginning of the string
 RTRIM() – It is to remove all whitespace at the end of the string
 CONCAT() – Concatenate function combines multiple character strings
together
 REPLACE() – To update the content of a string.

View Detailed Post

Practical SQL Interview Questions:

58. How to add new Employee details in an Employee_Details table with the
following details
Employee_Name: John, Salary: 5500, Age: 29?

INSERT into Employee_Details (Employee_Name, Salary, Age) VALUES (‘John’,


1
5500 , 29);

View Detailed Post

59. How to add a column ‘Salary’ to a table Employee_Details?

1 ALTER TABLE Employee_Details ADD (Salary);

View Detailed Post


60. How to change a value of the field ‘Salary’ as 7500 for an Employee_Name ‘John’
in a table Employee_Details?

1 UPDATE Employee_Details set Salary = 7500 where Employee_Name = ‘John’;

View Detailed Post

61. Write an SQL Query to select all records from the table?

1 Select * from table_name;

View Detailed Post

62. How To Get List of All Tables From A DataBase?


To view the tables available on a particular DataBase

1 USE TestDB

2 GO
3 SELECT * FROM sys.Tables

4 GO

63. Define SQL Delete statement.


The SQL Delete statement is used to delete records from a table.

1 DELETE FROM table_name WHERE some_column=some_value;

View Detailed Post

64. Write the command to remove all Players named Sachin from the Players table.

1 DELETE from Players WHERE Player_Name = ‘Sachin’

65. How to fetch values from TestTable1 that are not in TestTable2 without using
NOT keyword?

1 --------------
2 | TestTable1 |

3 --------------

4| 11 |

5| 12 |

6| 13 |

7| 14 |

8 --------------

1 --------------

2 | TestTable2 |

3 --------------

4| 11 |

5| 12 |

6 --------------
By using the except keyword

1 SELECT * FROM TestTable1 EXCEPT SELECT * FROM TestTable2;

66. How to get each name only once from an employee table?
By using the DISTINCT keyword, we could get each name only once.

1 SELECT DISTINCT employee_name FROM employee_table;

67. How to rename a column in the output of SQL query?


By using SQL AS keyword

1 SELECT column_name AS new_name FROM table_name;

68. What is the order of SQL SELECT?


Order of SQL SELECT statement is as follows

SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY.

69. How to display the current date in SQL.


By using query
1 SELECT GetDate();

70. Write an SQL Query to find an Employee_Name whose Salary is equal or greater
than 5000 from the below table Employee_Details.

1 | Employee_Name | Salary|

2 -----------------------------

3 | John | 2500 |

4 | Emma | 3500 |

5 | Mark | 5500 |

6 | Anne | 6500 |

7 -----------------------------

Syntax:
1 SELECT Employee_Name FROM Employee_Details WHERE Salary>=5000;

Output:

1 | Employee_Name | Salary|

2 -----------------------------

3 | Mark | 5500 |

4 | Anne | 6500 |

5 -----------------------------

71. Write an SQL Query to find list of Employee_Name start with ‘E’ from the below
table

1 | Employee_Name | Salary|

2 -----------------------------

3 | John | 2500 |
4 | Emma | 3500 |

5 | Mark | 5500 |

6 | Anne | 6500 |

7 -----------------------------

Syntax:

1 SELECT * FROM Employee_Details WHERE Employee_Name like 'E%';

Output:

1 | Employee_Name | Salary|

2 -----------------------------

3 | Emma | 3500 |

4 -----------------------------

72. Write SQL SELECT query that returns the FirstName and LastName from
Employee_Details table.
1 SELECT FirstName, LastName FROM Employee_Details;

73. How to rename a Table?

1 SP_RENAME TABLE 'SCOREBOARD', 'OVERALLSCORE'

To rename Table Name & Column Name

1 sp_rename OldTableName,NewTableName

2 sp_rename 'TableName.OldColumnName', 'NewColumnName'

74. How to select all the even number records from a table?
To select all the even number records from a table:

1 Select * from table where id % 2 = 0


2

75. How to select all the odd number records from a table?
To select all the odd number records from a table:

1 Select * from table where id % 2 != 0

76. What is the SQL CASE statement?


SQL Case statement allows embedding an if-else like clause in the SELECT
statement.

77. Can you display the result from the below table TestTable based on the
criteria M,m as M and F, f as F and Null as N and g, k, I as U

1 SELECT Gender from TestTable

1 | Gender |

2 ------------
3 | M |

4 | F |

5 | NULL |

6 | m |

7 | f |

8 | g |

9 | H |

10 | i |

11 ------------

By using the below syntax we could achieve the output as required.

1 SELECT Gender,

2 case

3 when Gender='i' then 'U'


4 when Gender='g' then 'U'

5 when Gender='H' then 'U'

6 when Gender='NULL' then 'N'

7 else upper(Gender)

8 end as newgender from TestTable GROUP BY Gender

78. What will be the result of the query below?

1 select case when null = null then 'True' else 'False' end as Result;

This query returns “False”. In the above question, we could see null = null is not the
proper way to compare a null value. To compare a value with null, we use IS
operator in SQL.

So the correct way is as follows

1 select case when null is null then 'True' else 'False' end as Result;

79. What will be the result of the query below?


select case when null is null then 'Queries In SQL Server' else 'Queries In MySQL'
1
end as Result;

This query will returns “Queries In SQL Server”.

80. How do you update F as M and M as F from the below table TestTable?

1 | Name | Gender |

2 ------------------------

3 | John | M |

4 | Emma | F |

5 | Mark | M |

6 | Anne | F |

7 ------------------------

By using the below syntax we could achieve the output as required.


1 UPDATE TestTable SET Gender = CASE Gender WHEN 'F' THEN 'M' ELSE 'F' END

81. Describe SQL comments?


Single Line Comments: Single line comments start with two consecutive hyphens (–)
and ended by the end of the line
Multi-Line Comments: Multi-line comments start with /* and end with */. Any text
between /* and */ will be ignored.

82. How to get unique records from a table?


By using DISTINCT keyword.

1 SELECT DISTINCT Col1, Col2 from Table1

83. What is the difference between NVL function, IFNULL function, and ISNULL
function?
These three functions work in the same way. These functions are used to replace
NULL value with another value. Oracle developers use NVL function, MySQL
developers use IFNULL function and SQL Server developers use ISNULL function.
Assume, some of the values in a column are NULL.
If you run below statement, you will get result as NULL
1 SELECT col1 * (col2 + col3) FROM Table1

Suppose any of the value in col3 is NULL then as I said your result will be NULL.

To overcome this we use NVL() function, IFNULL() function, ISNULL() Function.

ORACLE:

1 SELECT col1 * (col2 + NVL(col3,0)) FROM Table1

MySQL:

1 SELECT col1 * (col2 + IFNULL(col3,0)) FROM Table1

Also, you can use the COALESCE() function

1 SELECT col1 * (col2 + COALESCE(col3,0)) FROM Table1

SQL Server:
1 SELECT col1 * (col2 + ISNULL(col3,0)) FROM Table1

Вам также может понравиться