SQL Concepts - Tuning PDF
SQL Concepts - Tuning PDF
STUDENT
TABLE 1
These are some important terminologies that are used in terms of relation.
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
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:
Case 1: If we want to retrieve attributes ROLL_NO and NAME of all students, the
query will be:
ROLL_NO NAME
1 RAM
2 RAMESH
3 SUJIT
4 SURESH
ROLL_NO NAME
3 SUJIT
4 SURESH
CASE 4: If we want to represent the relation in ascending order by AGE, we can use
ORDER BY clause as:
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:
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.
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.;
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.
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 :
(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 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 :
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
into database.
in a transaction.
COMMIT;
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:
ROLLBACK;
Output:
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.
//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.
Once a SAVEPOINT has been released, you can no longer use the ROLLBACK
command to undo transactions performed since the last SAVEPOINT.
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:
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:
FROM StudentDetails
To see the data in the View, we can query the view in the same manner
as we query a table.
Output:
FROM StudentDetails
ORDER BY NAME;
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:
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:
For example, if we want to delete the View MarksView, we can do this as:
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:
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:
Output:
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”.
VALUES("Suresh","Gurgaon");
WHERE condition;
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.
WHERE NAME="Suresh";
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.
FROM StudentDetails
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:
--another comment
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:
another comment */
More examples:
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.
);
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.
3. (
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.
10. (
14. );
17. (
22. );
1 2253 3
2 3325 3
3 4521 2
4 8532 1
Customers
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:
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
26. (
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.
33. (
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:
SYSTEM
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 –
TO manager;
Grant succeeded.
Grant succeeded.
Drop a Role :
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.
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 –
Unique Indexes –
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.
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.
INCREMENT BY increment_value
CYCLE|NOCYCLE ;
Example
Following is the sequence query creating sequence in ascending order.
Example 1:
start with 1
increment by 1
minvalue 0
maxvalue 100
cycle;
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.
(
ID number(10),
NAME char(20)
);
______________________
| 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:
(SELECT avg(Attr1)
FROM Table),
SELECT Attr1
FROM Table
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
SQL Query:
WITH temporaryTable(averageValue) as
(SELECT avg(Salary)
from Employee),
Output:
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
SQL Query:
FROM Pilot
GROUP BY Airline),
airlineAverage(avgSalary) as
(SELECT avg(total)
FROM totalSalary )
SELECT Airline
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.
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
% characters.
[range_of_characters] brackets.
Basic syntax:
Queries
To fetch records from Student table with NAME ending with letter ‘T’.
Output:
To fetch records from Student table with NAME ending any letter but starting
from ‘RAMES’.
2RAMESHGURGAON965243154318
To fetch records from Student table with address containing letters ‘a’, ‘b’, or
‘c’.
Output:
2RAMESHGURGAON965243154318
To fetch records from Student table with ADDRESS not containing letters ‘a’,
‘b’, or ‘c’.
Output:
To fetch records from Student table with PHONE feild having a ‘9’ in 1st
position and a ‘5’ in 4th position.
Output:
Output:
To fetch records from Student table with ADDRESS containing ‘OH’ at any
position, and the result set should not contain duplicate data.
Output:
FROM table 1
WHERE…..
INTERSECT
FROM table 2
WHERE…..
Example :
Query :
FROM
table1
LEFT JOIN
table2
ON table1.ID = table2.Employee_ID
INTERSECT
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 :
FROM table 1
WHERE…..
EXCEPT
FROM table 2
WHERE…..
Example :
Table 1 containing Employee Details
Query :
FROM
table1
LEFT JOIN
table2
ON table1.ID = table2.Employee_ID
EXCEPT
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?
QUERY 2: Write SQL query to find the location_id, street_address, postal_code and
their respective country name?
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:
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:
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
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.
SELECT *
FROM Student
LIMIT 5 OFFSET 2;
Output:
12003 Hema 8
12004 Robin 9
12005 Sita 7
12006 Anne 10
12007 Yusuf 7
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....//
THEN UPDATE
THEN INSERT
THEN DELETE;
These SQL commands are mainly categorized into four categories as discussed
below:
Examples:
Now CPI_DATA domain is create so, we can use this domain anywhere in any table
of database as below :
Every time cpi_data will check the constraint, when you add data in student table.
Example 1 :
Example 2 :
DESCRIBE one;
OR
DESC one;
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:
name char(25),
city varchar2(25)
DESC one
OR
DESCRIBE one
Output:
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
5. [ELSE statement_list]
6. END CASE
8. CASE
Examples:
Say we have a relation, Faculty.
Faculty Table:
FACULTYID NAME DEPARTMENT GENDER
001 Aakash CS M
002 Sahil EC M
004 Shelley CS F
005 Anannya CS 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'
department='Computer Science';
WHEN 'EC'
END CASE
Output:
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.
CASE Gender
END
FROM Faculty
Output:
FROM Customers
ORDER BY
ElSE FacultyID
END
Output:
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
FROM table2
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
FROM table2
Queries
Example 1: Find all the instructors that taught at most one course in the year 2017.
Instructor relation:
SQL Query:
FROM Instructor as I
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
SQL Query:
FROM Course as C
FROM Course as T
COURSEID NAME
CSE101 Programming
Example:
(SELECT *
FROM pets
Queries
pets table:
Query 1:
SELECT *
FROM newTable
Output:
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 :
(SELECT *
FROM pets
Output:
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):
Columns can be also be given new name with the use of ALTER TABLE.
Syntax(Oracle):
Syntax(MySQL,MariaDB):
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.
OUTPUT:
ROLL_NO FIRST_NAME
1 Ram
2 Abhi
3 Rahul
4 Tanu
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.
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:
DROP COLUMN is used to drop column in a table. Deleting the unwanted columns
from the table.
Syntax:
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):
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.
OUTPUT:
1 Ram
2 Abhi
3 Rahul
ROLL_NO NAME AGE
4 Tanu
After running the above query maximum size of Course Column is reduced to 20
from 40.
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.
Employee Table:
As we can notice, the entries are not sorted on the basis of their primary key, i.e.
EmployeeID.
Sample Query:
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:
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:
PATTERN MEANING
‘a%t’ Match strings which contain the start with ‘a’ and end with ‘t’.
‘%wow%’ position.
‘a_%_%’ characters.
Example:
Say we have a relation, Supplier. We want to test various patterns using the LIKE
clause:
Supplier Table:
FROM Suppliers
WHERE Name LIKE 'Ca%';
Output:
SELECT *
FROM Suppliers
Output:
FROM Suppliers
Output:
SELECT column_name(s)
FROM table_name
Instructor Table:
select name
from instructor
from instructor
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
Examples:
Consider the following Employee table,
Print Fname, Lname of all the Employee except the employee having lowest
salary.
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
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
Output:
FROM Employee
ORDER BY Salary
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.
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:
1 Rohan DBMS
2 Kevin OS
3 Mansi DBMS
4 Mansi ADA
5 Rekha ADA
6 Megha OS
TA Table:
2 Sita IP
3 Manik AP
4 Rekha SNS
SELECT Name
FROM Students
EXCEPT
SELECT NAME
FROM TA;
Output:
Rohan
Mansi
Megha
SELECT Name
FROM Students
EXCEPTALL
SELECT Name
FROM TA;
Output:
Rohan
Mansi
Mansi
Megha
Important Points:
FROM table_name
WHERE condition
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:
GROUP BY NAME;
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:
FROM Student
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:
FROM table_name
WHERE condition
Example:
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.
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.
Output:
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.
Output:
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.
Output:
CODE
To fetch Branch using Stream as alias name and Grade as CGPA from table
Student_Details.
Output:
Stream CGPA
Information Technology O
Stream CGPA
Computer Science E
Computer Science O
Mechanical Engineering A
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.
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:
Output:
ROLL_NO
Output:
ROLL_NO
UNION ALL
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;
operator description
= Equal to
Queries
Output:
Output:
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;
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)
Output:
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.
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:
Output:
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,..);
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.
Output:
NAME ADDRESS
Ram Delhi
RAMESH GURGAON
SUJIT ROHTAK
NAME ADDRESS
SURESH Delhi
SUJIT ROHTAK
RAMESH GURGAON
Output:
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:
Sample Queries:
1. To fetch all the records from Student table where Age is 18 and ADDRESS is
Delhi.
Output:
3. To fetch all the records from Student table where NAME is Ram and Age is
18.
Output:
OR Operator
Basic Syntax:
Sample Queries:
1. To fetch all the records from Student table where NAME is Ram or NAME is
SUJIT.
3. To fetch all the records from Student table where NAME is Ram or Age is 20.
Output:
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:
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
Output:
NAME
Ram
RAMESH
SUJIT
SURESH
Output:
Basic Syntax:
Queries
To fetch first two data set from Student table.
Output:
ROLL_NO NAME ADDRESS PHONE Age
Output:
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:
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:
This query will return all the rows in the table with fields column1 , column2.
Query to fetch the fields ROLL_NO, NAME, AGE from the table Student:
Output:
1 Ram 18
2 RAMESH 18
3 SUJIT 20
4 SURESH 18
Output:
Basic Syntax
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.
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
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.
Output:
The table Student will now look like,
Examples:
DROP TABLE table_name;
table_name: Name of the table 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:
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
Basic Syntax:
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.
Output:
The above query will delete only the first row and the table Student will now
look like,
Deleting multiple records: Delete the rows from the table Student where Age
is 20. This will delete 2 rows(third row and fifth row).
Output:
The above query will delete two rows(third row and fifth row) and the
table Student will now look like,
Delete all of the records: There are two queries to do this as shown below,
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:
Example Query:
This query will create a new database in SQL and name the database
as 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:
column1 data_type(size),
column2 data_type(size),
column3 data_type(size),
....
);
Example Query:
This query will create a table named Students with three columns, ROLL_NO, NAME
and SUBJECT.
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:
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:
value1, value2, value3 : value of first column, second column,... for the new
record
Queries:
Output:
The table Student will now look like:
Output:
The table Student will now look like:
ROLL_NO NAME ADDRESS PHONE Age
Notice that the columns for which the values are not provided are filled by null.
Which is the default values for those columns.
Inserting all columns of a table: We can copy all the data of a table and insert
into in a different table.
Syntax:
We have used the SELECT statement to copy the data from one table and
INSERT INTO statement to insert in a different table.
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:
Table2: LateralStudent
Queries:
Method 1(Inserting all rows and columns):
Output:
This query will insert all the data of the table LateralStudent in the table
Student. The table Student will now look like,
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,
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,
StudentCourse
FROM table1
FROM Student
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:
5. WHERE some_condition;
6.
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
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
5. ON table1.matching_column = table2.matching_column;
6.
7.
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:
16.
17.
Note: We can also use LEFT OUTER JOIN instead of LEFT JOIN, both are same.
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
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:
26.
27.
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
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:
36.
37.
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Output:
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:
Output:
See, we are able to use apostrophe in the
new column as a literal value of myTable
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
:
Here we get Error since we are using apostrophe in our literal value directly.
Output:
See, we are able to use apostrophe in the
work column as a literal value of myTable2
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:
Output (Third and Fifth Columns show values concatenated by operator ||)
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:
with values)
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:
FROM table_name
WHERE condition
MINUS
WHERE condition;
Queries:
SELECT NAME, AGE , GRADE
FROM Table1
MINUS
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.
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.
Relational algebra
r1 ← πx(R) x S
x values with “incomplete combinations”,
r2x ← πx(r1-R)
and
result ← πx(R)-r2x
Supply Schema
WHERE sid not in ( SELECT sid FROM ( (SELECT sid, pid FROM (select pid from parts)
as p
cross join
EXCEPT
EXCEPT
Company schema
2. List employees who work on all projects controlled by dno=4.
Ans 1. Using implementation 1
(SELECT essn, pno FROM (select pno from project where dno=4)
EXCEPT
Important : For division correlated query seems simpler to write but may expensive
to execute.
Some more Examples.
NOT Example
The following SQL statement selects all fields from “Customers” where country is
not “UK”
SELECT * FROM Customers WHERE NOT Country=’UK’;
Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Examples:
Consider the following Employee Table,
Queries
WHERE Salary
Output:
FROM Employee
where DOB
FROM Emplyoee
WHERE Salary
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
Queries
Find the Fname, Lname of the Employees who have Salary equal to 30000,
40000 or 25000.
FROM Employee
Output:
Find the Fname, Lname of all the Employee who have Salary not equal to
25000 or 30000.
FROM Employee
Age INT,
GENDER VARCHAR(9),
PRIMARY KEY(ID),
);
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(
GENDER VARCHAR(9),
PRIMARY KEY(ID),
);
Student relation:
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)
There won’t be any database update and as the age < 17 years.
Remove check constraint: Check constraint can be removed from the relation
in the database from SQL server using the syntax:
Drop check constraint: Check constraint can be dropped from the relation in
the database in MySQL using the 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:
SELECT SQUARE(..value..)
Example:
SELECT CEILING(..value..)
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.
In this type of conversion the data is converted from one type to another implicitly
(by itself/automatically).
FROM TO
DATE VARCHAR2
NUMBER VARCHAR2
EXAMPLE :
1. QUERY:
2. SELECT employee_id,first_name,salary
3. FROM employees
OUTPUT :
4. QUERY:
5. SELECT employee_id,first_name,salary
6. FROM employees
OUTPUT :
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(date, ’format_model’)
FROM employees
OUTPUT :
EMPLOYEE_ID MONTH_HIRED
205 06/94
ELEMENT DESCRIPTION
AM or PM Meridian indicater
MI Minute 0-59
ELEMENT DESCRIPTION
SS Second 0-59
Other Formats :
ELEMENT DESCRIPTION
ELEMENT DESCRIPTION
THSP FOURTH
EXAMPLE :
SELECT last_name,
AS HIREDATE
FROM employees;
OUTPUT :
LASTNAME HIIREDATE
TO_CHAR(number, ’format_model’)
9 Represent a number
EXAMPLE :
SELECT TO_CHAR(salary, ’$99,999.00’) SALARY
FROM employees
OUTPUT :
SALARY
$5000
TO_NUMBER(char[, ’format_model’])
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 :
FROM employees
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:
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 :
Input:
SELECT GREATEST('XYZ', 'xyz')
from dual;
Output:
GREATEST('XYZ', 'xyz')
xyz
Input:
SELECT GREATEST('XYZ', null, 'xyz')
from dual;
Output:
GREATEST('XYZ', null, 'xyz')
-
Input:
SELECT IFNULL(1,0)
FROM dual;
Output:
-
1
Input:
SELECT IFNULL(NULL,10)
FROM dual;
Output:
--
10
Output:
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:
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 –
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 –
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 –
Example –
’ST_CLERK’, 1.15*salary,
’SA_REP’, 1.20*salary,salary)
Output :
Examples –
SELECT last_name,
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 –
Examples –
NULLIF(LENGTH(first_name),LENGTH(last_name))
Output :
LNNVL( condition(s) )
Examples –
Output :
Now the above examples does not considered those employees who have no
commission at all.
To include them as well we use LNNVL()
Output :
NANVL( n1 , n2 )
Example –
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 :
Case-Manipulative Functions
LOWER(SQL course)
Input1: SELECT LOWER('GEEKSFORGEEKS') FROM DUAL;
Output1: geeksforgeeks
Input2: SELECT LOWER('DATABASE@456') FROM DUAL;
Output2: database@456
UPPER(SQL course)
Input1: SELECT UPPER('geeksforgeeks') FROM DUAL;
Output1: GEEKSFORGEEKS
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
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
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
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
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')
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)
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:
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:
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.
FROM Employee;
Output:
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:
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.
FROM Employee;
Output:
FROM table_name;
Example:
Consider the following Contact_info table,
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:
FROM table_name;
Example:
Consider the following Sales table,
FROM Sales;
Output:
SQL | LISTAGG
LISTAGG function in DBMS is used to aggregate strings from data in columns in a
database table.
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 :
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.
2 FROM GfG ;
Output:
SUBJECTS
-----------------------------------------------------------------------------------
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
------ --------------------------------------------------------------------------------
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.
2 FROM GfG
3 GROUP BY SubNo
4 ORDER BY SubNo;
Output:
SUBNO SUBJECTS
----- --------------------------------
SELECT NOW();
Output:
2017-01-13 08:03:52
SELECT CURDATE();
Output:
2017-01-13
SELECT CURTIME();
Output:
08:05:15
Output:
Name BirthDate
Pratik 1996-09-26
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
Queries
Output:
Name BirthDay
Pratik 26
Output:
Name BirthYear
Pratik 1996
Output:
Name BirthSecond
Pratik 581
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
Queries
Output:
Name BirthTimeModified
Output:
Name BirthDayModified
Output:
Name BirthSecond
DATEDIFF(date1, date2);
Example:
Output:
DateDiff
10
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:
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
Queries:
1. Computing average marks of students.
Output:
AvgMarks
80
Output:
AvgAge
19.4
Output:
NumStudents
Output:
NumStudents
FIRST(): The FIRST() function returns the first value of the selected column.
Syntax:
Queries:
Output:
MarksFirst
90
Output:
AgeFirst
19
LAST(): The LAST() function returns the last value of the selected column. It
can be used only in MS ACCESS.
Syntax:
Queries:
1. Fetching marks of last student from the Students table.
Output:
MarksLast
82
Output:
AgeLast
18
MAX(): The MAX() function returns the maximum value of the selected
column.
Syntax:
Queries:
1. Fetching maximum marks among students from the Students table.
Output:
MaxMarks
95
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.
Output:
MinMarks
50
Output:
MinAge
18
SUM(): The SUM() function returns the sum of all the values of the selected
column.
Syntax:
Queries:
1. Fetching summation of total marks among students from the Students
table.
TotalMarks
400
Output:
TotalAge
97
Scalar Functions
UCASE(): It converts the value of a field to uppercase.
Syntax:
Queries:
1. Converting names of students from the table Students to uppercase.
Output:
NAME
HARSH
SURESH
PRATIK
DHANRAJ
RAM
Queries:
1. Converting names of students from the table Students to lowercase.
Output:
NAME
Harsh
suresh
Pratik
dhanraj
Ram
MID(): The MID() function extracts texts from the text field.
Syntax:
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.
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.
Output:
NAME
Output:
MARKS
90
50
80
95
85
NOW(): The NOW() function returns the current system date and time.
Syntax:
Queries:
1. Fetching current system time.
Output:
NAME DateTim
HARSH 1/13/2017 1:30
Queries:
1. Formatting current date as ‘YYYY-MM-DD’.
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
s_name varchar(20));
Table 3: details
d.school_id = m.school_id;
Output:
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:
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:
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:
Department relation:
Electrical 80000
Humanities 50000
Mechanical 40000
Civil 60000
Query:
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.
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.
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 AVG(salary)
FROM employees
WHERE department_id =
outer.department_id);
CORRELATED UPDATE :
WHERE alias1.column =
alias2.column);
Use a correlated subquery to update rows in one table based on rows from another
table.
CORRELATED DELETE :
(SELECT expression
Use a correlated subquery to delete rows in one table based on the rows from
another table.
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.
FROM employees
WHERE manager_id =
outer.employee_id);
OUTPUT :
FROM departments d
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.
SELECT column_name
FROM table_name
Sample Table:
DATABASE
NAME ROLL_NO LOCATION PHONE_NUMBER
STUDENT
Ravi 104 A
Sumathi 105 B
Raj 102 A
Sample Queries
:
WHERE ROLL_NO IN
(SELECT ROLL_NO from STUDENT where SECTION=’A’);
Table2: Student2
Output:
FROM Student1
WHERE LOCATION = ’chennai’);
Output:
UPDATE Student2
SET NAME=’geeks’
FROM Student1
Output:
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 :
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 :
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
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
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.
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.
NAME SECTION
abc CS1
bcd CS2
abc CS1
In the above table, we can find duplicate row using below query.
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:
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, count(NAME) as num
from Person
group by NAME
) as statistic
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
ename sal
A 23000
B 31000
C 24500
D 35000
E 28500
F 31500
G 39800
H 51000
I 39800
Query :
select * from(
where r=&n;
Output :
DENSE_RANK :
Alternate Solution :
———————————————————————————————————————
——————————————————————————————–
———————————————————————————————————————
—————————————-
6th highest
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)
———————————————————————————————————————
———————————–
+-------+-----+
| ENAME | SAL |
+-------+-----+
|A | 100 |
|B | 300 |
|C | 200 |
|D | 500 |
|F | 400 |
|G | 600 |
|H | 700 |
|I | 800 |
+-------+-----+
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.
We can nest the above query to find the second largest salary.
FROM employee
FROM employee);
WHERE salary IN
FROM employee);
FROM employee
FROM employee);
WITH T AS
SELECT *
FROM Employees
SELECT Name
FROM T
WHERE Rnk=2;
FROM employee
WHERE salary < (SELECT MAX(salary)
FROM employee
FROM employee)
);
Note that instead of nesting for second, third largest salary, we can find nth salary
using general query like in mysql:
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:
OR
Examples:
Output :
2. verify SEQUENCES
SYNTAX:
OR
SELECT * FROM USER_SEQUENCES;
Examples:
Output :
Output :
3. verify INDEXES
SYNTAX:
OR
Examples:
Output :
4. verify TABLES
SYNTAX:
OR
Examples:
Output :
5. verify SYNONYMS
SYNTAX:
Examples:
Output :
6. verify TRIGGERS
SYNTAX:
OR
Examples:
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:
Contains only one single base table or tables or is created from more
Simple view does not contain group by, It can contain group by, distinct,
Does not include NOT NULL columns selected by simple view can be
In Static SQL, how database will be In Dynamic SQL, how database will
a c2 50
b c3 60
d c1 70
e c2 80
b 60
d 70
e 80
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
StudentCourse Table
COURSEID ENROLLNO
1 1001
2 1001
3 1001
1 1002
2 1003
SELECT StudentCourse.CourseID,Student.StudentName
FROM Student
ON StudentCourse.EnrollNo = Student.EnrollNo
ORDER BY StudentCourse.CourseID
Note: INNER is optional above. Simple JOIN is also considered as INNER JOIN
COURSEID STUDENTNAME
1 geek1
1 geek2
2 geek1
2 geek3
3 geek1
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
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.
3. FROM Customers
5. FROM Orders
Output:
6. Using NOT with EXISTS
Fetch last and first name of the customers who has not placed any order.
8. FROM Customer
Output:
DELETE
FROM Orders
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:
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)
DEPTNO NUMBER(2)
DNAME VARCHAR2(14)
LOC VARCHAR2(13)
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:
SUBTABLE.MAXSAL, SUBTABLE.MINSAL,
SUBTABLE.AVGSAL, SUBTABLE.SUMSAL
FROM EMP
INNER JOIN
FROM EMP
ON EMP.JOB = SUBTABLE.JOB;
FROM EMP
ON EMP.DEPTNO=DEPT.DEPTNO
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:
FROM table_name
WHERE condition(s);
Syntax:
SELECT column_name(s)
FROM table_name
(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.
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
FROM OrderDetails
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
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
(SELECT column_name
FROM table_name
WHERE condition(s));
Queries
Find the Distinct CategoryID of the products which have any record in
OrderDetails Table.
FROM OrderDetails);
Output:
SELECT ProductName
FROM Products
FROM OrderDetails
1) Count()
2) Sum()
3) Avg()
4) Min()
5) Max()
Id Name Salary
-----------------------
1 A 80
2 B 40
3 C 60
4 D 70
5 E 60
6 F Null
Count():
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():
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.
Output: 243.5
+--------------------------------------+
| ABS(10)
+--------------------------------------+
| 10
+--------------------------------------+
Output: 1.318116071652818
3. ASIN(): It returns the arc sine of a number.
Output: 0.25268025514207865
4. ATAN(): It returns the arc tangent of a number.
Output: 1.1902899496825317
5. CEIL(): It returns the smallest integer value that is greater than or equal to a
number.
Output: 26
6. CEILING(): It returns the smallest integer value that is greater than or equal to
a number.
Output: 26
7. COS(): It returns the cosine of a number.
Output: 0.15425144988758405
8. COT(): It returns the cotangent of a number.
Output: -3.436353004180128
9. DEGREES(): It converts a radian value into degrees.
Output: 85.94366926962348
SQL>SELECT DEGREES(PI());
+------------------------------------------+
| DEGREES(PI())
+------------------------------------------+
| 180.000000
+------------------------------------------+
Output: 2
11. EXP(): It returns e raised to the power of number.
Output: 2.718281828459045
12. FLOOR(): It returns the largest integer value that is less than or equal to a
number.
Output: 25
13. GREATEST(): It returns the greatest value in a list of expressions.
Output: 125
14. LEAST(): It returns the smallest value in a list of expressions.
Output: 2
15. LN(): It returns the natural logarithm of a number.
Output: 0.6931471805599453
16. LOG10(): It returns the base-10 logarithm of a number.
Output: 0.6931471805599453
17. LOG2(): It returns the base-2 logarithm of a number.
Output: 2.584962500721156
18. MOD(): It returns the remainder of n divided by m.
Output: 2
19. PI(): It returns the value of PI displayed with 6 decimal places.
Output: 3.141593
20. POW(): It returns m raised to the nth power.
Output: 3.141592653589793
22. RAND(): It returns a random number.
Output: 0.33623238684258644
23. ROUND(): It returns a number rounded to a certain number of decimal
places.
Output: 6
24. SIGN(): It returns a value indicating the sign of a number.
Output: 1
25. SIN(): It returns the sine of a number.
Output: 0.9092974268256817
26. SQRT(): It returns the square root of a number.
Output: 5
27. TAN(): It returns the tangent of a number.
Output: -5.52037992250933
28. ATAN2(): It returns the arctangent of the x and y coordinates, as an angle and
expressed in radians.
Output: 1.42889927219073
29. TRUNCATE(): It returns 7.53635 truncated to 2 places right of the decimal
point.
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.
Output: 116
Output: 6
Output: 15
Output: ‘GeeksforGeeks’
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.
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');
19. LCASE(): This function is used to convert the given string into lower case.
21. LEFT(): This function is used to SELECT a sub string from the left of given size
or characters.
Output: geeks
25. LOCATE(): This function is used to find the nth position of the given word in a
string.
Output: 6
27. LOWER(): This function is used to convert the upper case string into lower
case.
Output: geeksforgeeks.org
29. LPAD(): This function is used to make the given string of the given size by
adding the given symbol.
000geeks
32. LTRIM(): This function is used to cut the given sub string from the original
string.
Output: geeks
34. MID(): This function is to find a word from the given position and of the given
size.
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.
Output: geeksgeeks
40. REPLACE(): This function is used to cut the given string by removing the given
sub string.
Output: geeks
Output: ‘gro.skeegrofskeeg’
44. RIGHT(): This function is used to SELECT a sub string from the right end of the
given size.
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.
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.
Output: ‘ ‘
Output: -1
54. SUBSTR(): This function is used to find a sub string from the a string from the
given position.
Output: ‘geeks’
56. SUBSTRING(): This function is used to find an alphabet from the mentioned
size and the given string.
Output: ‘G’
58. SUBSTRING_INDEX(): This function is used to find a sub string before the
given symbol.
Output: ‘www’
60. TRIM(): This function is used to cut the given symbol from the string.
Output: 123
62. UCASE(): This function is used to make the string in upper case.
GEEKSFORGEEKS
SQL | Advanced Functions
Following are some of the advanced functions defined in SQL:
2. SELECT BIN(18);
Output:
Output:
5. SELECT COALESCE(NULL,NULL,'GeeksforGeeks',NULL,'Geeks');
Output:
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:
Output:
11. IF(): It returns one value if a condition is TRUE, or another value if a condition
is FALSE.
Syntax:
Output:
13. LAST_INSERT_ID(): It returns the first AUTO_INCREMENT value that was set by
the most recent INSERT or UPDATE statement.
Syntax:
Output:
Output:
Syntax:
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:
Output:
19. USER(): It returns the user name and host name for the current MySQL user.
Syntax:
Output:
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:
Output: 2018-07-16
4. CURRENT_DATE(): It returns the current date.
Output: 2018-07-16
5. CURRENT_TIME(): It returns the current time.
Output: 02:53:15
6. CURRENT_TIMESTAMP(): It returns the current date and time.
Output: 02:53:28
8. DATE(): It extracts the date value from a date or date time expression.
Output: 2017-06-15
9. DATEDIFF(): It returns the difference in days between two date values.
Output: 10
10. DATE_ADD(): It returns a date after a certain time/date interval has been
added.
Output: 2018-07-16
11. DATE_FORMAT(): It formats a date as specified by a format mask.
Output: 2018
12. DATE_SUB(): It returns a date after a certain time/date interval has been
subtracted.
Output: 2018-07-16
13. DAY(): It returns the day portion of a date value.
Output: 16
14. DAYNAME(): It returns the weekday name for a date.
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.
Output: 0
17. DAYOFYEAR(): It returns the day of the year for a date value.
Output: 197
18. EXTRACT(): It extracts parts from a date.
Output: 7
19. FROM_DAYS(): It returns a date value from a numeric representation of the
day.
Output: 1876-09-29
20. HOUR(): It returns the hour portion of a date value.
Output: 9
21. LAST_DAY(): It returns the last day of the month for a given date.
Output: 2018-07-31
22. LOCALTIME(): It returns the current date and time.
Output: 2009-05-18
25. MAKETIME(): It returns the time for a certain hour, minute, second
combination.
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:
Output: 345
2. MINUTE(): It returns the minute portion of a date value.
Output: 12
3. MONTH(): It returns the month portion of a date value.
Output: 7
4. MONTHNAME(): It returns the full month name for a date.
Output: JULY
5. NOW(): It returns the current date and time.
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.
Output: 3
9. SECOND(): It returns the second portion of a date value.
Output: 0
10. SEC_TO_TIME(): It converts numeric seconds into a time value.
Output: 00:00:01
11. STR_TO_DATE(): It takes a string and returns a date specified by a format
mask.
Output: 0018-07-18
12. SUBDATE(): It returns a date after which a certain time/date interval has been
subtracted.
Output: 2017-06-05
13. SUBTIME(): It returns a time/date time value after a certain time interval has
been subtracted.
Output: 09:16:10
16. TIME_FORMAT(): It formats the time as specified by a format mask.
Output: 09 09 10
17. TIME_TO_SEC(): It converts a time value into numeric seconds.
Output: 33370
18. TIMEDIFF(): It returns the difference between two time/datetime values.
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.
Output: 737258
21. WEEK(): It returns the week portion of a date value.
Output: 28
22. WEEKDAY(): It returns the weekday index for a date value.
Output: 2
23. WEEKOFYEAR(): It returns the week of the year for a date value.
Output: 29
24. YEAR(): It returns the year portion of a date value.
Output: 2018
25. YEARWEEK(): It returns the year and week for a date value.
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
...
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:
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:
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:
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:
AS
(SELECT NationalIDNumber,
JobTitle
FROM HumanResources.Employee)
SELECT EmployeeNumber,
Title
FROM Employee_CTE
SELECT NationalIDNumber,
JobTitle
FROM HumanResources.Employee
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.
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
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.
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.
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.
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:
<common_table_expression>::=
AS (cte_query)
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.
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
AS
FROM Sales.SalesOrderHeader
GROUP BY SalesPersonID
SELECT
ts.NetSales
FROM Sales.vSalesPerson AS sp
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
FROM Sales.SalesOrderHeader
GROUP BY SalesPersonID
),
AS
SELECT ts.SalesPersonID,
CASE
ELSE sp.SalesQuota
END,
CASE
END
FROM cteTotalSales AS ts
ON ts.SalesPersonID = sp.BusinessEntityID
SELECT
sp.City,
ts.NetSales,
td.SalesQuota,
td.QuotaDiff
FROM Sales.vSalesPerson AS sp
ON sp.BusinessEntityID = ts.SalesPersonID
ON sp.BusinessEntityID = td.SalesPersonID
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.
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:
GO
)
GO
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
AS
(
SELECT EmployeeID, FirstName, LastName, ManagerID, 1
FROM Employees
UNION ALL
r.EmpLevel + 1
FROM Employees e
ON e.ManagerID = r.EmpID
SELECT
EmpLevel,
FROM cteReports
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:
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;
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:
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:
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.
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 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.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
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.
We need to report on the entire organizational structure under the CEO. The
following recursive code using a CTE will get us the output:
1 CEO NULL 0
2 President 1 1
3 Chairman 1 1
4 Vice President 2 2
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
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.
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.
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.
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.
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:
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
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
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:
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
END
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:
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:
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:
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
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:
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
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.
Below is a script for an employee table and sample data to run in your test
environment.
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.
;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
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
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:
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'
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
END
Executing the modified stored procedure again to split the same two entities lists
using the T-SQL script below:
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:
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.
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?
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.
SQL PL/SQL
We can execute one statement at a time in SQL We can execute block of statements in PL/SQL
BETWEEN
The BETWEEN operator is used to fetch rows based on a range of values.
For example,
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,
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.
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;
You may refer to this article on WHERE clause for more details on LIKE operator.
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.
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('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')
Data definition language or DDL allows executing queries like CREATE, DROP and
ALTER. That is, those queries which define the data.
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.
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.
3. FROM table_name
4. WHERE condition;
5.
For more details on how to create and use view, please refer to this article.
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.
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:
C_ID int,
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
Output –
ID NAME SALARY
1 Harpreet 20000
2 Ravi 30000
3 Vinay 10000
7 Rajeev 40000
10 Sanjay 50000
Employees –
Query –
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 –
Query –
From employees
Employees –
Query –
From employees
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 –
Query –
From employees
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 –
Query –
Select *
From employees
Select *
From employees
Select *
From employees
Note – Here every query will give same output and the list of Employees who’s
FName start with letter A.
What is DBMS?
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.
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.
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.
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.
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.
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.
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.
The normal forms can be divided into 5 forms, and they are explained below -.
This should remove all the duplicate columns from the table. Creation of tables for
the related data and identification of unique columns.
This should meet all requirements of 2NF. Removing the columns which are not
dependent on primary key constraints.
Meeting all the requirements of third normal form and it should not have multi-
valued dependencies.
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.
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.
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.
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.
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.
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.
NOT NULL.
CHECK.
DEFAULT.
UNIQUE.
PRIMARY KEY.
FOREIGN KEY.
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.
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.
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.
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.
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.
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.
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.
Disadvantage is that it can be executed only in the Database and utilizes more
memory in the database server.
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.
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.
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.
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.
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.
Example -.
45. How can you create an empty table from an existing table?
Example will be -.
Here, we are copying student table to another table with the same structure with
no rows copied.
Records can be fetched for both Odd and Even row numbers -.
49. What is the command used to fetch first 5 characters of the string?
Example -.
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
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.
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 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
FROM Employee
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:
FROM Employee
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
FROM Employee
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:
FROM Employee
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.
Action and Event are two main components of SQL triggers when certain actions
are performed the event occurs in response to that action.
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.
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 #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 #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.
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.
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.
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.
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.
Database Connectivity
Constraint Check
Required Application Field and its size
Data Retrieval and Processing With DML operations
Stored Procedures
Functional flow
WHERE <Condition>
5. What are the different types of constraints? Explain primary key, foreign key,
unique key & not null constraints?
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.
FROM students
GROUP BY subject_code;
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.
12. What are the three ways that Dynamic SQL can be executed?
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.
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.
20. What is the SQL CASE statement used for? Explain with an example?
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.
Syntax
{ index_or_statistics__name }
| ( { index_or_statistics_name } [ ,...n ] )
[ WITH
FULLSCAN
| RESAMPLE
[ ON PARTITIONS ( { | } [, …n] ) ]
| [ ,...n ]
[ [ , ] NORECOMPUTE ]
[ [ , ] INCREMENTAL = { ON | OFF } ]
];
::=
[ STATS_STREAM = stats_stream ]
[ ROWCOUNT = numeric_constant ]
[ PAGECOUNT = numeric_contant ]
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?
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 :-
For example :-
This query will return the string "Iabcllipaat". In this example, Stuff function
replaces the string "Intellipaat" onwards the 3rd position('nte') with 'abc'.
For example :-
This query will return the string Axyaxyaxy. In this example, Replace function
replaces the occurrence of each 'bc' string with 'xy'.
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.
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.
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 :
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’
GO
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:
abc
9343463943/PhoneNo>
xyz
9342673212
'
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
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:
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.
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.
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 :
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
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.
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,
Table: StudentInformation
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.
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.
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
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,
Informix etc.
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
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
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.
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.
Inner
join: Inner Join in MySQL is the most common type of join. It is used to return all the
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
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.
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
records from the table. An index creates an entry for each value and hence it will be
This index does not allow the field to have duplicate values if the column is unique
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.
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
DROP command removes a table and it cannot be rolled back from the database
whereas TRUNCATE command removes all the rows from the table.
There are many successive levels of normalization. These are called normal
forms. Each consecutive normal form depends on the previous one.The first three
ACID stands for Atomicity, Consistency, Isolation, Durability. It is used to ensure that
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
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.
Trigger in SQL is are a special type of stored procedures that are defined to execute
of code when an insert, update or any other query is executed against a specific
table.
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
A NULL value is not at all same as that of zero or a blank space. NULL value
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 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
Correlated subquery: These are queries which select the data from a table
To count the number of records in a table, you can use the below commands:
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
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:
Q32. Write a SQL query to get the third highest salary of an employee from
employee_table?
FROM(
FROM employee_table
the commonly used group functions are: AVG, COUNT, MAX, MIN, SUM, VARIANCE.
Relation or links are between entities that have something to do with each other.
Q35. How can you insert NULL values in a column while inserting the data?
Q36. What is the main difference between ‘BETWEEN’ and ‘IN’ condition operators?
Example of BETWEEN:
Example of IN:
SELECT * FROM students where ROLL_NO IN (8,15,25);
performs an UPDATE if a row exists, or an INSERT if the row does not exist.
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
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.
professionals on this technology, you can opt for a structured training from
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.
Using EXEC.
Using sp_executesql.
You can fetch common records from two tables using INTERSECT. For example:
LOWER(‘string’)
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
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
For example-
In the above example, emp refers to alias name for employee table and dept refers
single value. These calculations are done from the columns in a table. For example-
Scalar functions return a single value based on the input value. For example –
You can fetch alternate records i.e both odd and even row numbers. For example-
mod(rowno,2)=0
Q50. Name the operator which is used in the query for pattern matching?
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
You can select unique records from a table by using the DISTINCT keyword.
Using this command, it will print unique student id from the table Student.
There are a lot of ways to fetch characters from a string. For example:
SQL is a query language that allows you to issue a single query or execute a single
allows you to write a full program (loops, variables, etc.) to accomplish multiple
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
A view refers to a logical snapshot based on a table or another view. It is used for
the database system. Several SQL statements are consolidated into a stored
procedure and execute them whenever and wherever required which saves time
Advantages:
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
Scalar Functions
Inline Table-valued functions
Multi-statement valued functions
Scalar returns the unit, variant defined the return clause. Other two types of
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
width etc.
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
Local variables:
These variables can be used or exist only inside the function. These variables are
Global variables:
These variables are the variables which can be accessed throughout the program.
Auto increment keyword allows the user to create a unique number to get
AUTO INCREMENT keyword can be used in Oracle and IDENTITY keyword can be
and made available for the mining as well as online processing. Warehouse data
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
Click Start> Programs> Microsoft SQL Server and click SQL Enterprise
Manager to run SQL Enterprise Manager from the Microsoft SQL Server
program group.
Select SQL Server Configuration Properties, and choose the Security page.
where,
string_expression: it is the string that will have characters 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:
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.
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.
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.
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.,
INNER JOIN
LEFT JOIN
RIGHT JOIN
OUTER JOIN
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.
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.
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).
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 > 18), PRIMARY KEY (EmpID));
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.
1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
Atomicity
Consistency
Isolation
Durability
52. What is the difference between Delete, Truncate and Drop command?
The difference between the Delete, Truncate and Drop command is
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
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 maintains log and performance is Truncate maintains minimal log and
We need DELETE permission on Table to use We need at least ALTER permission on the
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.
2 UNION
2 UNION ALL
3 SELECT * FROM Table2
Data type of all the columns in the two tables should be same.
58. How to add new Employee details in an Employee_Details table with the
following details
Employee_Name: John, Salary: 5500, Age: 29?
61. Write an SQL Query to select all records from the table?
1 USE TestDB
2 GO
3 SELECT * FROM sys.Tables
4 GO
64. Write the command to remove all Players named Sachin from the Players table.
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
66. How to get each name only once from an employee table?
By using the DISTINCT keyword, we could get each name only once.
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:
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;
1 sp_rename OldTableName,NewTableName
74. How to select all the even number records from a table?
To select all the even number records from a table:
75. How to select all the odd number records from a table?
To select all the odd number records from a table:
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 | Gender |
2 ------------
3 | M |
4 | F |
5 | NULL |
6 | m |
7 | f |
8 | g |
9 | H |
10 | i |
11 ------------
1 SELECT Gender,
2 case
7 else upper(Gender)
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.
1 select case when null is null then 'True' else 'False' end as Result;
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 ------------------------
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.
ORACLE:
MySQL:
SQL Server:
1 SELECT col1 * (col2 + ISNULL(col3,0)) FROM Table1