SQL For Placement
SQL For Placement
SQL For Placement
TOP 30
SQL -Structured
Query Language
PLACEMENT PREPARATION [EXCLUSIVE NOTES]
Questions with Answers
@PREMMANDAL
BUSINESS & DATA ANALYST
Swipe
QUESTIONS COVERED:-
1. What is SQL? 15. What is the use of CREATE,
2. What is Database ? INSERT INTO, UPDATE and
3. What are the differences between DELETE Clauses?
SQL and PL/SQL? 16. What is the use of ADD, DROP
4. What is the difference between and MODIFY Commands?
BETWEEN and IN operators in 17. What are VIEWS in SQL?
SQL? 18. What are JOINS in SQL?
5. What is the use of LIKE operator? 6. 19. What is the use of GROUP BY
What is the use of ‘WHERE’ Clause?
Clause? 20. What are Aggregate Functions?
7. What is the use of ‘Having’ 21. What is Cursor in SQL ?
Clause? 22. What is the difference between
8. What are SQL Commands? Implicit and Explicit Cursor?
Explain types of SQL Commands 23. What is the difference between
9. What are normalization and VIEW and CURSOR in SQL?
denormalization and why do we 24. What are the advantages of
need them? PL/SQL functions?
10. What are Nested Queries in SQL? 25. Explain BETWEEN and IN
11. What are different types of Clause.
Normalization? 26. What is the difference between
12. What is Stored Procedures in SQL DROP and TRUNCATE?
? 27. What are Constraints in SQL?
13. What are different types of case 28. What is a TRIGGER?
manipulation functions available in 29. What is the use of LIMIT and
SQL. OFFSET in SQL?
14. What is the difference between 30. What are different types of
CHAR and VARCHAR2 datatype operators present in SQL?
in SQL?
What is SQL?
Structured Query Language is a computer language that we use to interact with a
relational database.SQL is a tool for organizing, managing, and retrieving archived
data from a computer database. The original name was given by IBM as
Structured English Query Language, abbreviated by the acronym SEQUEL. When
data needs to be retrieved from a database, SQL is used to make the request. The
DBMS processes the SQL query retrieves the requested data and returns it to us.
Rather, SQL statements describe how a collection of data should be organized or
what data should be extracted or added to the database.
In common usage, SQL encompasses DDL and DML commands for create, updates,
modified or other operations on database structure.
SQL uses:
• Data definition: It is used to define the structure and organization of the stored data
and relationships among the stored data items.
• Data retrieval: SQL can also be used for data retrieval.
• Data manipulation: If the user wants to add new data, remove data, or modifying in
existing data then SQL provides this facility also.
• Access control: SQL can be used to restrict a user’s ability to retrieve, add, and
modify data, protecting stored data against unauthorized access.
• Data sharing: SQL is used to coordinate data sharing by concurrent users, ensuring
that changes made by one user do not inadvertently wipe out changes made at
nearly the same time by another user.
SQL also differs from other computer languages because it describes what the user
wants the computer to do rather than how the computer should do it. (In more
technical terms, SQL is a declarative or descriptive language rather than a procedural
one.) SQL contains no IF statement for testing conditions, and no GOTO, DO, or
FOR statements for program flow control. Rather, SQL statements describe how a
collection of data is to be organized, or what data is to be retrieved or added to the
database. The sequence of steps to do those tasks is left for the DBMS to determine.
Features of SQL:
• SQL may be utilized by quite a number of users, which include people with very little
programming experience.
• SQL is a Non-procedural language.
• We can without difficulty create and replace databases in SQL. It isn't a time-
consuming process.
• SQL is primarily based totally on ANSI standards.
• SQL does now no longer have a continuation individual.
• SQL is entered into SQL buffer on one or extra lines.
• SQL makes use of a termination individual to execute instructions immediately.
It makes use of features to carry out a few formatting.
• It uses functions to perform some formatting.
Role of SQL :
SQL plays many different roles:
Despite the inaccuracy of its name, SQL has emerged as the standard language for
using relational databases. SQL is both a powerful language and one that is
relatively easy to learn. So SQL is a database management language. The database
administrator answerable for handling a minicomputer or mainframe database
makes use of SQL to outline the database shape and manipulate get entry to to the
saved data.
What is Database ?
The Database is an essential part of our life. As we encounter several activities that
involve our interaction with databases, for example in the bank, in the railway
station, in school, in a grocery store, etc. These are the instances where we need to
store a large amount of data in one place and fetch these data easily.
In a database, data is organized into tables consisting of rows and columns and it is
indexed so data can be updated, expanded, and deleted easily. Computer
databases typically contain file records data like transactions money in one bank
account to another bank account, sales and customer details, fee details of
students, and product details. There are different kinds of databases, ranging from
the most prevalent approach, the relational database, to a distributed database,
cloud database, and NoSQL databases.
• Relational Database:
A relational database is made up of a set of tables with data that fits into a
predefined category.
• Distributed Database:
A distributed database is a database in which portions of the database are
stored in multiple physical locations, and in which processing is dispersed or
replicated among different points in a network.
• Cloud Database:
A cloud database is a database that typically runs on a cloud computing
platform. Database service provides access to the database. Database
services make the underlying software-stack transparent to the user.
These interactions are the example of a traditional database where data is of one
type-that is textual. In advancement of technology has led to new applications of
database systems. New media technology has made it possible to store images,
video clips. These essential features are making multimedia databases.
Nowadays, people are becoming smart - before taking any decisions they analyze
facts and figures related to it, which come from these databases. As the databases
have made it easier to manage information, we are able to catch criminals and do
deep research.
What are the differences between SQL and PL/SQL?
IN
The IN operator is used to check for values contained in specific sets.
For example,
SELECT * FROM Students
WHERE ROLL_NO IN (20,21,23);
This query will select all those rows from the table Students where the value of the field
ROLL_NO is either 20 or 21 or 23.
What is the use of LIKE operator?
The LIKE operator of SQL is used for this purpose. It is used to fetch filtered data by
searching for a particular pattern in the where clause.
The Syntax for using LIKE is,
Basic Syntax:
SELECT column1,column2 FROM table_name WHERE column_name operator
value; column1 , column2: fields int the table
table_name: name of table
column_name: name of field used for filtering the data
operator: operation to be considered for filtering
value: exact value or pattern to get related data in result
List of operators that can be used with where clause:
EXAMPLE -
Queries
To fetch record of students with age equal to 20
SELECT * FROM Student WHERE Age=20;
Output:
Syntax:
select select_list from table_name
group by group_list
having conditions
Example:
select roll_number
from student
having name like 'R%'
Though many resources claim there to be another category of SQL clauses TCL -
Transaction Control Language. So we will see in detail about TCL as well.
DML statements are used for performing queries on the data within schema objects.
The purpose of the DQL Command is to get some schema relation based on the
query passed to it.
Example of DQL:
3. DML(Data Manipulation Language): The SQL commands that deal with the
manipulation of data present in the database belong to DML or Data Manipulation
Language and this includes most of the SQL statements.
Examples of DML:
o INSERT – is used to insert data into a table.
o UPDATE - is used to update existing data within a table.
o DELETE – is used to delete records from a database table.
STUDENT
S_ID S_NAME S_ADDRESS S_PHONE S_AGE
S1 RAM DELHI 9455123451 18
S2 RAMESH GURGAON 9652431543 18
S3 SUJIT ROHTAK 9156253131 20
S4 SURESH DELHI 9156768971 18
COURSE
C_ID C_NAME
C1 DSA
C2 Programming
C3 DBMS
STUDENT_COURSE
S_ID C_ID
S1 C1
S1 C3
S2 C1
S3 C2
S4 C2
S4 C3
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 the outer query will
return those S_IDs for which C_ID is equal to any member of the 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:
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:
The innermost query will return a set with members C1 and C3. Second inner query
will return those S_IDs for which C_ID is equal to any member of set (C1 and C3 in
this case) which are S1, S2 and S4. The outermost query will return those S_IDs
where S_ID is not a member of set (S1, S2 and S4). So it will return S3.
• Co-related Nested Queries: In co-related nested queries, the output of inner
query depends on the row which is being currently executed in outer query.
e.g.; If we want to find out S_NAME of STUDENTs who are enrolled
in C_ID ‘C1’, it can be done with the help of co-related nested query as:
For each row of STUDENT S, it will find the rows from STUDENT_COURSE where
S.S_ID = SC.S_ID and SC.C_ID=’C1’. If for a S_ID from STUDENT S, atleast a row
exists in STUDENT_COURSE SC with C_ID=’C1’, then inner query will return true
and corresponding S_ID will be returned as output.
2. 2NF : It is known as the second normal form. A table to be in its second normal
form should satisfy the following conditions:
○ The table should be in its 1NF i.e. satisfy all the conditions of 1NF.
○ Every non-prime attribute of the table should be fully functionally
dependent on the primary key i.e. every non-key attribute should be dependent on the
primary key in such a way that if any key element is
deleted then even the non_key element will be saved in the database.
3. 3NF : It is known as the third normal form. A table to be in its second normal
form should satisfy the following conditions:
○ The table should be in its 2NF i.e. satisfy all the conditions of 2NF.
○ There is no transitive functional dependency of one attribute on any
attribute in the same table.
4. BCNF: BCNF stands for Boyce-Codd Normal Form and is an advanced form of
3NF. It is also referred to as 3.5NF for the same reason. A table to be in its BCNF
normal form should satisfy the following conditions:
○ The table should be in its 3NF i.e. satisfy all the conditions of 3NF.
○ For every functional dependency of any attribute A on B
(A->B), A should be the super key of the table. It simply implies that A can’t
be a non-prime attribute if B is a prime attribute
IS
variables;
BEGIN
//statements;
END;
The most important part is parameters. Parameters are used to pass values to the
Procedure. There are 3 different types of parameters, they are as follows:
1. IN:
This is the Default Parameter for the procedure. It always receives the values
from calling program.
2. OUT:
This parameter always sends the values to the calling program.
3. IN OUT:
This parameter performs both the operations. It Receives value from as well
as sends the values to the calling program.
Example:
Imagine a table named with emp_table stored in Database. We are Writing a
Procedure to update a Salary of Employee with 1000.
IS
BEGIN
COMMIT;
END;
VARIABLE v NUMBER;
Execution of the Procedure:
UPPER: The purpose of this function is to return the string in uppercase. It takes a string as
an argument and returns the string by converting it into uppercase.
Syntax:
UPPER('string')
INITCAP: The purpose of this function is to return the string with the first letter in
uppercase and the rest of the letters in lowercase.
Syntax: INITCAP('string')
What is the use of CREATE, INSERT INTO, UPDATE and DELETE Clauses?
1. CREATE Clause
There are two CREATE statements available in SQL:
0. CREATE DATABASE
1. 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 university.
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 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 the CREATE TABLE
statement to create tables in SQL.
Syntax:
This query will create a table named Student. The ROLL_NO and AGE field is
of type int. The next two columns NAME and ADDRESS are of type varchar
and can store characters and the size 20 specifies that these two fields can
hold a maximum of 20 characters.
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:
0. Only values: First method is to specify only the value of data to be
inserted without the column names.
Syntax
3. UPDATE Clause
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.
4. DELETE Clause
Basic Syntax
The Student table will look like this after deleting ALLEN's record.
Syntax:
Columnname_2 datatype,
Columnname_n datatype);
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
Queries
Sample Table:
Student
ROLL_NONAM
E 1 Ram
2 Abhi
3 Rahul 4 Tanu
QUERY:
ROLL_NONAMEAGECOURS
E 1 Ram
2 Abhi
3 Rahul
4 Tanu
ROLL_NONAMEAG
E 1 Ram
2 Abhi
3 Rahul
4 Tanu
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;
To see the data in the View, we can query the view in the same manner as we query a
table.
OUTPUT
Output:
• INNER JOIN
• LEFT JOIN
• RIGHT JOIN
• FULL JOIN
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 the same.
Syntax:
2. SELECT table1.column1,table1.column2,table2.column1,....
3. FROM table1
5. ON table1.matching_column = table2.matching_column;
6. table1: First table.
o This query will show the names and age of students enrolled in
different courses.
ON Student.ROLL_NO = StudentCourse.ROLL_NO;
o
Output:
9. 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 the join. The rows
for which there is no matching row on the right side, the result-set will
contain null. LEFT JOIN is also known as LEFT OUTER JOIN. Syntax:
10. SELECT table1.column1,table1.column2,table2.column1,....
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:
17. 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 the
left side, the result-set will contain null. RIGHT JOIN is also known as RIGHT
OUTER JOIN.
Syntax:
Note: We can also use RIGHT OUTER JOIN instead of RIGHT JOIN, both
are the same.
Example Queries(RIGHT JOIN):
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Output:
25. FULL JOIN: FULL JOIN creates the result-set by combining results 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:
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Output:
Important Points:
This returns the Average Age for each address present in Students Table.
What are Aggregate Functions?
Return number of Non Null values over the column age. i.e 5.
Return number of distinct Non Null values over the column age .i.e 4
Return minimum non null value over the column age. i.e 18.
Return maximum non null value over the column age. i.e 21.
1. Implicit Cursors: Implicit Cursors are also known as Default Cursors of SQL
SERVER. These Cursors are allocated by SQL SERVER when the user
performs DML operations.
2. Explicit Cursors : Explicit Cursors are Created by Users whenever the user
requires them. Explicit Cursors are used for Fetching data from Table in Row-
By-Row Manner.
How to create Explicit Cursor:
OPEN s1
3. Fetch Data from cursor. There are total 6 methods to access data from
cursor. They are as follows :
FIRST is used to fetch only the first row from cursor table.
LAST is used to fetch only last row from cursor table.
NEXT is used to fetch data in forward direction from cursor table.
PRIOR is used to fetch data in backward direction from cursor table.
ABSOLUTE n is used to fetch the exact nth row from cursor table.
RELATIVE n is used to fetch the data in incremental way as well as
decremental way.
Syntax : FETCH NEXT/FIRST/LAST/PRIOR/ABSOLUTE n/RELATIVE n
FROM cursor_name
CLOSE s1
DEALLOCATE s1
1. View:
A view is a virtual table that not actually exist in the database but it can be
produced upon request by a particular user. A view is an object that gives the user a
logical view of data from a base table we can restrict to what user can view by
allowing them to see an only necessary column from the table and hide the other
database details. View also permits users to access data according to their
requirements, so the same data can be access by a different user in a different way
according to their needs.
2Cursor : A cursor is a temporary work area created in memory for processing and
storing the information related to an SQL statement when it is executed. The
temporary work area is used to store the data retrieved from the database and
manipulate data according to need. It contains all the necessary information on data
access by the select statement. It can hold a set of rows called active set but can
access only a single row at a time. There are two different types of cursors -
1. Implicit Cursor
2. Explicit Cursor
S.No.View Cursor
A view is a virtual table that gives logical view of A cursor is a temporary workstation create in database
1. server when SQL statement is executed.
data from base table.
Views are dynamic in nature which means any
2. changes made in base table are immediately Cursor can be static as well as dynamic in nature.
reflected in view.
• BETWEEN Clause
Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
• IN Clause
IN operator allows you to easily test if the expression matches any value in
the list of values. It is used to remove the need of multiple OR condition in
SELECT, INSERT, UPDATE or DELETE. You can also use NOT IN to exclude
the rows in your list.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (list_of_values);
Example : Query to get Student Records, Where Student's age is in the set
{18,20,21}.
Example : Query to get Student Records, Where Student's age is not in the
set {18,20,21}.
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 anymore.
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 that can uniquely identify each row in a
table. And this constraint is used to specify a field in a table as the primary key.
FOREIGN KEY: A Foreign key is a field that can uniquely identify each row in
another table. And this constraint is used to specify a field as a 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.
2. 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 column in a table.
For example, the below query creates a table Student where the field ID is specified
as UNIQUE. i.e, no two students can have the same ID. Unique constraint in detail.
3. PRIMARY KEY –
Primary Key is a field that uniquely identifies each row in the table. If a field in a
table is the primary key, then the field will not be able to contain NULL values as
well as all the rows should have unique values for this field. So, in other words, we
can say that this is a combination of NOT NULL and UNIQUE constraints.
A table can have only one field as a primary key. The below query will create a
table named Student and specifies the field ID as a primary key.
CREATE TABLE Student
(
ID int(6) NOT NULL UNIQUE,
NAME varchar(10),
ADDRESS varchar(20),
PRIMARY KEY(ID)
);
4. FOREIGN KEY –
Foreign Key is a field in a table that uniquely identifies each row of another table.
That is this field points to the primary key of another table. This usually creates a
kind of link between the tables.
Consider the two tables as shown below:
Orders
O_IDORDER_NOC_ID
1 225 3
2 3 3
3 332 2
4 5 1
452
1
852
Customers 3
C_ID NAME ADDRESS
1 RAMESH DELHI
2 SURESH NOIDA
3 DHARMESHGURGAON
As we can see clearly that the field C_ID in the Orders table is the primary key in
the Customers table, i.e. it uniquely identifies each row in the Customers table.
Therefore, it is a Foreign Key in the Orders table.
Syntax:
(i) 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
(ii) 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.
What is a TRIGGER?
A trigger is a stored procedure in database which automatically invokes whenever
a special event in the database occurs. For example, a trigger can be invoked when
a row is inserted into a specified table or when certain table columns are being
updated.
Syntax:
create trigger [trigger_name]
[before | after]
{insert | update | delete}
on [table_name]
[for each row]
[trigger_body]
Explanation of syntax:
Example:
Given Student Report Database, in which student marks assessment is recorded. In
such schema, create a trigger so that the total and average of specified marks is
automatically inserted whenever a record is insert.
Here, as trigger will invoke before record is inserted so, BEFORE Tag can be used.
Suppose the database Schema –
SOLUTION
create trigger stud_marks
before INSERT
on
Student
for each row
set Student.total = Student.subj1 + Student.subj2 + Student.subj3,
Student.per = Student.total * 60 / 100;
Above SQL statement will create a trigger in the student database in which
whenever subjects marks are entered, before inserting this data into the database,
trigger will compute those two values and insert with the entered values. I.e.,
mysql> insert into Student values(0, "ABCDE", 20, 20, 20, 0, 0);
Query OK, 1 row affected (0.09 sec)
mysql> select * from Student;
+-----+-------+-------+-------+-------+-------+------+
| tid | name | subj1 | subj2 | subj3 | total | per |
+-----+-------+-------+-------+-------+-------+------+
| 100 | ABCDE | 20 | 20 | 20 | 60 | 36 |
+-----+-------+-------+-------+-------+-------+------+
1 row in set (0.00 sec)
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.
SELECT *
FROM Students
LIMIT 3;
Output of the query gives First three Student Records.
SELECT *
FROM Students
ORDER BY age
LIMIT 3;
Output of the query gives three Student Records in order of Ascending Ages.
The LIMIT operator can be used in situations such as the above, where we need to
find the top N students in a class and based on any condition statements.
SELECT *
FROM Students
LIMIT 3 OFFSET 2
ORDER BY roll_no;
Arithmetic operators:
Logical operators:
The Logical operators are those that are true or false. They return true or false values to
combine one or more true or false values.
Special operators:
@PREMMANDAL
BUSINESS & DATA ANALYST