Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 191

SQL (STRUCTURED QUERY LANGUAGE)

What is SQL(SEQUEL)?
 SQL stands for Structured Query Language.
(Structured=Fixed Data Model(Tables/Relations) / Language=It is use to communicate with Databases).
(SEQUEL= Structured English Query Language. (SQL was developed by IBM Computer Scientists in the
1970s.)).
 SQL is a standard programming language used to interact with relational database management systems.
 It is especially useful in handling organized data comprised of entities (variables) and relations between
different entities of the data.

It is used to perform CRUD operations:


 Create
 Read
 Update
 Delete

What is a Query?

 A query is a request for data or information from a database table or combination of tables.
 A database query can be either a select query or an action query.

What is DATA:

"Data is a raw-fact which describes the attributes of an Entity ".


Data is basically a collection of facts related to some object.
What is Data Integrity?
 Data Integrity is the assurance of accuracy and consistency of data over its entire life-cycle and is a critical
aspect of the design, implementation, and usage of any system which stores, processes, or retrieves data.
 It also defines integrity constraints to enforce business rules on the data when it is entered into an application
or a database.

DATABASE:

"Database is a place or a medium in which we store the data in a Systematic and organized manner "
 A database is an organized collection of data, stored and retrieved digitally from a remote or local computer system.
 Databases can be vast and complex, and such databases are developed using fixed design and modelling approaches.

 A software application used to manage our DB is called DBMS


(Database Management System)

 The basic operations that can be performed on a database are

 CREATE / INSERT
 READ / RETRIEVE
 UPDATE / MODIFY
 DELETE / DROP

 These operations are referred as "CRUD" Operations.


TYPES OF DATABASES:

 Relational & Non-relational:

 Relational: Stores data in the form of table.


 E.g.: MySQL, PostgreSQL, MariaDB, Microsoft SQL Server, Microsoft Access SQLite, IBM Informix,
Apache Derby, H2 Database Engine, Amazon Relational Database Service (Amazon RDS), Sybase ASE,
DB2and Oracle Database.

 Non-relational(NoSQL): A NoSQL database has a dynamic schema for unstructured data.


 Data may be stored as simple key/value pairs, document-oriented, column-oriented, as JSON documents, or
as a graph consisting of edges and vertices.
 E.g.: MongoDB, NoSQL, Amazon Dynamo DB, Apache Cassandra, HBase, Apache CouchDB, Riak,
Amazon Simple DB, Redis, Neo4J, and Lotus Notes.

What is the difference between SQL and MySQL?

 SQL is a standard language for retrieving and manipulating structured databases.


 On the contrary, MySQL is a relational database management system, like SQL Server, Oracle or IBM
DB2, that is used to manage SQL databases.
Sr.
SQL MySQL
No.

It is a relational database management system


It is a structured query programming
that uses SQL. It supports all the basic
language that manages the relational
programming languages like C, C++, Perl, PHP,
database management system.
1. Python, and Ruby.

MySQL is an open-source platform. It allows


It is not an open-source language.
2. access to anyone.

In a structured query language syntax and


It is software hence it does not have any
format are fixed and easy to use. It starts
commands or a particular format.
3. with the clause and ends with a semicolon.

It supports only a single storage engine for MySQL supports different storage engines for
4. different operations. different functions and operations.

It supports user-defined functions and It does not support any user-defined function and
5. XML. XML.

SQL servers are secured as no third party MySQL is not secure due to its open-source
or outsiders are allowed to manipulate nature. It gives access to data manipulation and
6. data. modification to unauthorized users.

In SQL, the server and database work MySQL servers do not work independently from
7. independently. databases.

8. It is available in many languages. It is available only in simple English language.

It supports connectors like Workbench Tool for


It does not support any connectors.
9. building databases.

SQL follows a simple standard format MySQL has numerous variants and gets frequent
10. without many or regular updates. updates.

SQL NoSQL

RELATIONAL DATABASE MANAGEMENT Non-relational or distributed database


SYSTEM (RDBMS) system.
SQL NoSQL

These databases have fixed or static or predefined


They have a dynamic schema
schema

These databases are not suited for hierarchical data These databases are best suited for
storage. hierarchical data storage.

These databases are not so good for


These databases are best suited for complex queries
complex queries

Vertically Scalable Horizontally scalable

Follows ACID property (Atomicity, Consistency, Follows CAP(consistency, availability,


Isolation, and Durability) partition tolerance)

Examples: MySQL, PostgreSQL, Oracle, MS-SQL Examples: MongoDB, HBase, Neo4j,


Server, etc. Cassandra, etc.

Creating our First Database


 SHOW DATABASES;

 SELECT NAME FROM sys. databases;

To use Databases:
MYSQL use db_name;
SQL SERVERDrop down/In query.
 CREATE DATABASE db_name;
 CREATE DATABASE IF NOT EXISTS db_name;

 DROP DATABASE db_name;


 DROP DATABASE IF EXISTS db_name;

DATABASE MANAGEMENT SYSTEM (DBMS):

"It is a software which is used to maintain and manage


The database "

 DBMS stands for Database Management System. DBMS is a system software responsible for the creation,
retrieval, updation, and management of the database.
 It ensures that our data is consistent, organized, and is easily accessible by serving as an interface between the
database and its end-users or application software.

 Security and authorization are the two important features


that DBMS provides.
Software
QUERY
LANGUAGE Data

Database
DBMS

 We use query language to communicate or interact with DBMS


 DBMS stores the data in the form of files.

RELATIONAL DATABASE MANAGEMENT SYSTEM


(RDBMS):

What is RDBMS? How is it different from DBMS?

 RDBMS stands for Relational Database Management System.


 The key difference here, compared to DBMS, is that RDBMS stores data in the form of a collection of tables,
and relations can be defined between the common fields of these tables.
 Most modern database management systems like MySQL, Microsoft SQL Server, Oracle, IBM DB2, and
Amazon Redshift are based on RDBMS.

"It is a type of DBMS software in which we store the data in the form of Tables (Rows & Columns) ".

• We use SQL to communicate or interact with RDBMS


• RDBMS stores the data in the form of Tables.
• Example: Names
A
B
C
D
E
RELATIONAL MODEL:

 Relational Model was designed by E.F CODD.


 In Relational Model we can store the data in the form of tables.
 Any DBMS which follows Relational Model becomes RDBMS.

Rules of E.F CODD.

1. The data entered into a cell must always be a single valued data.

EID ENAME PHONE_NO


1 SMITH 101
2 ALLEN 102 , 202
3 CLARK 103

EID ENAME PHONE_NO ALTERNATE NO


1 SMITH 101
2 ALLEN 102 202
3 CLARK 103

2. According to E.F CODD we can store the data in Multiple Tables, if needed we can establish a
connection between the tables with the Help of Key Attribute.

3. In RDBMS we store everything in the form of tables including


Metadata (Metadata: The details about a data is knows as Metadata.).
TABLE(RELATIONS):

"It is a logical organization of data which consists of Columns &Rows.


 A table is an organized collection of data stored in the form of rows and columns. Columns can be categorized as
vertical and rows as horizontal. The columns in a table are called fields while the rows can be referred to as records.
Column defines the structure/schema(design) and rows define the individual data.

4. The data entered into the table can be validated in 2 steps.


i. By assigning Datatypes.
ii. By assigning Constraints.
Datatypes are mandatory, whereas Constraints Are Optional.
Creating our First Table:
SHOW TABLES;

Select & View ALL columns  SELECT * FROM table_name;

USE db_name;

CREATE TABLE table_name


(column_name1 datatype constraint,
column_name2 datatype constraint,
column_name2 datatype constraint);

Insert INSERT INTO table_name (colname1, colname2); VALUES (col1_v1, col2_v1), (col1_v2, col2_v2);
INSERT INTO table_name VALUES (col1_v1, col2_v1), (col1_v2, col2_v2);

Update (to update existing rows)

UPDATE table_name SET col1 = val1, col2 = val2 WHERE condition;

Delete (to delete existing rows)

DELETE FROM table_name WHERE condition;


Alter (to change the schema)

ADD Column

ALTER TABLE table_name


ADD COLUMN column_name datatype constraint;

DROP Column

ALTER TABLE table_name DROP COLUMN column_name;

RENAME Table

ALTER TABLE table_name RENAME TO new_table_name;

CHANGE Column (rename)

ALTER TABLE table_name CHANGE COLUMN old_name new_name new_datatype new_constraint;

MODIFY Column (modify datatype/ constraint)

ALTER TABLE table_name MODIFY col_name new_datatype new_constraint;


Truncate (to delete table's data)

TRUNCATE TABLE table_name ;

What is a View?
 A view in SQL is a virtual table based on the result-set of an SQL statement.
 A view contains rows and columns, just like a real table.
 The fields in a view are fields from one or more real tables in the database.
DATATYPES:

 It is used to specify or determine the type of data that will be stored in a particular memory location.

 They define the type of values that can be stored in a column.

Note: Data types might have different names in different database. And even if the name is the same, the size and
other details may be different! Always check the documentation!

For every database, data types are primarily classified into three categories.
 Numeric Datatypes.
 Date and Time Database.
 String Database.
Like in other programming languages, SQL also has certain datatypes available. A brief idea of all the datatypes is
discussed below.

DATATYPES IN SQL:

1. CHAR
2. VARCHAR / VARCHAR2
3. DATE
4. NUMBER
5. LARGE OBJECTS
i. Character Large Object.
ii. Binary Large Object.

NOTE: SQL is not a Case Sensitive Language .

1. CHAR: In character datatype we can store 'A-Z', 'a-z', '0-9' And Special Characters ($, @, &, !
…).


Characters must always be enclosed within single quotes ' '.

Whenever we use char datatype we must mention size

Size: it is used to specify number of characters it can store.
 The maximum number of characters it can store is 2000 character.


Char follows fixed length memory allocation.
2. VARCHAR: In varchar datatype we can store 'A-Z' , 'a-z' , '0-9' And Special Characters( $ , & , @ , !
…).

○ Characters must always be enclosed within single quotes ' '.


○ Whenever we use char datatype we must mention size
○ Size: it is used to specify number of characters it can store.
 The maximum number of characters it can store is
2000ch.
○ VarChar follows variable length memory allocation.

Example:

STUDENT

USN SNAME ADDRESS PAN_NO


CHAR(4) VARCHAR(10) VARCHAR(10) CHAR(10)
QSP1 DINGA BANGALORE ABC123XYZ1
QSP2 DINGI MYSORE ABC123XYZ2

3. NUMBER: It is used to store numeric values.

SYNTAX: NUMBER (Precision, [Scale])


[] - Not Mandatory.

Precision: it is used to determine the number of digits used to store integer


value.

Scale: it is used to determine the number of digits used to store Decimal


(floating) value within the precision.

 Scale is not mandatory, and the default value of scale Is zero (0).

Example : Number ( 3 ) +/- 999


Example : Number ( 5 , 0 ) +/- 99999
Example : Number ( 5 , 2 ) +/- 999.99
Example : Number ( 7 , 3 ) +/- 9999.999
Example : Number ( 4 , 4 ) +/- .9999
Example : Number ( 5 , 4 ) +/- 9.9999
Example : Number ( 3 , 6 ) +/- .000999
Example : Number ( 5 , 8 ) +/- .00099999
Example : Number ( 2 , 7 ) +/- .0000099

EID PHONE_NO SALARY


Number( 3 ) Number ( 10 ) Number ( 7 , 2 )
101 9876543210 9000.85

4. DATE: it is used to store dates in a particular format.

It used Oracle specified Format.

'DD-MON-YY' OR 'DD-MON-YYYY'
'22-JUN-20' '22-JUN-2020'

SYNTAX: DATE
5. Large Object

1. Character large object ( CLOB ) :

It is used to store characters up to 4 GB of size.

2. Binary large object (BLOB):

It is used to store binary values of images, mp3, mp4


Documents etc. …. Up to 4GB of size.

SQL Datatypes

Signed & Unsigned

TINYINT UNSIGNED (0 to 255)


TINYINT (-128 to 127)
===============================================================================
===============================================================================
MySQL Data Types (Version 8.0)

In MySQL there are three main data types: string, numeric, and date and time.

String Data Types

Data type Description

CHAR(size) A FIXED length string (can contain letters, numbers, and special characters).
The size parameter specifies the column length in characters - can be from 0 to 255.
Default is 1

VARCHAR(size) A VARIABLE length string (can contain letters, numbers, and special characters).
The size parameter specifies the maximum string length in characters - can be from
0 to 65535

BINARY(size) Equal to CHAR (), but stores binary byte strings. The size parameter specifies the
column length in bytes. Default is 1

VARBINARY(size) Equal to VARCHAR (), but stores binary byte strings. The size parameter specifies
the maximum column length in bytes.

TINYBLOB For BLOBs (Binary Large Objects). Max length: 255 bytes

TINYTEXT Holds a string with a maximum length of 255 characters

TEXT(size) Holds a string with a maximum length of 65,535 bytes

BLOB(size) For BLOBs (Binary Large Objects). Holds up to 65,535 bytes of data

MEDIUMTEXT Holds a string with a maximum length of 16,777,215 characters


MEDIUMBLOB For BLOBs (Binary Large Objects). Holds up to 16,777,215 bytes of data

LONGTEXT Holds a string with a maximum length of 4,294,967,295 characters

LONGBLOB For BLOBs (Binary Large Objects). Holds up to 4,294,967,295 bytes of data

ENUM(val1, val2, val3, ...) A string object that can have only one value, chosen from a list of possible values.
You can list up to 65535 values in an ENUM list. If a value is inserted that is not in
the list, a blank value will be inserted. The values are sorted in the order you enter
them

SET(val1, val2, val3, ...) A string object that can have 0 or more values, chosen from a list of possible
values. You can list up to 64 values in a SET list

Numeric Data Types

Data type Description

BIT(size) A bit-value type. The number of bits per value is specified in size.
The size parameter can hold a value from 1 to 64. The default value for size is 1.

TINYINT(size) A very small integer. Signed range is from -128 to 127. Unsigned range is from 0 to
255. The size parameter specifies the maximum display width (which is 255)

BOOL Zero is considered as false, nonzero values are considered as true.

BOOLEAN Equal to BOOL


SMALLINT(size) A small integer. Signed range is from -32768 to 32767. Unsigned range is from 0 to
65535. The size parameter specifies the maximum display width (which is 255)

MEDIUMINT(size) A medium integer. Signed range is from -8388608 to 8388607. Unsigned range is
from 0 to 16777215. The size parameter specifies the maximum display width
(which is 255)

INT(size) A medium integer. Signed range is from -2147483648 to 2147483647. Unsigned


range is from 0 to 4294967295. The size parameter specifies the maximum display
width (which is 255)

INTEGER(size) Equal to INT(size)

BIGINT(size) A large integer. Signed range is from -9223372036854775808 to


9223372036854775807. Unsigned range is from 0 to 18446744073709551615.
The size parameter specifies the maximum display width (which is 255)

FLOAT(size, d) A floating point number. The total number of digits is specified in size. The number
of digits after the decimal point is specified in the d parameter. This syntax is
deprecated in MySQL 8.0.17, and it will be removed in future MySQL versions

FLOAT(p) A floating point number. MySQL uses the p value to determine whether to use
FLOAT or DOUBLE for the resulting data type. If p is from 0 to 24, the data type
becomes FLOAT(). If p is from 25 to 53, the data type becomes DOUBLE()

DOUBLE(size, d) A normal-size floating point number. The total number of digits is specified in size.
The number of digits after the decimal point is specified in the d parameter

DOUBLE PRECISION(size, d)

DECIMAL(size, d) An exact fixed-point number. The total number of digits is specified in size. The
number of digits after the decimal point is specified in the d parameter. The
maximum number for size is 65. The maximum number for d is 30. The default
value for size is 10. The default value for d is 0.

DEC(size, d) Equal to DECIMAL(size,d)

Note: All the numeric data types may have an extra option: UNSIGNED or ZEROFILL. If you add the UNSIGNED
option, MySQL disallows negative values for the column. If you add the ZEROFILL option, MySQL automatically also
adds the UNSIGNED attribute to the column.

Date and Time Data Types

Data type Description

DATE A date. Format: YYYY-MM-DD. The supported range is from '1000-01-01' to


'9999-12-31'

DATETIME(fsp) A date and time combination. Format: YYYY-MM-DD hh:mm:ss. The


supported range is from '1000-01-01 00:00:00' to '9999-12-31 23:59:59'. Adding
DEFAULT and ON UPDATE in the column definition to get automatic
initialization and updating to the current date and time

TIMESTAMP(fsp) A timestamp. TIMESTAMP values are stored as the number of seconds since
the Unix epoch ('1970-01-01 00:00:00' UTC). Format: YYYY-MM-DD
hh:mm:ss. The supported range is from '1970-01-01 00:00:01' UTC to '2038-01-
09 03:14:07' UTC. Automatic initialization and updating to the current date and
time can be specified using DEFAULT CURRENT_TIMESTAMP and ON
UPDATE CURRENT_TIMESTAMP in the column definition

TIME(fsp) A time. Format: hh:mm:ss. The supported range is from '-838:59:59' to


'838:59:59'

YEAR A year in four-digit format. Values allowed in four-digit format: 1901 to 2155,
and 0000.
MySQL 8.0 does not support year in two-digit format.
SQL Server Data Types
String Data Types

Data type Description Max size Storage

char(n) Fixed width character string 8,000 characters Defined width

varchar(n) Variable width character 8,000 characters 2 bytes + number of


string chars

varchar(max) Variable width character 1,073,741,824 2 bytes + number of


string characters chars

text Variable width character 2GB of text data 4 bytes + number of


string chars

nchar Fixed width Unicode string 4,000 characters Defined width x 2

nvarchar Variable width Unicode 4,000 characters


string

nvarchar(max) Variable width Unicode 536,870,912 characters


string

ntext Variable width Unicode 2GB of text data


string
binary(n) Fixed width binary string 8,000 bytes

varbinary Variable width binary string 8,000 bytes

varbinary(max) Variable width binary string 2GB

image Variable width binary string 2GB

Numeric Data Types

Data type Description Storage

bit Integer that can be 0, 1, or NULL

tinyint Allows whole numbers from 0 to 255 1 byte

smallint Allows whole numbers between -32,768 and 32,767 2 bytes

int Allows whole numbers between -2,147,483,648 and 2,147,483,647 4 bytes

bigint Allows whole numbers between -9,223,372,036,854,775,808 and 8 bytes


9,223,372,036,854,775,807

5-17 bytes
decimal(p,s) Fixed precision and scale numbers.

Allows numbers from -10^38 +1 to 10^38 –1.

The p parameter indicates the maximum total number of digits that can be
stored (both to the left and to the right of the decimal point). p must be a value
from 1 to 38. Default is 18.

The s parameter indicates the maximum number of digits stored to the right of
the decimal point. s must be a value from 0 to p. Default value is 0

numeric(p,s) Fixed precision and scale numbers. 5-17 bytes

Allows numbers from -10^38 +1 to 10^38 –1.

The p parameter indicates the maximum total number of digits that can be
stored (both to the left and to the right of the decimal point). p must be a value
from 1 to 38. Default is 18.

The s parameter indicates the maximum number of digits stored to the right of
the decimal point. s must be a value from 0 to p. Default value is 0

smallmoney Monetary data from -214,748.3648 to 214,748.3647 4 bytes

money Monetary data from -922,337,203,685,477.5808 to 922,337,203,685,477.5807 8 bytes

float(n) Floating precision number data from -1.79E + 308 to 1.79E + 308. 4 or 8 bytes

The n parameter indicates whether the field should hold 4 or 8 bytes. float(24)
holds a 4-byte field and float(53) holds an 8-byte field. Default value of n is
53.

real Floating precision number data from -3.40E + 38 to 3.40E + 38 4 bytes

Date and Time Data Types

Data type Description Storage

datetime From January 1, 1753 to December 31, 9999 with an accuracy of 3.33 8 bytes
milliseconds

datetime2 From January 1, 0001 to December 31, 9999 with an accuracy of 100 nanoseconds 6-8 bytes

smalldatetime From January 1, 1900 to June 6, 2079 with an accuracy of 1 minute 4 bytes
date Store a date only. From January 1, 0001 to December 31, 9999 3 bytes

time Store a time only to an accuracy of 100 nanoseconds 3-5 bytes

datetimeoffset The same as datetime2 with the addition of a time zone offset 8-10 bytes

timestamp Stores a unique number that gets updated every time a row gets created or
modified. The timestamp value is based upon an internal clock and does not
correspond to real time. Each table may have only one timestamp variable

Other Data Types

Data type Description

sql_variant Stores up to 8,000 bytes of data of various data types, except text, ntext, and timestamp

uniqueidentifier Stores a globally unique identifier (GUID)

xml Stores XML formatted data. Maximum 2GB

cursor Stores a reference to a cursor used for database operations

table Stores a result-set for later processing


MS Access Data Types
Data type Description Storage

Text Use for text or combinations of text and numbers. 255 characters maximum

Memo Memo is used for larger amounts of text. Stores up to 65,536


characters. Note: You cannot sort a memo field. However, they are searchable

Byte Allows whole numbers from 0 to 255 1 byte

Integer Allows whole numbers between -32,768 and 32,767 2 bytes

Long Allows whole numbers between -2,147,483,648 and 2,147,483,647 4 bytes

Single Single precision floating-point. Will handle most decimals 4 bytes

Double Double precision floating-point. Will handle most decimals 8 bytes

Currency Use for currency. Holds up to 15 digits of whole dollars, plus 4 decimal 8 bytes
places. Tip: You can choose which country's currency to use

AutoNumber AutoNumber fields automatically give each record its own number, usually 4 bytes
starting at 1

Date/Time Use for dates and times 8 bytes

Yes/No A logical field can be displayed as Yes/No, True/False, or On/Off. In code, use 1 bit
the constants True and False (equivalent to -1 and 0). Note: Null values are not
allowed in Yes/No fields

Ole Object Can store pictures, audio, video, or other BLOBs (Binary Large Objects) up to 1GB

Hyperlink Contain links to other files, including web pages

Lookup Wizard Let you type a list of options, which can then be chosen from a drop-down list 4 bytes

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

Numeric Data Types in MYSQL


Exact Numeric Datatype
There are nine subtypes which are given below in the table. The table contains the range of data in a particular
type.
Data Type From To

BigInt -263 (-9,223,372,036,854,775,808) 263 -1 (9,223,372,036,854,775,807)

Int -231 (-2,147,483,648) 231-1 (2,147,483,647)

smallint -215 (-32,768) 215-1 (32,767)

tinyint 0 28-1 (255)

bit 0 1

decimal -1038+1 1038-1

numeric -1038+1 1038-1

money -922,337,203,685,477.5808 922,337,203,685,477.5807


Data Type From To

smallmoney -214,748.3648 214,748.3647

Approximate Numeric Datatype


The subtypes of this datatype are given in the table with the range.
Data Type From To

Float -1.79E+308 1.79E+308

Real -3.40E+38 3.40E+38

String Data Types in MYSQL


Character String Datatype
The subtypes are given in below table –
Data Type Description

char The maximum length of 8000 characters.(Fixed-Length non-Unicode Characters)

The maximum length of 8000 characters.(Variable-Length non-Unicode


varchar
Characters)

The maximum length of 231 characters(SQL Server 2005 only).(Variable Length


varchar(max)
non-Unicode data)

The maximum length of 2,127,483,647 characters(Variable Length non-Unicode


text
data)

Unicode Character String Datatype


The details are given in below table –
Data Type Description

nchar The maximum length of 4000 characters(Fixed-Length Unicode Characters)

Nvarchar The maximum length of 4000 characters.(Variable-Length Unicode Characters)

The maximum length of 231 characters(SQL Server 2005 only).(Variable Length


nvarchar(max)
Unicode data)

Server String Data Type in SQL


There are four subtypes of this datatype which are given below:
Datatypes Description

Binary The maximum length of 8000 bytes(Fixed-Length binary data)


Datatypes Description

varbinary The maximum length of 8000 bytes(Variable Length binary data)

varbinary(max) The maximum length of 231 bytes(SQL Server 2005 only).(Variable Length binary data)

text Maximum Length of 2,147,483,647 bytes(Variable Length binary data)

Server Date and Time Data Type in SQL


The details are given in the below table.
Data Type Description

DATE A data type is used to store the data of date in a record

TIME A data type is used to store the data of time in a record

DATETIME A data type is used to store both the data,date, and time in the record.

Other Data Types


XML Datatype
XML data type allows storage of XML documents and fragments in a SQL Server database
DataType Description

XML Datatype A Datatype used to store data in the format of XML datatype

Spatial Dataype
A datatype is used for storing planar spatial data, such as points, lines, and polygons, in a database table.
DataType Description

A datatype is used for storing planar spatial data, such as points, lines, and polygons, in a
Geometry
database table.

Array Datatype
SQL Server does not have a built-in array datatype. However, it is possible to simulate arrays using tables or XML
data types.
This text discusses the properties of data types in MYSQL.
SQL data types define the type of data that can be stored in a database column or variable. Here are the most
common SQL data types:
Datatype Properties

Numeric data These are used to store numeric values. Examples include INT, BIGINT,
types DECIMAL, and FLOAT.

Character data These are used to store character strings. Examples include CHAR, VARCHAR,
types and TEXT.
Datatype Properties

Date and time These are used to store date and time values. Examples include DATE, TIME,
data types and TIMESTAMP

These are used to store binary data, such as images or audio files. Examples
Binary data types
include BLOB and BYTEA.

This data type is used to store logical values. The only possible values are
Boolean data type
TRUE and FALSE.

Interval data These are used to store intervals of time. Examples include INTERVAL YEAR,
types INTERVAL MONTH, and INTERVAL DAY.

Array data types These are used to store arrays of values. Examples include ARRAY and JSON.

XML data type This data type is used to store XML data.

These are used to store geometric or geographic data. Examples include POINT,
Spatial data types
LINE, and POLYGON.

Different databases may have different variations of these data types, or they may have additional data types not
listed here. Understanding SQL data types are important for creating tables and working with data in a database, as
it affects how data is stored and processed.

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

===============================================================================
===============================================================================

CONSTRAINTS:
What are Constraints in SQL?

It is a rule given to a column for validation.


SQL constraints are used to specify rules for data in a table.
Constraints are used to specify the rules concerning data in the table. It can be applied for single or multiple fields in
an SQL table during the creation of the table or after creating using the ALTER TABLE command.

Types of Constraints:

1. UNIQUE
2. NOT NULL
3. CHECK
4. PRIMARY KEY
5. FOREIGN KEY.

1. UNIQUE: "It is used to avoid duplicate values into the column’’. /all values in column are different/
Ensures unique values to be inserted into the field.

A UNIQUE constraint ensures that all values in a column are different. This provides uniqueness for the column(s)
and helps identify each row uniquely. Unlike primary key, there can be multiple unique constraints defined per table.
The code syntax for UNIQUE is quite similar to that of PRIMARY KEY and can be used interchangeably.

2. NOT NULL: "It is used to avoid Null". /columns cannot have a null value/Restricts NULL value from being
inserted into a column.

3. CHECK: "It is an extra validation with a condition if the condition is satisfied, then the value is accepted
else Rejected’’. Verifies that all values in a field satisfy a condition.

4. DEFAULT - Automatically assigns a default value if no value has been specified for the field.

5. INDEX - Indexes a field providing faster retrieval of records.

A database index is a data structure that provides a quick lookup of data in a column or columns of a table. It
enhances the speed of operations accessing data from a database table at the cost of additional writes and
memory to maintain the index data structure.

 Unique and Non-Unique Index:

 Unique indexes are indexes that help maintain data integrity by ensuring that no two rows of data in a table
have identical key values. Once a unique index has been defined for a table, uniqueness is enforced whenever
keys are added or changed within the index.

 Non-unique indexes, on the other hand, are not used to enforce constraints on the tables with which they are
associated. Instead, non-unique indexes are used solely to improve query performance by maintaining a sorted
order of data values that are used frequently.

 Clustered and Non-Clustered Index:


 Clustered indexes are indexes whose order of the rows in the database corresponds to the order of the rows in
the index. This is why only one clustered index can exist in a given table, whereas, multiple non-clustered
indexes can exist in the table.
 The only difference between clustered and non-clustered indexes is that the database manager attempts to
keep the data in the database in the same order as the corresponding keys appear in the clustered index.
Clustering indexes can improve the performance of most query operations because they provide a linear-
access path to data stored in the database.

 What is the difference between Clustered and Non-clustered index?


As explained above, the differences can be broken down into three small factors –
 Clustered index modifies the way records are stored in a database based on the indexed column. A
non-clustered index creates a separate entity within the table which references the original table.
 Clustered index is used for easy and speedy retrieval of data from the database, whereas, fetching
records from the non-clustered index is relatively slower.
 In SQL, a table can have a single clustered index whereas it can have multiple non-clustered
indexes.

6. PRIMARY KEY: "It is a constraint which is used to identify a record Uniquely from the table./makes a
column unique & not null but used only for one./ Uniquely identifies each record in a table.

It is a column (or set of columns) in a table that uniquely identifies each row. (a unique id)

The PRIMARY KEY constraint uniquely identifies each row in a table. It must contain UNIQUE values and has an
implicit NOT NULL constraint. A table in SQL is strictly restricted to have one and only one primary key, which is
comprised of single or multiple fields (columns)

Characteristics of Primary key:


 We can have only 1 PK in a table
 PK cannot accept duplicate / repeated values.
 PK cannot accept Null
 PK is always a combination of Unique and Not Null Constraint.

7. FOREIGN KEY: "It is used to establish a connection between the tables. /Prevents actions that would
destroy links between tables. / Ensures referential integrity for a record in another table.

A foreign key is a column (or set of columns) in a table that refers to the primary key in another table.
There can be multiple FKs.
FKs can have duplicate & null values.

A FOREIGN KEY comprises of single or collection of fields in a table that essentially refers to the PRIMARY
KEY in another table. Foreign key constraint ensures referential integrity in the relation between two tables.
The table with the foreign key constraint is labeled as the child table, and the table containing the candidate key is
labeled as the referenced or parent table.

Characteristics of Foreign key:


 We can have only Multiple FK in a table
 FK can accept duplicate / repeated values.
 FK can accept Null
 FK is not a combination of Unique and Not Null Constraint.
 For an Attribute (column) to become a FK, it is mandatory That it must be a PK in its own table.

 Cascading for FK:

On Delete Cascade
 When we create a foreign key using this option, it deletes the referencing rows in the child table when the referenced
row is deleted in the parent table which has a primary key.

On Update Cascade
 When we create a foreign key using UPDATE CASCADE the referencing rows are updated in the child table when the
referenced row is updated in the parent table which has a primary key.

Example:

EMP

Primary
key
Check ( Check
Salary >
0) ( length(phone) =
10 )
Not Null Not Null Not Null Not Null Not Null
Unique Unique
EID NAME SALARY DOJ PHONE
Number(2) Varchar(10 Number(7,2) Date Number(10)
)
1 A 10000 '20-JUN-20' 9876543210
2 B 20000 '20-JUN-19' 9876543222
3 C 35000 '01-JAN-18' 9876543333
4 D 50000 '01-OCT- 9876511111
19'

Example for Foreign Key

EID NAME SALAR DN F CID


Y O K FK
1 A 10000 20 2
2 B 20000 10 3
3 C 35000 20 1
4 D 50000 10 2

Child Table

CID CNAME CNO DNO DNAME LOC


1 X 1001 10 D1 L1
2 Y 2002 20 D2 L2
3 Z 3003

Parent Tables

1. Differentiate between Primary key and Foreign key.

PRIMARY KEY FOREIGN KEY


It is used to identify a It is used to establish a connection
records Uniquely from the Between the tables
table.
It cannot accept Null It can accept Null
It cannot accept duplicate values It can accept duplicate values
It is always a combination of It is not a combination of
Not Null and Unique constraint Not Null and Unique constraint
We can have only 1 PK in a table We can have Multiple FK in a table

NOTE: NULL
Null Is a keyword which is used to represent Nothing / Empty Cell.

Characteristics of Null:
 Null doesn’t represent 0 or Space.
 Any operations performed on a Null will result in Null itself
Types of SQL Commands:

OVERVIEW OF SQL STATEMENTS:

1. DATA DEFINITION LANGUAGE (DDL)


2. DATA MANIPULATION LANGUAGE (DML)
3. TRANSCATION CONTROL LANGUAGE (TCL)
4. DATA CONTROL LANGUAGE (DCL)
5. DATA QUERY LANGUAGE (DQL)

 DDL (Data Definition Language): create, alter, rename, truncate & drop
 DQL (Data Query Language): select
 DML (Data Manipulation Language): select, insert, update & delete
 DCL (Data Control Language): grant & revoke permission to users
 TCL (Transaction Control Language): start transaction, commit, rollback etc.

 DATA QUERY LANGUAGE (DQL):

" DQL is used to retrieve the data from the database ".

It had 4 statements:

1. SELECT
2. PROJECTION
3. SELECTION
4. JOIN
1. SELECT: "It is used to retrieve the data from the table and display it.
2. PROJECTION: "It is a process of retrieving the data by selecting only the columns is known as Projection ".
In projection all the records / values present in a particular column are by default selected.
3. SELECTION: "It is a process of retrieving the data by selecting both the columns and rows is known as
Selection ".
4. JOIN: “It is a process of retrieving the data from Multiple tables simultaneously is known as Join "

o PROJECTION

"It is a process of retrieving the data by selecting only the columns is known as Projection ".
In projection all the records / values present in a particular column are by default selected.

 "It is a process of retrieving the data by selecting only the columns


is known as Projection ".

 In projection all the records / values present in a particular column


are by default selected.

SYNTAX:
SELECT * / [DISTINCT] Column_Name / Expression [ALIAS] FROM
Table_Name ;

ORDER OF EXECUTION
1. FROM Clause
2. SELECT Clause
NOTE:

 FROM Clause starts the execution.


 For FROM Clause we can pass Table_Name as an argument.
 The job of FROM Clause is to go to the Database and search
for the table and put the table under execution.
 SELECT Clause will execute after the execution of FROM Clause
 For SELECT Clause we pass 3 arguments
⬥*
⬥ Column_Name
⬥ Expression
 The job of SELECT Clause is to go the table under execution
and select the columns mentioned.
 SELECT Clause is responsible for preparing the result table.
 Asterisk (*): it means to select all the columns from the table.
 Semicolon: it means end of the query.

 WAQTD student id and student names for all the students.

SELECT SID , SNAME


FROM STUDENT ;

 WAQTD name and branch of all the students .

SELECT SNAME , BRANCH


FROM STUDENT ;

 WAQTD NAME , BRANCH AND PERCENTAGE FOR ALL


THE STUDENTS .

SELECT SNAME , BRANCH , PER


FROM STUDENT ;
 WAQTD details of all the students from students table .
SELECT *
FROM STUDENT ;

 WAQTD sname , sid , per , branch of all the students .

SELECT SNAME , SID , PER , BRANCH


FROM STUDENT ;
EMP Table :

 WAQTD name salary and commission given to all the employees .

Select ename , sal ,


comm From emp ;

 WAQTD name of the employee along with their date of joining .

Select ename ,
hiredate From emp ;

DEPT :
DEPTNO DNAME LOC
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

 WAQTD dname and location for all the depts .

Select dname ,
loc From dept ;
QUESTIONS ON EMP AND DEPT TABLE:
1. WRITE A QUERY TO DISPLAY ALL THE DETAILS FROM THE EMPLOYEE TABLE.
2. WAQTD NAMES OF ALL THE EMPLOYEES.
3. WAQTD NAME AND SALARY GIVEN TO ALL
THE EMPLOYEES.
4. WAQTD NAME AND COMMISSION GIVEN TO ALL
THE EMPLOYEES.
5. WAQTD EMPLOYEE ID AND DEPARTMENT NUMBER OF
ALL THE EMPLOYEES
IN EMP TABLE.
6. WAQTD ENAME AND HIREDATE OF ALL THE EMPLOYEES.
7. WAQTD NAME AND DESIGNATION OF ALL
THE EMPLPOYEES.
8. WAQTD NAME, JOB AND SALARY GIVEN ALL THE
EMPLOYEES.
9. WAQTD DNAMES PRESENT IN DEPARTMENT TABLE.
10.WAQTD DNAME AND LOCATION PRESENT IN DEPT TABLE.

DISTINCT Clause:
" It is used to remove the duplicate or repeated values from the Result table " .
 Distinct clause has to be used As the first argument to select clause .
 We can use multiple columns As an argument to distinct clause, it will remove the combination of columns in which
the records are duplicated.

Student
SID SNAME BRANCH PER
1 A ECE 60
2 B CSE 75
3 C ME 50
4 D ECE 80
5 C CSE 75
6 E CIVIL 95

 SELECT SNAME
FROM STUDENT ;

SNAM
E
A
B
C
D
C
E

 SELECT DISTINCT SNAME


FROM STUDENT ;

SNAME
SNAME
 SELECT DISTINCT BRANCH
FROM STUDENT ;

BRANCH
ECE BRANCH
CSE ECE
ME CSE
ECE ME
CSE CIVIL
CIVIL

EXPRESSION

"A statement which gives result is known as Expression ".

Expression is a combination Operand and Operator.

Operand: These are the values that we pass.

Operator: These are the Symbols which perform some Operation on


The Operand.

Example: 5 * 10

EMP
EID ENAME SAL
1 A 100
2 B 200
2 C 100

1. WAQTD name and salary given to the employees .

SELECT ENAME , SAL


FROM EMP ;

2. WAQTD name and annual salary of the employees .

SELECT ENAME , SAL * 12


3. FROM EMP ;
ENAME SAL*12
A 1200
B 2400
C 1200
4. WAQTD all the details of the employee along with annual salary
Select eid , ename , sal , sal*12
From emp ;

Select emp.* , sal*12


From emp ;

5. WAQTD name and salary with a hike of 20% .

Select ename , Sal + Sal*20/100


From emp ;

Formulae to calculate percentage :


Sal + Sal * a / 100 Sal * 1.a

6. WAQTD name and salary of an employee with a deduction


Of 10% .

Select ename , sal - sal * 10 /100


From emp ;

ALIAS

"It is an alternate name given to a Column or an Expression


In the result table " .

 An alias is a feature of SQL that is supported by most, if not all,


RDBMSs.
 It is a temporary name assigned to the table or table column for
the purpose of a particular SQL query.
 In addition, aliasing can be employed as an obfuscation
technique to secure the real names of database fields.
 A table alias is also called a correlation name.
 An alias is represented explicitly by the AS keyword but in
some cases, the same can be performed without it as well.
Nevertheless, using the AS keyword is always a good practice.

○ We can assign alias name with or without using


'As' keyword .
○ Alias names have to be a single string which is
separated by An underscore or enclosed within double
quotes .

SELECT A.emp_name AS "Employee" /* Alias using AS keyword */


B.emp_name AS "Supervisor"
FROM employee A, employee B /* Alias without AS keyword */
WHERE A.emp_sup = B.emp_id;
Example : ANNUAL_SALARY
"ANNUAL SALARY"
 WAQTD annual salary for all the employees .

Select sal*12
From emp ;
SAL*12
1200
2400
1200

Select sal*12 Annual_Salary


From emp ;
Annual Salary
1200
2400
1200

Select sal + sal * 10 / 100 Hike


From emp ;

 WAQTD name and salary with a deduction 32% .

Select Ename , sal-sal*32/100 as deduction


From emp ;

ASSIGNMENT ON EXPRESSION & ALIAS

1. WAQTD NAME OF THE EMPLOYEE ALONG WITH


THEIR ANNUAL SALARY.
2. WAQTD ENAME AND JOB FOR ALL THE EMPLOYEE
WITH THEIR HALF TERM SALARY.
3. WAQTD ALL THE DETAILS OF THE EMPLOYEES
ALONG WITH AN ANNUALBONUS OF 2000.
4. WAQTD NAME SALARY AND SALARY WITH A HIKE OF
10%.
5. WAQTD NAME AND SALARY WITH DEDUCTION OF 25%.
6. WAQTD NAME AND SALARY WITH MONTHLY HIKE OF
50.
7. WAQTD NAME AND ANNUAL SALARY WITH
DEDUCTION OF 10%.
8. WAQTD TOTAL SALARY GIVEN TO EACH
EMPLOYEE (SAL+COMM).
9. WAQTD DETAILS OF ALL THE EMPLOYEES ALONG
WITH ANNUAL SALARY.
10. WAQTD NAME AND DESIGNATION ALONG WITH
100 PENALTY IN SALARY.
SELECTION :
"It is a process of retrieving the data by selecting both the
columns and rows is known as Selection " .
SELECT operator in SQL is used to select data from a database. The
data returned is stored in a result table, called the result-set.

SYNTAX :
SELECT * / [DISTINCT] Column_Name / Expression [ALIAS] FROM
Table_Name
WHERE <Filter_Condition> ;

SELECT * FROM myDB.students;

What are some common clauses used with SELECT query in SQL?

Some common SQL clauses used in conjunction with a SELECT query are as follows:
 WHERE clause in SQL is used to filter records that are necessary, based on specific conditions.
 ORDER BY clause in SQL is used to sort the records based on some field(s) in ascending (ASC) or
descending order (DESC).

SELECT * FROM myDB.students


WHERE graduation_year = 2019
ORDER BY studentID DESC;

ORDER OF EXECUTION
1. FROM
2. WHERE
3. SELECT

WHERE Clause

"Where clause is used to filter the records ".


To define some conditions

SELECT col1, col2


FROM table_name
WHERE conditions;

Example :

 WAQTD names of the employees working in dept 20 .


 WAQTD names of the employees getting salary More than 300 .

SELECT ENAME
FROM EMP
WHERE SAL > 300 ;

 WAQTD names and salary of the employees working in dept 10.

SELECT ENAME , SAL


FROM EMP
WHERE DEPTNO = 10 ;

 WAQTD all the details of the employees whose salary


is Less than 1000 rupees .

SELECT *
FROM
EMP
WHERE SAL < 1000 ;
EMP :
 WAQTD name and hiredate of an employee hired
on '09-JUN-1981'

SELECT ENAME , HIREDATE


FROM EMP
WHERE DATE = '09-JUN-1981' ;

 WAQTD details of the employee whose name is 'Miller'

SELECT *
FROM
EMP
WHERE ENAME ='MILLER' ;

 WAQTD details of the employee hired after '01-JAN-1982'

SELECT *
FROM
EMP
WHERE HIREDATE > '01-JAN-1982' > ;

 WAQTD name sal and hiredate of the employees who


were Hired before 1985 .

SELECT ENAME , SAL , HIREDATE


FROM EMP
WHERE HIREDATE < '01-JAN-1985' ;

 WAQTD name sal and hiredate of the employees who


were Hired after 1985 .

SELECT ENAME , SAL , HIREDATE


FROM EMP
WHERE HIREDATE > '31-DEC-1985' ;

 WAQTD name of the employees who was hired on


Valentine's day 2020 .
SELECT ENAME
FROM EMP
WHERE HIREDATE = '14-FEB-2020' ;

ASSIGNMENT ON WHERE Clause .

1. WAQTD THE ANNUAL SALARY OF THE EMPLOYEE


WHOS NAME IS SMITH

2. WAQTD NAME OF THE EMPLOYEES WORKING AS CLERK

3. WAQTD SALARY OF THE EMPLOYEES WHO


ARE WORKING AS SALESMAN

4. WAQTD DETAILS OF THE EMP WHO EARNS MORE THAN


2000

5. WAQTD DETAILS OF THE EMP WHOS NAME IS JONES

6. WAQTD DETAILS OF THE EMP WHO WAS HIRED AFTER


01-JAN-81

7. WAQTD NAME AND SAL ALONG WITH HIS ANNUAL


SALARY IF THE ANNUAL SALARY IS MORE THAN
12000

8. WAQTD EMPNO OF THE EMPLOYEES WHO ARE


WORKING IN DEPT 30

9. WAQTD ENAME AND HIREDATE IF THEY ARE


HIRED BEFORE 1981

10. WAQTD DETAILS OF THE EMPLOYEES WORKING


AS MANAGER

11. WAQTD NAME AND SALARY GIVEN TO AN EMPLOYEE


IF EMPLOYEE EARNS A COMMISSION OF RUPEES 1400

12. WAQTD DETAILS OF EMPLOYEES HAVING


COMMISSION MORE THAN SALARY

13. WAQTD EMPNO OF EMPLOYEES HIRED BEFORE


THE YEAR 87

14. WAQTD DETAILS OF EMPLOYEES WORKING AS AN


N ANALYST

15. WAQTD DETAILS OF EMPS EARNING MORE THAN


2000 RUPEES PER MONTH.

OPERATORS IN SQL

1. ARITHEMATIC OPERATORS :- ( + , - , * , / ) / +(addition) , -(subtraction), *(multiplication), /(division), %


(modulus)
2. CONCATENATION OPERATOR :- ( || )
3. COMPARISION OPERATORS :- ( = , != or <> ) / = (equal to), != (not equal to), > , >= , <=
4. RELATIONAL OPERATOR :- ( > , < , >= , <=
) 5.LOGICAL OP : ( AND , OR , NOT ) /
AND,OR, NOT, IN, BETWEEN, ALL, LIKE,
ANY

6. SPECIAL OPERATOR :-
1.IN
2.NOT IN
3.BETWEEN
4.NOT BETWEEN
5.IS
6.IS NOT
7.LIKE
8.NOT LIKE
7. SUBQUERY OPERATORS:-
1.ALL
2.ANY
3.EXISTS
4.NOT EXISTS

Bitwise Operators : & (Bitwise AND), | (Bitwise OR)

CONCATENATION Operator :

" It is used to join the strings ".

Symbol : ||

Example : SELECT ENAME


FROM EMP
WHERE JOB ='MANAGER' ;

Ename
ALLEN
MARTIN
SMITH

SELECT 'Hi ' || ename


FROM EMP
WHERE JOB ='MANAGER' ;
Ename
Hi ALLEN
Hi MARTIN
Hi SMITH
 WAQTD name and deptno of the employees
hired After '01-JAN-87' .

SELECT ENAME , DEPTNO


FROM EMP
WHERE HIREDATE > '01-JAN-1987' ;

 WAQTD name and hiredate of the employees


hired before 31-JUL-88

SELECT ENAME , HIREDATE


FROM EMP
WHERE HIREDATE < '31-JUL-88' ;

LOGICAL OPERATORS

1. AND -AND (to check for both conditions to be true)

2. OR - OR (to check for one of the conditions to be true)

3. NOT - NOT (to negate the given condition)

4 . Limit Clause - Sets an upper limit on number of (tuples)rows to be returned

SELECT col1, col2


FROM table_name
LIMIT number;

We use logical operators to write multiple conditions .


1. WAQTD name and deptno along with job for the
employee working in dept 10 .

SELECT ENAME , DEPTNO , JOB


FROM EMP
WHERE DEPTNO = 10 ;

2. WAQTD name and deptno along with job for the


employee working as manager in dept 10 .

SELECT ENAME , DEPTNO , JOB


FROM EMP
WHERE JOB ='MANAGER' AND DEPTNO = 10 ;
3. WAQTD name , deptno , salary of the employee working
in dept 20 and earning less than 3000 .

SELECT ENAME, DEPTNO , SAL


FROM EMP
WHERE DEPTNO = 20 AND SAL < 3000 ;

4. WAQTD name and salary of the employee if emp earns


More than 1250 but less than 3000 .

SELECT ENAME , SAL


FROM EMP
WHERE SAL > 1250 AND SAL < 3000 ;

5. WAQTD name and deptno of the employees if the works


in dept 10 or 20

SELECT ENAME , DEPTNO FROM


EMP
WHERE DEPTNO = 10 OR DEPTNO = 20 ;

6. WAQTD name and sal and deptno of the employees


If emp gets more than 1250 but less than 4000 and works
in dept 20 .

SELECT ENAME , SAL , DEPTNO


FROM EMP
WHERE SAL > 1250 AND SAL < 4000 AND DEPTNO
=20 ;

7. WAQTD name , job , deptno of the employees working


as a manager in dept 10 or 30 .

SELECT ENAME , JOB , DEPTNO


FROM EMP
WHERE JOB ='MANAGER' AND ( DEPTNO = 10 OR
DEPTNO = 20 ) ;

8. WAQTD name , deptno , job of the employees working


in dept 10 or 20 or 30 as a clerk .

SELECT ENAME , JOB , DEPTNO


FROM EMP
WHERE JOB ='CLERK' AND ( DEPTNO = 10 OR
DEPTNO = 20 AND DEPTNO = 30 ) ;

9. WAQTD name , job and deptno of the employees


working as clerk or manager in dept 10 .

SELECT ENAME , JOB , DEPTNO


FROM EMP
WHERE ( JOB = 'CLERK' OR JOB ='MANAGER' )
AND DEPTNO = 10 ;

10. WAQTD name , job , deptno , sal of the employees


working as clerk or salesman in dept 10 or 30 and
earning more than 1800 .

SELECT ENAME , JOB , SAL


FROM EMP
WHERE ( JOB ='CLERK' OR JOB ='SALESMAN')
AND ( DEPTNO = 10 OR DEPTNO = 30 ) AND SAL >
1800 ;

ASSIGNMENT ON LOGICAL OPERATORS :

1. WAQTD DETAILS OF THE EMPLOYEES


WORKING AS CLERK AND EARNING LESS THAN
1500

2. WAQTD NAME AND HIREDATE OF THE


EMPLOYEES WORKING AS MANAGER IN DEPT 30

3. WAQTD DETAILS OF THE EMP ALONG WITH


ANNUAL SALARY IF THEY ARE WORKING IN DEPT
30 AS SALESMAN AND THEIR ANNUAL SALARY
HAS TO BE GREATER THAN 14000.
4. WAQTD ALL THE DETAILS OF THE EMP
WORKING IN DEPT 30 OR AS ANALYST
5. WAQTD NAMES OF THE EMPMLOYEES
WHOS SALARY IS LESS THAN 1100 AND THEIR
DESIGNATION IS CLERK

6. WAQTD NAME AND SAL , ANNUAL SAL AND


DEPTNO IF DEPTNO IS 20 EARNING MORE THAN
1100 AND ANNUAL SALARY EXCEEDS 12000

7. WAQTD EMPNO AND NAMES OF THE


EMPLOYEES WORKING AS MANAGER IN DEPT 20

8. WAQTD DETAILS OF EMPLOYEES WORKING


IN DEPT 20 OR 30 .

9. WAQTD DETAILS OF EMPLOYEES WORKING


AS ANALYST IN DEPT 10 .

10. WAQTD DETAILS OF EMPLOYEE WORKING


AS PRESIDENT WITH SALARY OF RUPEES 4000

11.WAQTD NAMES AND DEPTNO , JOB OF EMPS


WORKING AS CLERK IN DEPT 10 OR 20
12. WAQTD DETAILS OF EMPLOYEES WORKING
AS CLERK OR MANAGER IN DEPT 10 .

13. WAQTD NAMES OF EMPLOYEES WORKING


IN DEPT 10 , 20 , 30 , 40 .

14. WAQTD DETAILS OF EMPLOYEES WITH EMPNO


7902,7839.

15. WAQTD DETAILS OF EMPLOYEES WORKING


AS MANAGER OR SALESMAN OR CLERK

16. WAQTD NAMES OF EMPLOYEES HIRED AFTER


81 AND BEFORE 87

17. WAQTD DETAILS OF EMPLOYEES EARNING


MORE THAN 1250 BUT LESS THAN 3000

18. WAQTD NAMES OF EMPLOYEES HIRED AFTER


81 INTO DEPT 10 OR 30

19. WAQTD NAMES OF EMPLOYEES ALONG WITH


ANNUAL SALARY FOR THE EMPLOYEES WORKING
AS MANAGER OR CLERK INTO DEPT 10 OR 30

20. WAQTD ALL THE DETAILS ALONG WITH


ANNUAL SALARY IF SAL IS BETWEEN 1000 AND
4000 ANNUAL SALARY MORE THAN 15000

ANSWERS :

1.WAQTD DETAILS OF THE EMPLOYEES


WORKING AS CLERK AND EARNING LESS
THAN1500
SELECT *
FROM
EMP
WHERE JOB ='CLERK' AND SAL< 1500 ;

2.WAQTD NAME AND HIREDATE OF THE


EMPLOYEES WORKING AS MANAGER IN DEPT
30
SELECT ENAME ,
HIREDATE FROM EMP
WHERE JOB ='MANAGER' AND DEPTNO=30 ;

3.WAQTD DETAILS OF THE EMP ALONG WITH


ANNUAL SALARY IF THEY ARE WORKING INDEPT
30 AS SALESMAN AND THEIR ANNUAL SALARY
HAS TO BE GREATER THAN 14000
SELECT EMP.* , SAL*12 ANNUAL_SALARY
FROM EMP
WHERE DEPTNO = 30 AND JOB ='SALESMAN' AND
SAL* 12 > 14000 ;

4.WAQTD ALL THE DETAILS OF THE EMP


WORKING IN DEPT 30 OR AS ANALYST
SELECT *
FROM
EMP
WHERE DEPTNO = 30 OR JOB ='ANALYST' ;

5.WAQTD NAMES OF THE EMPMLOYEES WHOS


SALARY IS LESS THAN 1100 AND THEIR
DESIGNATION IS CLERK SELECT ENAME
FROM EMP
WHERE SAL< 1100 AND JOB ='CLERK' ;

6.WAQTD NAME AND SAL , ANNUAL SAL AND


DEPTNO IF DEPTNO IS 20 EARNING MORE THAN
1100 AND ANNUAL SALARY EXCEEDS 12000
SELECT ENAME , SAL , SAL*12 ,
DEPTNO FROM EMP
WHERE DEPTNO = 20 AND SAL > 1100 AND SAL*12 > 12000 ;

7.WAQTD EMPNO AND NAMES OF THE


EMPLOYEES WORKING AS MANAGER IN DEPT
20
SELECT EMPNO , ENAME
FROM EMP
WHERE DEPTNO = 20 AND JOB ='MANAGER' ;

8.WAQTD DETAILS OF EMPLOYEES WORKING IN


DEPT 20 OR 30
SELECT *
FROM
EMP
WHERE DEPTNO = 10 OR DEPTNO = 30 ;

9.WAQTD DETAILS OF EMPLOYEES


WORKING AS ANALYST IN DEPT 10
SELECT *
FROM EMP
WHERE DEPTNO = 10 AND JOB ='ANALYST' ;

10. WAQTD DETAILS OF EMPLOYEE


WORKING AS PRESIDENT WITH SALARY OF
RUPEES 4000 SELECT *
FROM EMP
WHERE SAL=4000 AND JOB ='PRESIDENT' ;

11. WAQTD NAMES AND DEPTNO , JOB OF EMPS


WORKING AS CLERK IN DEPT 10 OR 20
SELECT ENAME, DEPTNO,
JOB FROM EMP
WHERE JOB = ‘CLERK’ AND ( DEPTNO =10 OR
DEPTNO = 20);

12. WAQTD DETAILS OF EMPLOYEES WORKING AS


CLERK OR MANAGER IN DEPT 10
SELECT *
FROM
EMP
WHERE ( JOB = ‘CLERK’OR JOB = ‘MANAGER’ ) AND
DEPTNO = 10;

13. WAQTD NAMES OF EMPLOYEES WORKING IN


DEPT 10 , 20 , 30 , 40
SELECT
ENAME FROM
EMP
WHERE DEPTNO = 10 OR DEPTNO = 20 OR DEPTNO =
30 OR DEPTNO =40 ;

14. WAQTD DETAILS OF EMPLOYEES WITH EMPNO


7902, 7839
SELECT *
FROM
EMP
WHERE EMPNO = 7902 OR EMPNO = 7839;

15. WAQTD DETAILS OF EMPLOYEES


WORKING AS MANAGER OR SALESMAN OR
CLERK
SELECT *
FROM
EMP
WHERE JOB = 'MANAGER' OR JOB = 'SALESMAN' OR
JOB = 'CLERK';

16.WAQTD NAMES OF EMPLOYEES HIRED AFTER


81 AND BEFORE 87
SELECT
ENAME FROM
EMP
WHERE HIREDATE > '31-DEC-81' AND HIREDATE
<'01- JAN-87'

17.WAQTD DETAILS OF EMPLOYEES EARNING


MORE THAN 1250 BUT LESS THAN 3000
SELECT *
FROM EMP
WHERE SAL > 1250 AND SAL < 3000 ;

18.WAQTD NAMES OF EMPLOYEES HIRED AFTER


81 INTO DEPT 10 OR 30
SELECT
ENAME FROM
EMP
WHERE HIREDARE > '31-DEC-81' AND ( DEPTNO =
10 OR DEPTNO = 20 ) ;

19.WAQTD NAMES OF EMPLOYEES ALONG WITH


ANNUAL SALARY FOR THE EMPLOYEES
WORKING AS MANAGER OR CLERK INTO DEPT 10
OR 30 SELECT ENAME , SAL*12
FROM EMP
WHERE ( JOB = 'MANAGER' OR JOB ='CLERK')
AND ( DEPTNO = 10 OR DEPTNO = 30 ) ;

20.WAQTD ALL THE DETAILS ALONG WITH


ANNUAL SALARY IF SAL IS BETWEEN 1000 AND
4000 ANNUAL SALARY MORE THAN 15000
SELECT EMP.* , SAL*12
FROM EMP
WHERE SAL > 1000 AND SAL < 4000 AND SAL*12 > 15000 ;

3. BETWEEN : "It is used whenever we have range of values "


[ Start value and Stop Value ] .

Between (selects for a given range)

Syntax:

Column_Name BETWEEN Lower_Range AND Higher_Range ;

- Between Op works including the range .


Example :

 WAQTD name and salary of the employees if the emp is


earning Salary in the range 1000 to 3000 .

SELECT ENAME , SAL


FROM EMP
WHERE SAL BETWEEN 1000 AND 3000 ;

 WAQTD name and deptno of the employees working in dept


10 And hired during 2019 (the entire year of 2019) .

SELECT ENAME , DEPTNO


FROM EMP
WHERE DEPTNO = 10 AND HIREDATE BETWEEN
'01- JAN-2019' AND '31-DEC-2019' ;

 WAQTD name , sal and hiredate of the employees hired


during 2017 into dept 20 with a salary greater that 2000 .

SELECT ENAME , SAL , HIREDATE


FROM EMP
WHERE DEPTNO = 20 AND SAL> 2000 AND HIREDATE
BETWEEN '01-JAN2017' AND 31-DEC-2017' ;

4. NOT BETWEEN : It is Opposite of Between .

Syntax:

Column_Name NOT BETWEEN Lower_Range AND Higher_Range ;

Example :

 WAQTD name and salary of the employees if the emp is


not earning Salary in the range 1000 to 3000 .

SELECT ENAME , SAL


FROM EMP
WHERE SAL NOT BETWEEN 1000 AND 3000 ;

 WAQTD name and deptno of the employees working in dept


10 And not hired during 2019 .

SELECT ENAME , DEPTNO


FROM EMP
WHERE DEPTNO = 10 AND HIREDATE NOT BETWEEN
'01- JAN-2019' AND '31-DEC-2019' ;

 WAQTD name , sal and hiredate of the employees who were


not hired during 2017 into dept 20 with a salary greater that
2000 .

SELECT ENAME , SAL , HIREDATE


FROM EMP
WHERE DEPTNO = 20 AND SAL> 2000 AND HIREDATE NOT
BETWEEN '01-JAN2017' AND 31-DEC-2017' ;

5. IS : "It is used to compare only NULL "

Syntax: Column_Name IS NULL ;

Example :

EID ENAME SAL COMM


1 A 1000 100
2 B null null
3 C null 200
4 D 2000 null

 WAQTD name of the employee who is not getting salary .

SELECT ENAME
FROM EMP
WHERE SAL IS NULL ;

 WAQTD name of the emp who doesn’t get commission .

SELECT ENAME
FROM EMP
WHERE COMM IS NULL ;

 WAQTD name , sal and comm of the emp if the emp doesn’t
earn both .

SELECT ENAME , SAL , COMM


FROM EMP
WHERE COMM IS NULL AND SAL IS NULL ;

6. IS NOT : "It is used to compare the values with NOT NULL ".
Syntax: Column_Name IS NOT NULL ;

Example :
 WAQTD name of the employee who is getting salary .

SELECT ENAME
FROM EMP
WHERE SAL IS NOT NULL ;

 WAQTD name of the emp who gets commission .

SELECT ENAME
FROM EMP
WHERE COMM IS NOT NULL ;

 WAQTD name , sal and comm of the emp if the emp doesn’t
earn commission but gets salary .

SELECT ENAME , SAL , COMM


FROM EMP
WHERE COMM IS NULL AND SAL IS NOT NULL;

7. LIKE: "It is used for Pattern Matching ".

To achieve pattern matching we use special characters.


 Percentile (%)
 Underscore (_)

Syntax: Column_Name LIKE 'pattern' ;

Example :

 WAQTD details of an employee whose name is SMITH .

SELECT *
FROM
EMP
WHERE ENAME ='SMITH' ;

 WAQTD details of the employee who's name starts with 'S' .

SELECT *
FROM EMP
WHERE ENAME LIKE 'S%' ;

 WAQTD details of the employee who's name ends with 'S' .

SELECT *
FROM
EMP
WHERE ENAME LIKE '%S' ;
 WAQTD names of the employees who have character 'S' in
their names .

SELECT *

WHERE ENAME LIKE '%S%' ;

 WAQTD names that starts with 'J' and ends with 'S' .

SELECT ENAME
FROM EMP
WHERE ENAME LIKE 'J%S' ;

 WAQTD names of the employee if the emp has char 'A' as


his second character .

SELECT ENAME
FROM EMP
WHERE ENAME LIKE '_A%' ;

 WAQTD names of the employee if the emp has char 'A' as his
Third character .

SELECT ENAME
FROM EMP
WHERE ENAME LIKE ' A%' ;

 WAQTD names of the employee if the emp has char 'A' as


his second character and 'S' is last character .

SELECT ENAME
FROM EMP
WHERE ENAME LIKE '_A%S' ;

 WAQTD names of the employee if the emp has char 'A' present at
at least 2 times .

SELECT ENAME
FROM EMP
WHERE ENAME LIKE '%A%A%' ;

 WAQTD names of the employee if the emp name starts with 'A'
and ends with 'A' .

SELECT ENAME
FROM EMP
WHERE ENAME LIKE 'A%A' ;
 WAQTD names of the employee if the emp's salary's last 2 digit
is 50 rupees .

SELECT ENAME
FROM EMP
WHERE SAL LIKE '%50' ;

 WAQTD names of the employees hired in November .

SELECT ENAME

WHERE HIREDATE LIKE '%NOV%' ;

8. NOT LIKE :Opposite of Like .

Syntax: Column_Name NOT LIKE 'pattern' ;

ASSIGNMENT ON SEPCIAL OPERATORS :

1) LIST ALL THE EMPLOYEES WHOSE COMMISSION


IS NULL
2) LIST ALL THE EMPLOYEES WHO DON’T HAVE
A REPORTING MANAGER
3) LIST ALL THE SALESMEN IN DEPT 30
4) LIST ALL THE SALESMEN IN DEPT NUMBER 30
AND HAVING SALARY GREATER THAN 1500
5) LIST ALL THE EMPLOYEES WHOSE NAME
STARTS WITH ‘S’ OR ‘A’
6) LIST ALL THE EMPLOYEES EXCEPT THOSE WHO
ARE WORKING IN DEPT 10 & 20.
7) LIST THE EMPLOYEES WHOSE NAME DOES NOT
START WITH ‘S’
8) LIST ALL THE EMPLOYEES WHO ARE
HAVING REPORTING MANAGERS IN DEPT 10
9) LIST ALL THE EMPLOYEES WHOSE COMMISSION
IS NULL AND WORKING AS CLERK
10) LIST ALL THE EMPLOYEES WHO DON’T HAVE
A REPORTING MANAGER IN DEPTNO 10 OR 30
11) LIST ALL THE SALESMEN IN DEPT 30 WITH SAL
MORE THAN 2450
12) LIST ALL THE ANALYST IN DEPT NUMBER 20
AND HAVING SALARY GREATER THAN 2500
13) LIST ALL THE EMPLOYEES WHOSE NAME
STARTS WITH ‘M’ OR ‘J’
14) LIST ALL THE EMPLOYEES WITH ANNUAL
SALARY EXCEPT THOSE WHO ARE WORKING IN DEPT
30
15) LIST THE EMPLOYEES WHOSE NAME DOES NOT
END WITH ‘ES’ OR ‘R’
16) LIST ALL THE EMPLOYEES WHO ARE HAVING
REPORTING MANAGERS IN DEPT 10 ALONG WITH
10% HIKE IN SALARY
17) DISPLAY ALL THE EMPLOYEE WHO ARE
‘SALESMAN’S HAVING ‘E’ AS THE LAST BUT ONE
CHARACTER IN ENAME BUT SALARY HAVING
EXACTLY 4 CHARACTER
18) DISPLAY ALL THE EMPLOYEE WHO ARE
JOINED AFTER YEAR 81
19) DISPLAY ALL THE EMPLOYEE WHO ARE JOINED
IN FEB
20) LIST THE EMPLOYEES WHO ARE NOT WORKING
AS MANAGERS AND CLERKS IN DEPT 10 AND 20 WITH
A SALARY IN THE RANGE OF 1000 TO 3000.
F
U
N
C
T
I
O
N
S

Are a block of code or list of instructions which are used to


perform a specific task .

There are 3 main components of a function


1. Function_Name
2. Number_of_arguments ( no of inputs )
3. Return type

Types of Functions in SQL :

1. SINGLE ROW FUNCTIONS


2. MUTLI ROW FUNCTIONS / AGGREGATE / GROUP FUNCTIONS

Multi Row Functions/Aggregate Functions;


What are Aggregate and Scalar functions?
An aggregate function performs operations on a collection of values to return a single scalar value. Aggregate
functions are often used with the GROUP BY and HAVING clauses of the SELECT statement. Following are
the widely used SQL aggregate functions:

It takes all the inputs at one shot and then executes and provides
A single output .
 Aggregare functions perform a calculation on a set of values,
and return a single value.
 If we pass 'n' number of inputs to a MRF( ) it returns '1' Output .

List of MRF ( )

1. MAX( ) : it is used to obtain the maximum value present in


the column./ Calculates the maximum of a collection of values
2. MIN ( ) : it is used to obtain the minimum value present in the column./ Calculates the minimum of a
collection of values
3. SUM ( ) : it is used to obtain the summation of values present in
the column./ Calculates the sum of a collection of values.
4. AVG( ) : it is used to obtain the average of values present in
the column./ Calculates the mean of a collection of values.
5. COUNT( ) : it is used to obtain the number of values present in
the column./ Counts the total number of records in a specific table or view.
6. FIRST () - Fetches the first element in a collection of values.
7. LAST () - Fetches the last element in a collection of values.

Note: All aggregate functions described above ignore NULL values except for the COUNT function.

group by

NOTE :

 Multi row functions can accept only one argument , i.e a


Column_Name or an Expression
MRF ( Column_Name / Exp )

 Along with a MRF( ) we are not supposed to use any


other Column_Name in the select clause .

 MRF( ) ignore the Null .

 We cannot use a MRF( ) in where clause .

 COUNT( ) is the only MRF which can accept * as an


Argument .

Examples :

1. WAQTD maximum salary given to a manager .

SELECT MAX( SAL )


FROM EMP
WHERE JOB ='MANAGER' ;

2. WAQTD Total salary given to dept

10 SELECT SUM( SAL )


FROM EMP
WHERE DEPTNO =10 ;
WAQTD number of employees earing more than 1500 in dept 20

3. SELECT COUNT(*)
FROM EMP
WHERE SAL > 1500 AND DEPTNO = 20 ;

4. WAQTD number of employee having 'E' in their names .

SELECT COUNT(*)
FROM EMP
WHERE ENAME LIKE '%E%' ;

5. WAQTD minimum salary given to the employees working as


clerk in Dept 10 or 20 .
SELECT MIN( SAL )
FROM EMP
WHERE JOB='CLERK' AND DEPTNO IN ( 10 , 20 ) ;

6. WAQTD number of employees hired after 1982 and before


1985 into Dept 10 or 30 .

SELECT COUNT(*)
FROM EMP
WHERE JIREDATE >'31-DEC-1982' AND HIREDATE
<'01- JAN-1985' AND DEPTNO IN ( 10 , 30 ) ;

New Section 1 Page 1


7. WAQTD number of employees getting commission .

SELECT COUNT(*)
FROM EMP
WHERE COMM IS NOT NULL ;

SELECT COUNT( COMM )


FROM EMP ;

8. WAQTD maximum salary given to employees if the emp has


character 'S' in the name and works as a Manager in dept 10 with
as salary of more than 1800 .

SELECT MAX( SAL )


FROM EMP
WHERE ENAME LIKE '%S%' AND JOB ='MANAGER' AND
DEPTNO = 10 AND SAL> 1800 ;

9. WAQTD number of employees working in dept 10 or 30


and getting commission without the salary .

SELECT COUNT(*)
FROM EMP
WHERE DEPTNO IN ( 10 , 30 ) AND COMM IS NOT
NULL AND SAL IS NULL ;

SELECT COUNT( COMM )


FROM EMP
WHERE DEPTNO IN ( 10 , 30 ) AND SAL IS NULL ;

10. WAQTD maximum salary given to a manager working in dept


20 and also his comm must be greater than his salary .

SELECT MAX( SAL )


FROM EMP
WHERE JOB ='MANAGER' AND DEPTNO = 20 AND COMM >
SAL ;

ASSIGNEMENT ON MRF( )

1. WAQTD NUMBER OF EMPLOYEES GETTING SALARY


LESS THAN 2000 IN DEPTNO 10
2. WAQTD TOTAL SALARY NEEDED TO PAY
EMPLOYEES WORKING AS CLERK
3. WAQTD AVERAGE SALARY NEEDED TO PAY
ALL EMPLOYEES
4. WAQTD NUMBER OF EMPLOYEES HAVING 'A' AS
THEIR FIRST CHARACTER
5. WAQTD NUMBER OF EMPLOYEES WORKING AS CLERK
OR MANAGER
New Section 1 Page 2
6. WAQTD TOTAL SALARY NEEDED TO PAY
EMPLOYEES HIRED IN FEB
7. WAQTD NUMBER OF EMPLOYEES REPORTING TO 7839 (MGR)
8. WAQTD NUMBER OF EMPLOYEES GETTING COMISSION
IN DEPTNO 30
9. WAQTD AVG SAL , TOTAL SAL , NUMBER OF EMPS AND
MAXIMUM SALARY GIVEN TO EMPLOYEES WORKING
AS PERSIDENT
10. WAQTD NUMBER OF EMPLOYEES HAVING 'A' IN
THEIR NAMES
11. WAQTD NUMBER OF EMPS AND TOTAL SALARY
NEEDED TO PAY THE EMPLOYEES WHO HAVE 2
CONSICUTIVE L's IN THEIR NAMES
12. WAQTD NUMBER OF DEPARTMENTS PRESENT
IN EMPLOYEE TABLE
13. WAQTD NUMBER OF EMPLOYEES HAVING CHARACTER
'Z' IN THEIR NAMES
14. WAQTD NUMBER OF EMPLOYEES HAVING '$' IN
THEIR NAMES .
15. WAQTD TOTAL SALARY GIVEN TO EMPLOYEES
WORKING AS CLERK IN DEPT 30
16. WAQTD MAXIMUM SALARY GIVEN TO THE
EMPLOYEES WORKING AS ANALYST
17. WAQTD NUMBER OF DISTINCT SALARIES PRESENT
IN EMPLOYEE TABLE
18. WAQTD NUMBER OF JOBS PRESENT IN EMPLOYEE TABLE
19. WATQD AVG SALARY GIVEN TO THE CLERK
20. WAQTD MINIMUM SALARY GIVEN TO THE
EMPLOYEES WHO WORK IN DEPT 10 AS MANAGER OR A
CLERK

ANSWERS :

1. WAQTD NUMBER OF EMPLOYEES GETTING SALARY


LESS THAN 2000 IN DEPTNO 10
SELECT
COUNT(*) FROM
EMP
WHERE DEPTNO = 10 AND SAL < 2000 ;
2. WAQTD TOTAL SALARY NEEDED TO PAY
EMPLOYEES WORKING AS CLERK
SELECT
SUM(SAL) FROM
EMP
WHERE JOB ='CLERK';
3. WAQTD AVERAGE SALARY NEEDED TO PAY
ALL EMPLOYEES
SELECT
AVG(SAL) FROM
EMP ;
4. WAQTD NUMBER OF EMPLOYEES HAVING 'A' AS
THEIR FIRST CHARACTER

New Section 1 Page 3


SELECT
COUNT(*) FROM
EMP
WHERE ENAME LIKE 'A%';
5. WAQTD NUMBER OF EMPLOYEES WORKING AS CLERK
OR MANAGER
SELECT
COUNT(*) FROM
EMP
WHERE JOB IN ('MANAGER' , 'CLERK' );
6. WAQTD TOTAL SALARY NEEDED TO PAY
EMPLOYEES HIRED IN FEB
SELECT
SUM(SAL) FROM
EMP
WHERE HIREDATE LIKE '%FEB%';
7. WAQTD NUMBER OF EMPLOYEES REPORTING TO 7839 (MGR)
SELECT COUNT(*)
FROM EMP
WHERE MGR = 7839 ;
8. WAQTD NUMBER OF EMPLOYEES GETTING COMISSION
IN DEPTNO 30
SELECT
COUNT(*) FROM
EMP
WHERE COMM IS NOT NULL AND DEPTNO =
30 ; OR
SELECT
COUNT(COMM) FROM
EMP
WHERE DEPTNO = 30 ;
9. WAQTD AVG SAL , TOTAL SAL , NUMBER OF EMPS AND
MAXIMUM SALARY GIVEN TO EMPLOYEES WORKING
AS PERSIDENT
SELECT AVG(SAL) , SUM(SAL) , COUNT(*) ,
MAX(SAL) FROM EMP
WHERE JOB = 'PRESIDENT' ;
10. WAQTD NUMBER OF EMPLOYEES HAVING 'A' IN
THEIR NAMES
SELECT
COUNT(*) FROM
EMP
WHERE ENAME LIKE '%A%';
11. WAQTD NUMBER OF EMPS AND TOTAL SALary needed to
pay THE EMPLOYEES WHO HAVE 2 CONSICUTIVE L's IN
THEIR NAMES
New Section 1 Page 4
SELECT COUNT(*) , SUM(SAL)
FROM EMP
WHERE ENAME LIKE '%LL%';
12. WAQTD NUMBER OF DEPARTMENTS PRESENT
IN EMPLOYEE TABLE
SELECT COUNT( DISTINCT
DEPTNO ) FROM EMP ;
13. WAQTD NUMBER OF EMPLOYEES HAVING CHARACTER '_'
IN THEIR NAMES
SELECT
COUNT(*) FROM
EMP
WHERE ENAME LIKE '%!_%' ESCAPE '!' ;
14. WAQTD NUMBER OF EMPLOYEES HAVING ATLEAST
2 PERCENTILES IN THEIR NAMES
SELECT
COUNT(*) FROM
EMP
WHERE ENAME LIKE '%!%%!%%' ESCAPE '%' ;
15. WAQTD TOTAL SALARY GIVEN TO EMPLOYEES
WORKING AS CLERK IN DEPT 30
SELECT
SUM(SAL) FROM
EMP
WHERE JOB ='CLERK' AND DEPTNO = 30 ;
16. WAQTD MAXIMUM SALARY GIVEN TO THE
EMPLOYEES WORKING AS ANALYST
SELECT
MAX(Sal) FROM
EMP
WHERE JOB ='ANALYST' ;
17. WAQTD NUMBER OF DISTINCT SALARIES PRESENT
IN EMPLOYEE TABLE
SELECT COUNT( DISTINCT SAL )
FROM EMP ;
18. WAQTD NUMBER OF JOBS PRESENT IN EMPLOYEE TABLE
SELECT COUNT( DISTINCT
JOB ) FROM EMP ;
19. WATQD AVG SALARY GIVEN TO THE CLERK
SELECT
AVG(SAL) FROM
EMP
WHERE JOB ='CLERK' ;
20. WAQTD MINIMUM SALARY GIVEN TO THE
EMPLOYEES WHO WORK IN DEPT 10 AS MANAGER OR A
CLERK

New Section 1 Page 5


SELECT
MIN(SAL) FROM
EMP
WHERE DEPTNO = 10 AND JOB IN ( 'MANAGER' , 'CLERK' ) ;

A scalar function returns a single value based on the input value. Following are the widely used SQL scalar
functions:

LEN () - Calculates the total length of the given field (column).


UCASE () - Converts a collection of string values to uppercase characters.
LCASE () - Converts a collection of string values to lowercase characters.
MID () - Extracts substrings from a collection of string values in a table.
CONCAT () - Concatenates two or more strings.
RAND () - Generates a random collection of numbers of a given length.
ROUND () - Calculates the round-off integer value for a numeric field (or decimal point values).
NOW () - Returns the current date & time.
FORMAT () - Sets the format to display a collection of values.

What is User-defined function? What are its various types?

The user-defined functions in SQL are like functions in any other programming language that
accept parameters, perform complex calculations, and return a value. They are written to use
the logic repetitively whenever required. There are two types of SQL user-defined functions:

 Scalar Function: As explained earlier, user-defined scalar functions return a single scalar value.
 Table-Valued Functions: User-defined table-valued functions return a table as output.
Inline: returns a table data type based on a single SELECT statement.
Multi-statement: returns a tabular result-set but, unlike inline, multiple SELECT statements can be used
inside the function body

GROUP & FILTERING

New Section 1 Page 6


GROUPING : GROUP BY Clause

Group by clause is used to group the records .


Groups rows that have the same values into summary rows.
It collects data from multiple records and groups the result by one or more column.

GROUP BY clause in SQL is used to group records with identical data and can be used in conjunction with some aggregation
functions to produce summarized results from the database.

*Generally we use group by with some aggregation function.

SYNTAX:

SELECT group_by_expression / group_function FROM


table_name
[WHERE <filter_condition>]

ORDER OF EXECUTION:

1- FROM
2- WHERE (if used) [ROW-BY-ROW]
3- GROUP BY [ROW-BY-ROW]
4- SELECT [GROUP-BY-GROUP]

EMP
EID ENAME SAL DEPTN
O
1 A 100 20
2 B 200 10
3 C 300 30
4 D 100 10
5 E 200 10
6 A 400 30
7 C 500 20
8 F 200 30

Example :

New Section 1 Page 7


 WAQTD number of employees working in each dept .
SELECT COUNT(*)
FROM EMP
GROUP BY DEPTNO ;

NOTE :

 Group By clause is used to group the records .


 Group By clause executes row by row .
 After the execution of Group By clause we get Groups .
 Therefore any clause that executes after group by must
execute Group By Group .
 The Column_Name or expression used for grouping can be used
In select clause .
 Group By clause can be used without using Where clause .

Questions :

1. WAQTD number of employees working in each dept except


the Employee working as analyst .

SELECT DEPTNO , COUNT(*)


FROM EMP
WHERE JOB NOT IN 'ANALYST'
GROUP BY DEPTNO ;

2. WAQTD maximum salary given to each job .

SELECT JOB , MAX( SAL )


FROM EMP
GROUP BY JOB ;

New Section 1 Page 8


3. WAQTD number of employees working in each job if
the employees Have character 'A' in their names .

SELECT JOB , COUNT(*)


FROM EMP
WHERE ENAME LIKE '%A
%' GROUP BY JOB ;

4. WAQTD number of employees getting commission in


each dept .

SELECT DEPTNO , COUNT( COMM )


FROM EMP
GROUP BY DEPTNO ;

ASSIGNMENT QUESTIONS ON GROUP BY

1. WAQTD NUMBER OF EMPLOYEES WORKING IN


EACH DEPARTEMENT EXCEPT PRESIDENT.
2. WAQTD TOTAL SALARY NEEDED TO PAY ALL
THE EMPLOYEES IN EACH JOB.
3. WAQTD NUMBER OF EMPLOYEEES WORKING
AS MANAGER IN EACH DEPARTMENT .
4. WAQTD AVG SALARY NEEDED TO PAY ALL THE
EMPLOYEES IN EACH DEPARTMENT EXCLUDING
THE EMPLOYEES OF DEPTNO 20.
5. WAQTD NUMBER OF EMPLOYEES HAVING
CHARACTER 'A' IN THEIR NAMES IN EACH JOB .
6. WAQTD NUMBER OF EMPLOYEES AND AVG
SALARY NEEDED TO PAY THE EMPLOYEES WHO
SALARY IN GREATER THAN 2000 IN EACH DEPT.
7. WAQDTD TOTAL SALARY NEEDED TO PAY AND
NUMBER OF SALESMANS IN EACH DEPT.
8. WAQTD NUMBER OF EMPLOYEES WITH THEIR
MAXIMUM SALARIES IN EACH JOB.
9. WAQTD MAXIMUM SALARIES GIVEN TO AN
EMPLOYEE WORKING IN EACH DEPT.
10. WAQTD NUMBER OF TIMES THE SALARIES PRESENT
IN EMPLOYEE TABLE .

ANSWERS :

1. WAQTD NUMBER OF EMPLOYEES WORKING IN


EACH DEPARTEMENT EXCEPT PRESIDENT
SELECT DEPTNO, COUNT(*)
FROM EMP
WHERE JOB NOT IN
'PRESIDENT' GROUP BY
DEPTNO;

2. WAQTD TOTAL SALARY NEEDED TO PAY ALL


THE EMPLOYEES IN EACH JOB
New Section 1 Page 9
SELECT JOB , SUM(SAL)
FROM EMP
GROUP BY JOB

3. WAQTD NUMBER OF EMPLOYEEES WORKING


AS MANAGER IN EACH DEPARTMENT

SELECT DEPTNO, COUNT(*)


FROM EMP
WHERE JOB='MANAGER'
GROUP BY DEPTNO;

4. WAQTD AVG SALARY NEEDED TO PAY ALL THE


EMPLOYEES IN EACH DEPARTMENT EXCLUDING
THE EMPLOYEES OF DEPTNO 20

SELECT DEPTNO,
AVG(SAL) FROM EMP
WHERE DEPTNO NOT IN 20
GROUP BY DEPTNO;

5. WAQTD NUMBER OF EMPLOYEES HAVING


CHARACTER 'A' IN THEIR NAMES IN EACH JOB

SELECT JOB, COUNT(*)


FROM EMP
WHERE ENAME LIKE '%A
%' GROUP BY JOB;

6. WAQTD NUMBER OF EMPLOYEES AND AVG


SALARY NEEDED TO PAY THE EMPLOYEES WHO
SALARY IN GREATER THAN 2000 IN EACH DEPT

SELECT DEPTNO, COUNT(*) , AVG(SAL)


FROM EMP
WHERE SAL > 2000
GROUP BY DEPTNO;

7. WAQDTD TOTAL SALARY NEEDED TO PAY AND


NUMBER OF SALESMANS IN EACH DEPT

SELECT DEPTNO, COUNT(*) ,


SUM(SAL) FROM EMP
WHERE JOB='SALESMAN'
GROUP BY DEPTNO;

WAQTD NUMBER OF EMPLOYEES WITH THEIR MAXIMUM SALARIES IN EACH JOB

SELECT JOB, COUNT(*) , MAX(SAL)


FROM EMP
GROUP BY JOB;

8. WAQTD MAXIMUM SALARIES GIVEN TO AN


EMPLOYEE WORKING IN EACH DEPT

New Section 1 Page


SELECT DEPTNO,
MAX(SAL) FROM EMP
GROUP BY DEPTNO;

9. WAQTD NUMBER OF TIMES THE SALARIES PRESENT


IN EMPLOYEE TABLE

SELECT SAL , COUNT(*)


FROM EMP
GROUP BY SAL;

FILTERING : HAVING Clause

" Having Clause is used to Filter the Group "


Similar to Where i.e. applies some condition on rows.
Used when we want to apply any condition after grouping.

HAVING clause in SQL is used to filter records in combination with the GROUP BY clause. It is different from
WHERE, since the WHERE clause cannot filter aggregated records.

SYNTAX:

SELECT group_by_expression / group_function


FROM table_name
[WHERE <filter_condition>] GROUP
BY column_name/expression
HAVING <group_filter_condition>

SELECT COUNT(studentId), country


FROM myDB.students WHERE country != "INDIA"
GROUP BY country
HAVING COUNT(studentID) > 5;

ORDER OF EXECUTION:
1-FROM
2-WHERE (if used) [ROW-BY-ROW]
3-GROUP BY (if used) [ROW-BY-ROW]
4-HAVING (if used) [GROUP-BY-GROUP]
5-SELECT [GROUP-BY-GROUP]

General Order
New Section 1 Page
SELECT column(s)
FROM table_name
WHERE condition
GROUP BY column(s)
HAVING condition
ORDER BY column(s) ASC;

Count number of students in each city where max marks cross 90.

Example :

WAQTD to find number of employees working in each Dept if there are at least 3 employees in each dept
SELECT DEPTNO , COUNT(*)
FROM EMP
GROUP BY DEPTNO
HAVING COUNT(*)>=3 ;

Questions :

New Section 1 Page


1. WAQTD the designations in which there are at lest 2
employees Present .

SELECT JOB , COUNT(*)


FROM EMP
GROUP BY JOB
HAVING COUNT(*)>=2
;

2. WAQTD the names that are repeated .

SELECT ENAME , COUNT(*)


FROM EMP
GROUP BY ENAME
HAVING COUNT(*) > 1 ;

3. WAQTD names that are repeated exactly twice .

SELECT ENAME , COUNT(*)


FROM EMP
GROUP BY ENAME
HAVING COUNT(*) = 2 ;

4. WAQTD the salary that is repeated .

SELECT SAL, COUNT(*)


FROM EMP
GROUP BY SAL
HAVING COUNT(*) > 1 ;

5. WAQTD number of employees working in each dept


having At least 2 emp's Character 'A' or 'S' in their names .

SELECT DEPTNO , COUNT(*)


FROM EMP
WHERE ENAME LIKE '%A%' OR ENAME LIKE '%S
%' GROUP BY DEPTNO
HAVING COUNT(*)>=2 ;

6. WAQTD job and total salary of each job , if the total salary
Of each job is greater than 3450 .

SELECT JOB , SUM( SAL )


FROM EMP
GROUP BY JOB
HAVING SUM( SAL ) > 3450 ;

7. WAQTD job and total salary of the employees if the


employees Are earning more than 1500.

SELECT JOB , SUM( SAL )


FROM EMP
New Section 1 Page
WHERE SAL > 1500
GROUP BY JOB ;

NOTE :

Differentiate between Where and Having .

WHERE HAVING
 Where clause is used to  Having clause is used to
Filter the records Filter the groups .
 Where clause executes  Having clause executes
row By row . Group by group
 In Where Clause we  Can use MRF( ).
cannot Use MRF( )
 Where clause executes  Having clause executes
before Group by clause . After group by clause .

8. WAQTD Job wise maximum salary if the maximum


salary Of each job exceeds 2000 .

SELECT JOB , MAX( SAL )


FROM EMP
GROUP BY JOB
HAVING MAX( SAL ) > 2000 ;

9. WAQTD number of emp earning sal more than 1200 in each


job and the total sal needed to pay emp of each job must
exceeds 3800.

SELECT JOB , COUNT(*) , SUM( SAL )


FROM EMP WHERE SAL > 1200
GROUP BY JOB
HAVING SUM( SAL ) > 3800 ;

ASSIGNMENT QUESTIONS ON HAVING CLAUSE

1. WAQTD DNO AND NUMBER OF EMP WORKING IN


EACH DEPT IF THERE
ARE ATLEAST 2 CLERKS IN EACH DEPT
2. WAQTD DNO AND TOTAL SAALARYNEEDED TO PAY
ALL EMP
IN EACH DEPT IF THERE ARE ATLEAST 4 EMP IN EACH
DEPT
3. WAQTD NUMBER OF EMP EARNING SAL MORE THAN
1200 IN EACH JOB
AND THE TOTAL SAL NEEDED TO PAY EMP OF EACH JOB
MUST EXCEES 3800
4. WAQTD DEPTNO AND NUMBER OF EMP WORKING
ONLY IF THERE ARE 2 EMP WORKING IN EACH DEPT AS
MANAGER .
5. WAQTD JOB AND MAX SAL OF EMP IN EACH JOB IF

New Section 1 Page


THE MAX SAL EXCEEDS 2600
6. WAQTD THE SALARIES WHICH ARE REPEATED IN
EMP TABLE
7. WAQTD THE HIREDATE WHICH ARE DUPLICATED IN
EMP TABLE
8. WAQTD AVG SALARY OF EACH DEPT IF AVG SAL IS
LESS THAN 3000
9. WAQTD DEPTNO IF THERE ARE ATLEAST 3 EMP IN
EACH DEPT WHOS NAME
HAS CHAR 'A' OR 'S' .
10. WAQTD MIN AND MAX SALARIES OF EACH JOB IF MIN
SAL IS MORE THAN 1000 AND MAX SAL IS LESS THAN 5000
.

Order By Clause - To sort in ascending (ASC) or descending order (DESC)

SELECT col1, col2


FROM table_name
ORDER BY col_name(s) ASC;
SUB-QUERY

" A QUERY WRITTEN INSIDE ANOTHER QUERY IS KNOWN


AS SUB QUERY "

Working Principle :

New Section 1 Page


Let us consider two queries Outer Query and Inner Query .
 Inner Query executes first and produces an Output .
 The Output of Inner Query is given / fed as an Input to Outer Query .
 The Outer Query generates the Result.
 Therefore we can state that 'the Outer Query is dependent on
Inner Query' and this is the Execution Principle of Sub Query
.

Why / When Do we use SUB QUERY :

Case 1 : Whenever we have Unknowns present in the Question


We use sub query to find the Unknown .
Example :

EMP
EID ENAME SAL DEPTNO
1 ALLEN 1000 20
2 BLAKE 2000 10
3 CLARK 3000 30
4 MILLER 1500 10
5 SMITH 2500 10

1. WAQTD names of the employees earning more than 2500 .

SELECT ENAME
FROM EMP
WHERE SAL > 2500 ;

2. WAQTD names of the employees earning less than MILLER .

SELECT ENAME
FROM EMP
WHERE SAL < ( SELECT SAL
FROM EMP
WHERE ENAME = 'MILLER' );

3. WAQTD name and deptno of the employees working in the


same Dept as SMITH .

SELECT ENAME , DEPTNO


FROM EMP
WHERE DEPTNO = ( SELECT DEPTNO
FROM EMP
WHERE ENAME ='SMITH' ) ;

4. WAQTD name and hiredate of the employees if the


employee Was hired after JONES .

SELECT ENAME , HIREDATE


New Section 1 Page
FROM EMP
WHERE HIREDATE > ( SELECT HIREDATE
FROM EMP
WHERE ENAME ='JONES' ) ;

5. WAQTD all the details of the employee working in the


same Designation as KING .

SELECT *
FROM
EMP
WHERE JOB = ( SELECT JOB
FROM EMP
WHERE ENAME ='KING' );

6. WAQTD name , sal , deptno of the employees if the employees


Earn more than 2000 and work in the same dept as JAMES .

SELECT ENAME , SAL , DEPTNO


FROM EMP
WHERE SAL > 2000 AND DEPTNO = ( SELECT DEPTNO
FROM EMP
WHERE ENAME ='JAMES' ) ;

7. WAQTD all the details of the employees working in the


Same designation as MILLER and earning more than
1500.

SELECT *
FROM
EMP
WHERE SAL > 1500 AND JOB = ( SELECT JOB
FROM EMP
WHERE ENAME ='MILLER' ) ;
SELECT *
FROM EMP
WHERE JOB = ( SELECT JOB
FROM EMP
WHERE ENAME ='MILLER' ) AND SAL > 1500 ;

8. WAQTD details of the employees earning more than


SMITH But less than KING .

SELECT *
FROM EMP
WHERE SAL > ( SELECT SAL
FROM EMP
WHERE ENAME ='SMITH' ) AND SAL < ( SELECT SAL
FROM EMP
WHERE ENAME ='KING' ) ;

9. WAQTD name , sal and deptno of the employees if the employee


Is earning commission in dept 20 and earning salary more than
Scott .

New Section 1 Page


SELECT ENAME , SAL , DEPTNO
FROM EMP
WHERE COMM IS NOT NULL AND DEPTNO = 20 AND
SAL > ( SELECT SAL
FROM EMP
WHERE ENAME ='SCOTT' ) ;

10. WAQTD name and hiredate of the employees who's name ends
with 'S' and hired after James .

SELECT ENAME , HIREDATE


FROM EMP
WHERE ENAME LIKE '%S' AND
HIREDATE > ( SELECT HIREDATE
FROM EMP
WHERE ENAME ='JAMES' ) ;

11. WAQTD names of the employees working in the same dept as


JAMES and earning salary more than ADAMS and working in
the same job role as MILLER and hired after MARTIN .

SELECT ENAME
FROM EMP
WHERE DEPTNO=(SELECT DEPTNO
FROM EMP
WHERE ENAME='JAMES') AND
SAL>(SELECT SAL
FROM EMP
WHERE ENAME='ADAMS') AND
JOB=(SELECT JOB
FROM EMP
WHERE ENAME='MILLER') AND
HIREDATE>(SELECT HIREDATE
FROM EMP
WHERE ENAME='MARTIN');

12. WAQTD all the details of the employees working as salesman in


the dept 20 and earning commission more than Smith and hired
after KING .

SELECT *
FROM
EMP
WHERE JOB ='SALESMAN' AND
DEPTNO = 20 AND
COMM > ( SELECT COMM
FROM EMP
WHERE ENAME ='SMITH' ) AND
HIREDATE > ( SELECT HIREDATE
FROM EMP
WHERE ENAME ='KING' ) ;

13. WAQTD number of employees earning more than SMITH and


less than MARTIN .
New Section 1 Page
SELECT COUNT(*)
FROM EMP
WHERE SAL > ( SELECT SAL
FROM EMP
WHERE ENAME ='SMITH') AND
SAL < ( SELECT SAL
FROM EMP
WHERE ENAME ='MARTIN' )

14. WAQTD Ename and SAL for all the employees earning more
than JONES .

SELECT ENAME , SAL


FROM EMP
WHERE SAL > ( SELECT SAL
FROM EMP
WHERE ENAME =JONES' ) ;

15. WAQTD all the details of the employees working as a manager .

SELECT *
FROM
EMP
WHERE JOB ='MANAGER' ;

NOTE :
 In the Inner Query / Sub Query we cannot select more than
One column .
 The corresponding columns need not be same , but the
datatypes of those has to be same .

ASSIGNMENT ON CASE 1

1. WAQTD NAME OF THE EMPLOYEES EARNING MORE


THAN ADAMS
2. WAQTD NAME AND SALARY OF THE EMPLOYEES
EARNING LESS THAN KING
3. WAQTD NAME AND DEPTNO OF THE EMPLOYEES IF THEY
ARE WORKING IN THE SAME DEPT AS JONES
4. WAQTD NAME AND JOB OF ALL THE EMPLOYEES
WORKING IN THE SAME DESIGNATION AS JAMES
5. WAQTD EMPNO AND ENAME ALONG WITH ANNUAL
SALARY OF ALL THEEMPLOYEES IF THEIR ANNUAL SALARY
IS GREATER THAN WARDS ANNUAL SALARY.
6. WAQTD NAME AND HIREDATE OF THE EMPLOYEES IF
THEY ARE HIRED BEFORE SCOTT
7. WAQTD NAME AND HIREDATE OF THE EMPLOYEES IF
THEY ARE HIRED AFTER THE PRESIDENT
8. WAQTD NAME AND SAL OF THE EMPLOYEE IF THEY ARE
EARNING SAL LESS THAN THE EMPLOYEE WHOS EMPNO IS
7839 9.WAQTD ALL THE DETAILS OF THE EMPLOYEES IF THE
EMPLOYEES ARE HIRED BEFORE MILLER
New Section 1 Page
10. WAQTD ENAME AND EMPNO OF THE EMPLOYEES
IF EMPLOYEES ARE EARNING MORE THAN ALLEN
11. WAQTD ENAME AND SALARY OF ALL THE EMPLOYEES
WHO ARE EARNING MORE THAN MILLER BUT LESS THAN
ALLEN .
12. WAQTD ALL THE DETAILS OF THE EMPLOYEES WORKING IN
DEPT 20 AND WORKING IN THE SAME DESIGNATION AS SMITH
13.WAQTD ALL THE DETAILS OF THE EMPLOYEES WORKING
AS MANAGER IN THE SAME DEPT AS TURNER
14. WAQTD NAME AND HIREDATE OF THE EMPLOYEES
HIRED AFTER 1980 AND BEFORE KING
15. WAQTD NAME AND SAL ALONG WITH ANNUAL SAL FOR
ALL EMPLOYEES WHOS SAL IS LESS THAN BLAKE AND MORE
THAN 3500
16. WAQTD ALL THE DETAILS OF EMPLOYEES WHO EARN
MORE THAN SCOTT BUT LESS THAN KING
17. WAQTD NAME OF THE EMPLOYEES WHOS NAME
STARTS WITH 'A' AND WORKS IN THE SAME DEPT AS
BLAKE
18. WAQTD NAME AND COMM IF EMPLOYEES EARN
COMISSION AND WORK IN THE SAME DESIGNATION AS SMITH
19. WAQTD DETAILS OF ALL THE EMPLOYEES WORKING
AS CLERK IN THE SAME DEPT AS TURNER .
20. WAQTD ENAME, SAL AND DESIGNATION OF THE
EMPLOYEES WHOS ANNUAL SALARY IS MORE THAN SMITH
AND LESS THAN KING.

1. WAQTD NAME OF THE EMPLOYEES EARNING MORE


THAN ADAMS
SELECT
ENAME FROM
EMP
WHERE SAL > ( SELECT
SAL FROM EMP
WHERE ENAME ='ADAMS' );
2. WAQTD NAME AND SALARY OF THE EMPLOYEES
EARNING LESS
THAN KING
SELECT ENAME ,
SAL FROM EMP
WHERE SAL < ( SELECT
SAL FROM EMP
WHERE ENAME ='KING' );

3. WAQTD NAME AND DEPTNO OF THE EMPLOYEES IF THEY


ARE WORKING
IN THE SAME DEPT AS JONES
SELECT ENAME , DEPTNO
FROM EMP
WHERE DEPTNO = ( SELECT DEPTNO
New Section 1 Page
FROM EMP
WHERE ENAME =JONES');

4. WAQTD NAME AND JOB OF ALL THE EMPLOYEES


WORKING IN THE SAME
DESIGNATION AS JAMES
SELECT ENAME , JOB
FROM EMP
WHERE JOB = ( SELECT
JOB FROM EMP
WHERE ENAME ='JAMES' );

5. WAQTD EMPNO AND ENAME ALONG WITH ANNUAL


SALARY OF ALL THE
EMPLOYEES IF THEIR ANNUAL SALARY IS GREATER THAN
WARDS
ANNUAL SALARY.
SELECT EMPNO , ENAME .
SAL*12 FROM EMP
WHERE SAL * 12 > ( SELECT
SAL*12 FROM EMP
WHERE ENAME = 'WARD' );

6. WAQTD NAME AND HIREDATE OF THE EMPLOYEES IF


THEY ARE HIRED
BEFORE SCOTT
SELECT ENAME ,
HIREDATE FROM EMP
WHERE HIREDATE < ( SELECT HIREDATE
FROM EMP
WHERE ENAME ='SCOTT' );

7. WAQTD NAME AND HIREDATE OF THE EMPLOYEES IF


THEY ARE HIRED
AFTER THE PRESIDENT
SELECT ENAME ,
HIREDATE FROM EMP
WHERE HIREDATE > ( SELECT HIREDATE FROM EMP
WHERE JOB = 'PRESIDENT' );

8. WAQTD NAME AND SAL OF THE EMPLOYEE IF THEY


ARE EARNING SAL
LESS THAN THE EMPLOYEE WHOS EMPNO IS 7839
SELECT ENAME ,
SAL FROM EMP

New Section 1 Page


WHERE SAL < ( SELECT
SAL FROM EMP
WHERE EMPNO = 7839 );

9. WAQTD ALL THE DETAILS OF THE EMPLOYEES IF


THE EMPLOYEES ARE
HIRED BEFORE MILLER
SELECT *
FROM EMP
WHERE HIREDATE < ( SELECT HIREDATE
FROM EMP
WHERE ENAME ='MILLER' );

10. WAQTD ENAME AND EMPNO OF THE EMPLOYEES


IF EMPLOYEES ARE
EARNING MORE THAN ALLEN
SELECT ENAME ,
EMPNO FROM EMP
WHERE SAL > ( SELECT
SAL FROM EMP
WHERE ENAME ='ALLEN' );

11. WAQTD ENAME AND SALARY OF ALL THE EMPLOYEES


WHO ARE EARNING
MORE THAN MILLER BUT LESS THAN ALLEN
SELECT ENAME ,
SAL FROM EMP
WHERE SAL > ( SELECT
SAL FROM EMP
WHERE ENAME ='MILLER ) AND SAL < ( SELECT SAL
FROM EMP
WHERE ENAME ='ALLEN' );

12. WAQTD ALL THE DETAILS OF THE EMPLOYEES WORKING


IN DEPT 20
AND WORKING IN THE SAME DESIGNATION AS SMITH
SELECT *
FROM EMP
WHERE DEPTNO = 20 AND JOB = ( SELECT
JOB FROM EMP
WHERE ENAME ='SMITH');

13. WAQTD ALL THE DETAILS OF THE EMPLOYEES WORKING


AS MANAGER
IN THE SAME DEPT AS TURNER
SELECT * from emp
New Section 1 Page
WHERE JOB ='MANAGER' AND DEPTNO = ( SELECT DEPTNO
FROM EMP
WHERE ENAME ='TURNER' ) ;

14. WAQTD NAME AND HIREDATE OF THE EMPLOYEES


HIRED AFTER 1980
AND BEFORE KING
SELECT ENAME ,
HIREDATE FROM EMP
WHERE HIREDATE > '31-DEC-1980 ' AND HIREDATE < ( SELECT
HIREDATE
FROM EMP
WHERE ENAME ='KING' );

15. WAQTD NAME AND SAL ALONG WITH ANNUAL SAL FOR
ALL EMPLOYEES
WHOS SAL IS LESS THAN BLAKE AND MORE THAN 3500
SELECT ENAME , SAL ,
SAL*12 FROM EMP
WHERE SAL > 3500 AND SAL < ( SELECT SAL
FROM EMP
WHERE ENAME ='BLAKE );

16. WAQTD ALL THE DETAILS OF EMPLOYEES WHO EARN


MORE THAN SCOTT
BUT LESS THAN KING
SELECT *
FROM
EMP
WHERE SAL > ( SELECT
SAL FROM EMP
WHERE ENAME ='SCOTT') AND SAL < ( SELECT SAL
FROM EMP
WHERE ENAME ='KING' );

17. WAQTD NAME OF THE EMPLOYEES WHOS NAME


STARTS WITH ‘A’ AND
WORKS IN THE SAME DEPT AS BLAKE
SELECT
ENAME FROM
EMP
WHERE ENAME LIKE 'A%' AND DEPTNO = ( SELECT DEPTNO
FROM EMP
WHERE ENAME ='BLAKE' ) ;

New Section 1 Page


18. WAQTD NAME AND COMM IF EMPLOYEES EARN
COMISSION AND WORK IN
THE SAME DESIGNATION AS SMITH
SELECT ENAME , COMM
FROM EMP
WHERE COMM IS NOT NULL AND JOB = ( SELECT
JOB FROM EMP
WHERE ENAME ='SMITH');

19. WAQTD DETAILS OF ALL THE EMPLOYEES WORKING AS


CLERK IN THE
SAME DEPT AS TURNER
SELECT *
FROM
EMP
WHERE JOB ='CLERK' AND DEPTNO = ( SELECT DEPTNO
FROM EMP
WHERE ENAME ='TURNER' ) ;

20. WAQTD ENAME, SAL AND DESIGNATION OF THE


EMPLOYEES WHOS
ANNUAL SALARY IS MORE THAN SMITH AND LESS THAN KING
SELECT ENAME , SAL ,
JOB FROM EMP
WHERE SAL*12 > ( SELECT SAL
*12 FROM EMP
WHERE ENAME ='SMITH') AND SAL < ( SELECT SAL *12
FROM EMP
WHERE ENAME ='KING' );

CASE-2 : Whenever the data to be selected and the condition to be


executed are present in different tables we use Sub Query .

Example :

Emp
EID ENAME SAL DEPTNO
1 ALLEN 1000 20 DEPT
2 BLAKE 2000 10 DEPTN DNAM LOC
3 CLARK 3000 30 O E
4 MILLER 1500 10 10 D1 L1
5 ADAMS 2500 20 20 D2 L2
30 D3 L3

New Section 1 Page


1. WAQTD deptno of the employee whose name is Miller .

SELECT DEPTNO
FROM EMP
WHERE ENAME ='MILLER' ;

2. WAQTD dname of the employee whose name is Miller .

SELECT DNAME
FROM
DEPT
WHERE DEPTNO = ( SELECT DEPTNO
FROM EMP
WHERE ENAME ='MILLER' ) ;

3. WAQTD Location of ADAMS

SELECT
LOC FROM
DEPT
WHERE DEPTNO = ( SELECT DEPTNO
FROM EMP
WHERE ENAME ='ADAMS' ) ;

4. WAQTD names of the employees working in Location L2.

SELECT ENAME
FROM EMP
WHERE DEPTNO = ( SELECT DEPTNO
FROM DEPT
WHERE LOC ='L2' ) ;

5. WAQTD number of employees working in dept D3 .

SELECT COUNT(*)
FROM EMP
WHERE DEPTNO = ( SELECT DEPTNO
FROM DEPT
WHERE DNAME ='D3' ) ;

6. WAQTD ename , sal of all the employee earning more


than Scott and working in dept 20 .

SELECT ENAME , SAL


FROM EMP
WHERE DEPTNO = 20 AND SAL > ( SELECT SAL
FROM EMP
WHERE ENAME ='SCOTT' ) ;

7. WAQTD all the details of the employee working as a


Manager In the dept Accounting .

SELECT *

New Section 1 Page


FROM EMP
WHERE JOB ='MANAGER' AND
DEPTNO = ( SELECT DEPTNO
FROM DEPT
WHERE DNAME ='ACCOUNTING' ) ;

8. WAQTD all the details of the employee working in the


same designation as Miller and works in location New York
.

SELECT *
FROM EMP
WHERE JOB = ( SELECT JOB
FROM EMP
WHERE ENAME ='MILLER' ) AND DEPTNO = (
SELECT DEPTNO FROM DEPT WHERE LOC ='NEW
YORK' ) ;

9. WAQTD number of employees working as a clerk in the


same deptno as SMITH and earning more than KING hired
after MARTIN in the location BOSTON .

SELECT COUNT(*)
FROM EMP
WHERE JOB ='CLERK' AND
DEPTNO = ( SELECT DEPTNO
FROM EMP
WHERE ENAME ='SMITH') AND
SAL > ( SELECT SAL
FROM EMP
WHERE ENAME ='KING' ) AND
HIREDATE > ( SELECT HIREDATE
FROM EMP
WHERE ENAME ='MARTIN' ) AND
DEPTNO = ( SELECT DEPTNO
FROM DEPT
WHERE LOC ='BOSTON' ) ;
10. WAQTD maximum salary given to a person working in DALLAS .

SELECT MAX( SAL )


FROM EMP
WHERE DEPTNO = ( SELECT DEPTNO
FROM DEPT
WHERE LOC ='DALLAS' ) ;

ASSIGNMENT ON CASE 2 :

21. WAQTD DNAME OF THE EMPLOYEES WHOS NAME


IS SMITH
22. WAQTD DNAME AND LOC OF THE EMPLOYEE
WHOS ENAME IS KING
23. WAQTD LOC OF THE EMP WHOS EMPLOYEE NUMBER IS
7902

New Section 1 Page


24. WAQTD DNAME AND LOC ALONG WITH DEPTNO OF
THE EMPLOYEE WHOS NAME ENDS WITH 'R' .
25. WAQTD DNAME OF THE EMPLOYEE WHOS
DESIGNATION IS PRESIDENT
26. WAQTD NAMES OF THE EMPLOYEES WORKING
IN ACCOUNTING DEPARTMENT
27. WAQTD ENAME AND SALARIES OF THE EMPLOYEES
WHO ARE WORKING IN THE LOCATION CHICAGO
28. WAQTD DETAILS OF THE EMPLOYEES WORKING IN SALES
29. WAQTD DETAILS OF THE EMP ALONG WITH
ANNUAL SALARY IF EMPLOYEES ARE WORKING IN
NEW YORK 30.WAQTD NAMES OF EMPLOYEES
WORKING IN OPERATIONS DEPARTMENT

ASSIGNMENT ANSWERS ON CASE 2 :

21. WAQTD DNAME OF THE EMPLOYEES WHOS NAME


IS SMITH
SELECT DNAME
FROM DEPT
WHERE DEPTNO = ( SELECT
DEPTNO FROM EMP
WHERE ENAME ='SMITH' ) ;

22. WAQTD DNAME AND LOC OF THE EMPLOYEE


WHOS ENAME IS KING
SELECT
DNAME ,LOC FROM
DEPT
WHERE DEPTNO = ( SELECT
DEPTNO FROM EMP
WHERE ENAME =''KING' ) ;

23. WAQTD LOC OF THE EMP WHOS EMPLOYEE NUMBER IS


7902
SELECT
LOC FROM
DEPT
WHERE DEPTNO = ( SELECT
DEPTNO FROM EMP
WHERE EMPNO=7902 ) ;

24. WAQTD DNAME AND LOC ALONG WITH DEPTNO OF


THE EMPLOYEE WHO’S NAME ENDS WITH ‘R’.
SELECT DNAME ,
LOC FROM DEPT

New Section 1 Page


WHERE DEPTNO = ( SELECT
DEPTNO FROM EMP
WHERE ENAME LIKE '%R' ) ;

25. WAQTD DNAME OF THE EMPLOYEE WHOS


DESIGNATION IS PRESIDENT
SELECT
DNAME FROM
DEPT
WHERE DEPTNO = ( SELECT
DEPTNO FROM EMP
WHERE JOB = 'PRESIDENT' ) ;

26. WAQTD NAMES OF THE EMPLOYEES WORKING IN


ACCOUNTING DEPARTMENT
SELECT
ENAME FROM
EMP
WHERE DEPTNO = ( SELECT
DEPTNO FROM DEPT
WHERE DNAME = 'ACCOUNTING' );

27. WAQTD ENAME AND SALARIES OF THE EMPLOYEES


WHO ARE WORKING IN
THE LOCATION ‘CHICAGO’
SELECT
ENAME ,SAL FROM
EMP
WHERE DEPTNO = ( SELECT
DEPTNO FROM DEPT
WHERE LOC = 'CHICAGO' );

28. WAQTD DETAILS OF THE EMPLOYEES WORKING IN SALES


SELECT *
FROM
EMP
WHERE DEPTNO = ( SELECT DEPTNO
FROM DEPT
WHERE DNAME ='SALES' );

29. WAQTD DETAILS OF THE EMP ALONG WITH


ANNUAL SALARY IF EMPLOYEES
ARE WORKING IN NEW YORK
SELECT EMP.* ,
SAL*12 FROM EMP

New Section 1 Page


WHERE DEPTNO = ( SELECT
DEPTNO FROM DEPT
WHERE LOC ='NEW YORK' );

30. WAQTD NAMES OF EMPLOYEES WORKING


IN OPERATIONS DEPARTMENT
SELECT
ENAME FROM
EMP
WHERE DEPTNO = ( SELECT DEPTNO
FROM DEPT
WHERE DNAME ='OPERATIONS' );

ASSIGNMENT ON CASE 1 & 2

31. WAQTD NAMES OF THE EMPLOYEES EARNING


MORE THAN SCOTT IN ACCOUNTING DEPT
32. WAQTD DETAILS OF THE EMPLOYEES WORKING
AS MANAGER IN THE LOCATION CHICAGO
33. WAQTD NAME AND SAL OF THE EMPLOYEES
EARNING MORE THAN KING IN THE DEPT ACCOUNTING
34. WAQTD DETAILS OF THE EMPLOYEES WORKING
AS SALESMAN IN THE DEPARTEMENT SALES
35. WAQTD NAME , SAL , JOB , HIREDATE OF THE
EMPLOYEES WORKING IN OPERATIONS DEPARTMENT AND
HIRED BEFORE KING
36. DISPLAY ALL THE EMPLOYEES WHOSE
DEPARTMET NAMES ENDING 'S'.
37. WAQTD DNAME OF THE EMPLOYEES WHOS NAMES
HAS CHARACTER 'A' IN IT .
38. WAQTD DNAME AND LOC OF THE EMPLOYEES
WHOS SALARY IS RUPEES 800 .
39. WAQTD DNAME OF THE EMPLOYEES WHO
EARN COMISSION
40. WAQTD LOC OF THE EMPLOYEES IF THEY
EARN COMISSION IN DEPT 40

New Section 1 Page


ANSWERS ON CASE 1 & 2 :

31. WAQTD NAMES OF THE EMPLOYEES EARNING


MORE THAN SCOTT IN
ACCOUNTING DEPT
SELECT ENAME
FROM EMP
WHERE SAL > ( SELECT
SAL FROM EMP
WHERE ENAME ='SCOTT' ) AND DEPTNO = ( SELECT DEPTNO
FROM DEPT
WHERE DNAME =
'ACCOUNTING');

32. WAQTD DETAILS OF THE EMPLOYEES WORKING


AS MANAGER IN THE
LOCATION CHICAGO
SELECT *
FROM
EMP
WHERE JOB ='MANAGER' AND DEPTNO = ( SELECT DEPTNO
FROM
DEPT
WHERE
LOC
='CHICAGO');

33. WAQTD NAME AND SAL OF THE EMPLOYEES


EARNING MORE THAN KING
IN THE DEPT ACCOUNTING
SELECT
ENAME ,SAL FROM
EMP
WHERE SAL > ( SELECT
SAL FROM EMP
WHERE ENAME ='KING' ) AND DEPTNO = ( SELECT DEPTNO
FROM DEPT
WHERE DNAME =
'ACCOUNTING');

34. WAQTD DETAILS OF THE EMPLOYEES WORKING


AS SALESMAN IN THE
DEPARTEMENT SALES
New Section 1 Page
SELECT *
FROM
EMP
WHERE JOB ='SALESMAN' AND DEPTNO = ( SELECT DEPTNO
FROM DEPT
WHERE
DNAME
='SALES');

35. WAQTD NAME , SAL , JOB , HIREDATE OF THE


EMPLOYEES WORKING IN OPERATIONS DEPARTMENT AND
HIRED BEFORE KING
SELECT ENAME ,SAL , JOB , HIREDATE
FROM EMP
WHERE HIREDATE < ( SELECT HIREDATE
FROM EMP
WHERE ENAME ='KING') AND DEPTNO = ( SELECT DEPTNO
FROM DEPT
WHERE DNAME
='OPERATIONS');
36. DISPLAY ALL THE EMPLOYEES WHOSE
DEPARTMET NAMES ENDING 'S'.
SELECT
ENAME FROM
EMP
WHERE DEPTNO = ( SELECT
DEPTNO FROM DEPT
WHERE DNAME LIKE '%S' );
37. WAQTD DNAME OF THE EMPLOYEES WHOS NAMES
HAS CHARACTER ‘A’ IN IT .
SELECT
DNAME FROM
DEPT
WHERE DEPTNO IN( SELECT
DEPTNO FROM EMP
WHERE ENAME LIKE '%A%' ) ;

38. WAQTD DNAME AND LOC OF THE EMPLOYEES


WHOS SALARY IS RUPEES 800 .
SELECT DNAME ,
LOC FROM DEPT
WHERE DEPTNO = ( SELECT
DEPTNO FROM EMP
WHERE SAL = 800) ;

New Section 1 Page


39. WAQTD DNAME OF THE EMPLOYEES WHO
EARN COMISSION
SELECT
DNAME FROM
DEPT
WHERE DEPTNO = ( SELECT DEPTNO
FROM EMP
WHERE COMM IS NOT NULL );

40. WAQTD LOC OF THE EMPLOYEES IF THEY


EARN COMISSION IN DEPT 40
SELECT
LOC FROM
DEPT
WHERE DEPTNO = 40 AND DEPTNO = ( SELECT
DEPTNO FROM EMP
WHERE COMM IS NOT NULL ) ;

SELECT
LOC FROM
DEPT
WHERE DEPTNO = ( SELECT DEPTNO
FROM EMP
WHERE COMM IS NOT NULL AND DEPTNO = 40 ) ;

MAX & MIN :

EID ENAM SAL DEPTN


E O
1 ALLEN 1000 20
2 BLAKE 2000 10
3 CLARK 3000 30
4 MILLE 1500 10
R
5 ADAM 2500 20
S

New Section 1 Page


1. WAQTD maximum salary of an employee .

SELECT MAX( SAL )


FROM EMP ;

2. WAQTD name of the employee getting maximum salary .

SELECT ENAME , MAX( SAL )


FROM EMP ;

SELECT ENAME
FROM EMP
WHERE SAL = MAX( SAL ) ;

SELECT ENAME
FROM EMP
WHERE SAL = ( SELECT MAX( SAL )
FROM EMP ) ;

3. WAQTD name and salary earned by the employee


getting Minimum salary .

SELECT ENAME , SAL


FROM EMP
WHERE SAL = ( SELECT MIN( SAL )
FROM EMP ) ;

ASSIGNMENT ON MAX & MIN :

41. WAQTD NAME OF THE EMPLOYEE EARNING


MAXIMUM SALARY
42. WAQTD NAME OF THE EMPLOYEE EARNING
MINIMUM SALARY
43. WAQTD NAME AND HIREDATE OF THE EMPLOYEE
HIRED BEFORE
ALL THE EMPLOYEES (FIRST EMP)
44. WAQTD NAME AND HIREDATE OF THE EMPLOYEES
HIRED AT THE LAST
45. WAQTD NAME, COMM OF THE EMPLOYEE WHO
EARNS MIN COMISSION
46. WAQTD NAME, SAL AND COMM OF THE EMPLOYEE EARNING MAXIMUM COMISSION
47. WAQTD DETAILS OF THE EMPLOYEE WHO HAS GREATEST
EMPNO
48. WAQTD DETAILS OF THE EMPLOYEES HAVING THE
LEAST HIREDATE
49. WAQTD DETAILS OF THE EMPLOYEES EARNING
LEAST ANNUAL SALARY
50. WAQTD NAME , ANNUAL SALARY OF THE EMPLOYEES IF
THEIR ANNUAL SALARY IS MORE THAN ALL THE
SALESMAN

New Section 1 Page


41. WAQTD NAME OF THE EMPLOYEE EARNING
MAXIMUM SALARY
SELECT
ENAME FROM
EMP
WHERE SAL = ( SELECT MAX(SAL)
FROM EMP );

42. WAQTD NAME OF THE EMPLOYEE EARNING


MINIMUM SALARY
SELECT
ENAME FROM
EMP
WHERE SAL = ( SELECT MIN(SAL)
FROM EMP );
43. WAQTD NAME AND HIREDATE OF THE EMPLOYEE
HIRED BEFORE
ALL THE EMPLOYEES (FIRST EMP)
SELECT ENAME ,
HIREDATE FROM EMP
WHERE HIREDATE = ( SELECT
MIN(HIREDATE) FROM EMP );

44. WAQTD NAME AND HIREDATE OF THE EMPLOYEES


HIRED AT THE LAST
SELECT ENAME ,
HIREDATE FROM EMP
WHERE HIREDATE = ( SELECT
MAX(HIREDATE) FROM EMP );

45. WAQTD NAME, COMM OF THE EMPLOYEE WHO


EARNS MIN COMISSION
SELECT ENAME ,
COMM FROM EMP
WHERE COMM= ( SELECT
MIN(COMM) FROM EMP );

46. WAQTD NAME, SAL AND COMM OF THE


EMPLOYEE EARNING MAXIMUM
COMISSION
SELECT ENAME ,SAL,
COMM FROM EMP
WHERE COMM= ( SELECT
MAX(COMM) FROM EMP );

47. WAQTD DETAILS OF THE EMPLOYEE WHO HAS


GREATEST EMPNO
New Section 1 Page
SELECT *
FROM
EMP
WHERE EMPNO= ( SELECT MAX(EMPNO)
FROM EMP );

48. WAQTD DETAILS OF THE EMPLOYEES HAVING THE


LEAST HIREDATE
SELECT *
FROM
EMP
WHERE EMPNO= ( SELECT MIN(EMPNO)
FROM EMP );

49. WAQTD DETAILS OF THE EMPLOYEES EARNING


LEAST ANNUAL SALARY
SELECT
ENAME FROM
EMP
WHERE SAL*12= ( SELECT MIN(SAL*12)
FROM EMP );

50. WAQTD NAME , ANNUAL SALARY OF THE EMPLOYEES IF THEIR ANNUAL


SALARY IS MORE THAN ALL THE SALESMAN
SELECT ENAME ,
SAL*12 FROM EMP
WHERE SAL*12 > ( SELECT MAX(SAL*12)
FROM EMP
WHERE JOB
='SALESMAN' ); OR
SELECT ENAME ,
SAL*12 FROM EMP
WHERE SAL*12 > ALL ( SELECT
SAL*12 FROM EMP
WHERE JOB ='SALESMAN' );

TYPES OF SUB - QUERY :


New Section 1 Page
1. SINGLE ROW SUB QUERY
2. MULTI ROW SUB QUERY

Example :

Emp
EID ENAME SAL DEPTNO
1 ALLEN 1000 20 DEPT
2 BLAKE 2000 10 DEPTN DNAM LOC
3 CLARK 3000 30 O E
4 MILLER 1500 10 10 D1 L1
5 SMITH 2500 10 20 D2 L2
30 D3 L3

1. WAQTD dname of ALLEN .

SELECT DNAME
20
FROM DEPT
WHERE DEPTNO = ( SELECT DEPTNO
FROM EMP
WHERE ENAME = 'ALLEN' ) ;

2. WAQTD dnames of allen and smith .


20
SELECT DNAME
FROM DEPT 10
WHERE DEPTNO =
( SELECT DEPTNO FROM
EMP WHERE ENAME IN
DEPTNO ( 'ALLEN' ,'SMITH' ) ) ;
20
10
Here , since the sub query returns
30
2 records we cannot use '=' Op .
10 We've to use IN Op .
10

New Section 1 Page


1. SINGLE ROW SUB QUERY :

 If the sub query returns exactly 1 record / value we call it


as Single Row Sub Query .

 If it returns only 1 value then we can use the normal


operators Or the Special Operators to compare the values
.

2. MULTI ROW SUB QUERY :

 If the sub query returns more than1 record / value we call


it as Multi Row Sub Query .
 If it returns more than 1 value then we cannot use the
normal operators We have to use only Special Operators
to compare the values .

Note : It is difficult to identify whether a query Belongs Single or Multi


row So , it is always recommended to use Special Operators to
Compare The values .

1. WAQTD ename and salary of the employees earning more than


Employees of dept 10 .

EID ENAM SAL DEPTN


E O
1 ALLE 1000 20
N
2 BLAK 2000 10
E
3 CLAR 3000 30
K
4 MILLE 1500 10
R
5 SMITH 2500 10
2000
1500
SELECT ENAME , SAL
FROM EMP 2500
WHERE SAL > ( SELECT SAL
FROM EMP
WHERE DEPTNO = 10 ) ;

New Section 1 Page


Here we cannot use > symbol to compare
Multiple values .

We cant use IN or. NOT IN as well because It


is used for = and != symbols .

Therefore we have to use Sub Query Operators


For Comparing Relational Operators such as (

Sub Query Operators :


1. ALL :

"It is special Op used along with a relational Op ( > , < , > = , <= )
to compare the values present at the RHS ".
 ALL Op returns true if all the values at the RHS have satisfied
the condition .

Example :
2000
1500
CLARK ,300
2500
0

SELECT ENAME , ( SELECT SAL


SAL FROM EMP
FROM EMP WHERE DEPTNO = 10 ) ;
WHERE SAL > ALL

SAL
1000
2000 1000 > ALL ( 2000 , 1500 , 2500 )
3000 1000 > 2000 False
1500 1000 > 1500 False
2500 1000 > 2500 False

New Section 1 Page


2000 > ALL ( 2000 , 1500 , 2500 )

2000 > 2000 False


2000 > 1500 True
2000 > 2500 False

3000 > ALL ( 2000 , 1500 , 2500 )

3000 > 2000 True


3000 > 1500 True
3000 > 2500 True

1500 > ALL ( 2000 , 1500 , 2500 )

1500 > 2000 False


1500 > 1500 False
1500 > 2500 False

2500 > ALL ( 2000 , 1500 , 2500 )

2500 > 2000 True


2500 > 1500 True
2500 > 2500 False

2. ANY :

"It is special Op used along with a relational Op ( > , < , > = , <= )
to compare the values present at the RHS ".
• ANY Op returns true if one of the values at the RHS have
satisfied the condition .

Example :
2000
1500
2500
SELECT ENAME ,
SAL FROM EMP
WHERE SAL > ANY ( SELECT SAL
FROM EMP
WHERE DEPTNO = 10 ) ;

New Section 1 Page


SAL
1000
1000 > ANY ( 2000 , 1500 , 2500 )
2000
3000
1500 1000 > 2000 False
2500 1000 > 1500 False
1000 > 2500 False

2000 > ANY ( 2000 , 1500 , 2500 )

2000 > 2000 False


2000 > 1500 True
2000 > 2500 False

3000 > ANY ( 2000 , 1500 , 2500 )

3000 > 2000 True


3000 > 1500 True
3000 > 2500 True

1500 > ANY ( 2000 , 1500 , 2500 )

1500 > 2000 False


1500 > 1500 False
1500 > 2500 False

2500 > ANY ( 2000 , 1500 , 2500 )

2500 > 2000 True


2500 > 1500 True
2500 > 2500 False
1. WAQTD name of the employee if the employee earns less
than The employees working as salesman .

SELECT ENAME
FROM EMP
WHERE SAL < ALL ( SELECT SAL
FROM EMP
WHERE JOB='SALESMAN' ) ;

2. WAQTD name of the employee if the employee earns less


than At least a salesman .

SELECT ENAME
FROM EMP
WHERE SAL < ANY ( SELECT SAL
FROM EMP
WHERE JOB ='SALESMAN' ) ;

New Section 1 Page


3. WAQTD names of the employees earning more than ADAMS .

SELECT ENAME
FROM EMP
WHERE SAL > ALL ( SELECT SAL
FROM EMP
WHERE ENAME ='ADAMS' ) ;

ASSIGNMENT ON TYPES OF SUB QUERY .

51. WAQTD NAME OF THE EMPLOYEES EARNING


SALARY MORE THAN THE SALESMAN
52. WAQTD DETAILS OF THE EMPLOYEES HIRED AFTER
ALL THE CLERKS
53. WAQTD NAME AND SALARY FOR ALL THE EMPLOYEES
IF THEY ARE EARNING LESS THAN ATLEST A MANAGER
54.WAQTD NAME AND HIREDATE OF EMPLOYEES HIRED
BEFORE ALL THE MANAGERS
55. WAQTD NAMES OF THE EMPLOYEES HIRED AFTER ALL
THE MANAGERS AND EARNING SALARY MORE THAN
ALL THE CLERKS
56. WAQTD DETAILS OF THE EMPLOYEES WORKING
AS CLERK AND HIRED BEFORE ATLEST A SALESMAN
57.WAQTD DETAILS OF EMPLOYEES WORKING IN
ACCOUNTING OR SALES DEPT
58. WAQTD DEPARTMENT NAMES OF THE EMPOYEES
WITH NAME SMITH , KING AND MILLER
59. WAQTD DETAILS OF EMPLOYEES WORKING
NEWYORK OR CHICAGO
60. WAQTD EMP NAMES IF EMPLOYEES ARE HIRED
AFTER ALL THE EMPLOYEES OF DEPT 10

NESTED SUB QUERY :

" A sub query written inside a sub query is known as Nested Subquery "

 WE CAN NEST ABOUT 255 SUB QUERIES

1. WAQTD maximum salary given to an employee .

SELECT MAX( SAL 5000


) FROM EMP ;

2. WAQTD second maximum salary given to an


employee . 4000
SELECT MAX( SAL )
FROM MP 5000

New Section 1 Page


WHERE SAL < ( SELECT MAX( SAL)
FROM EMP ) ;
SAL
1000
2000
4000
3000
5000

3. WAQTD 3rd maximum salary .

SELECT MAX( SAL ) 3000


FROM EMP
WHERE SAL < ( SELECT MAX( SAL ) 4000
FROM EMP
WHERE SAL < ( SELECT MAX( SAL ) 5000
FROM EMP ) )

4. WAQTD 4th maximum salary .

SELECT MAX( SAL ) 2000


FROM EMP
WHERE SAL < ( SELECT MAX( SAL ) 3000
FROM EMP
WHERE SAL < ( SELECT MAX( SAL ) 4000
FROM EMP
WHERE SAL < ( SELECT MAX( SAL ) 5000
FROM EMP ) ) )

5. WAQTD 3 minimum salary .

SELECT MIN(SAL )
FROM EMP
WHERE SAL > ( SELECT MIN(SAL )
FROM EMP
WHERE SAL > ( SELECT MIN ( SAL )
FROM EMP ) ) ;

6. WAQTD Dept name of the employee getting 2nd


Minimum salary .

SELECT DNAME
FROM DEPT
WHERE DEPTNO = ( SELECT DEPTNO
FROM EMP
WHERE SAL = (SELECT MIN( SAL )
FROM EMP
New Section 1 Page 1
WHERE SAL > ( SELECT MIN( SAL )
FROM EMP ) ) );

REMEMBER :

MAXIMUM MAX( ) <


MINIMUM MIN( ) >

ASSIGNMENT ON NESTED SUB QUERY :

61. WAQTD 2ND MINIMUM SALARY


62. WAQTD 5TH MAXIMUM SALARY
63. WAQTD NAME OF THE EMPLOYEE EARNING
3RD MAXIMUM SALARY
64. WAQTD EMPNO OF THE EMPLOYEE EARNING
2D MAXIMUM SALARY
65. WAQTD DEPARTMENT NAME OF AN EMPLOYEE GETTING
4TH MAX SAL
66. WAQTD DETAILS OF THE EMPLOYEE WHO WAS HIRED 2nd
67. WAQTD NAME OF THE EMPLOYEE HIRED BEFORE
THE LAST EMPLOYEE
68. WAQTD LOC OF THE EMPLOYEE WHO WAS HIRED FIRST
69. WAQTD DETAILS OF THE EMPLOYEE EARNING
7TH MINIMUM SALARY
70. WAQTD DNAME OF EMPLOYEE GETTING 2ND
MAXIMUM SALARY

EMPLOYEE AND MANAGER RELATION :

EID ENAME MGR


1 ALLEN 3
2 SMITH 1
3 JAMES 2
4 KING 3

CASE 1 :

 WAQTD name of Allen's manager .


JAMES
SELECT ENAME
FROM EMP 3
WHERE EID = ( SELECT MGR
FROM EMP
WHERE ENAME1 ='ALLEN' )
2
3
4

New Section 1 Page 2


 WAQTD name of SMITH's manager .

SELECT ENAME
FROM EMP
WHERE EID = ( SELECT MGR
FROM EMP
WHERE ENAME ='SMITH' ) ;

 WAQTD name of SMITH's manager's manager .

EID ENAME MGR


1 ALLEN 3
2 SMITH 1
3 JAMES 2
4 KING 3

SELECT ENAME
FROM EMP
WHERE EID = ( SELECT MGR
FROM EMP
WHERE EID = ( SELECT MGR
FROM EMP

WHERE ENAME ='SMITH' ) ) ;

 WAQTD dname of King's Manager .

SELECT DNAME
FROM DEPT
WHERE DEPTNO = ( SELECT DEPTNO
FROM EMP
WHERE EID = ( SELECT MGR
FROM EMP
WHERE ENAME ='KING' ) ) ;

 WAQTD Location of Adams's manager's manager .

SELECT LOC
FROM DEPT
WHERE DEPTNO = ( SELECT DEPTNO
FROM EMP
WHERE EID = ( SELECT MGR
FROM EMP
WHERE EID = ( SELECT MGR
FROM EMP
WHERE ENAME ='ADAMS' ) ) ) ;

CASE -2

New Section 1 Page 3


 WAQTD Names of the employees reporting to KING.

SELECT ENAME
FROM EMP
WHERE MGR = ( SELECT EID
FROM EMP
WHERE ENAME ='KING' ) ;

 WAQTD Name and salary given to the employees


reporting To James .

SELECT ENAME , SAL


FROM EMP
WHERE MGR = ( SELECT EID
FROM EMP
WHERE ENAME ='JAMES' ) ;

To find Manager Select MGR in Sub Q


To find Employees Select EID in Sub Q

 WAQTD dname of the employee reporting to President .

SELECT DNAME
FROM DEPT
WHERE DEPTNO = ( SELECT DEPTNO

FROM EMP
WHERE MGR = ( SELECT EID
FROM EMP
WHERE JOB ='PRESIDENT' ) ) ;

 WAQTD Department details of the employees who are


reporting to MILLER .

SELECT *
FROM DEPT
WHERE DEPTNO = ( SELECT DEPTNO
FROM EMP
WHERE MGR = ( SELECT EID
FROM EMP
WHERE ENAME ='MILLER' ));

ASSIGNMENT ON EMP AND MANAGER RELATION .

71. WAQTD SMITHS REPORTING MANAGER'S NAME


72. WAQTD ADAMS MANAGER'S MANAGER NAME
73. WAQTD DNAME OF JONES MANAGER
74. WAQTD MILLER'S MANAGER'S SALARY
75. WAQTD LOC OF SMITH'S MANAGER'S MANAGER.
76. WAQTD NAME OF THE EMPLOYEES REPORTING
TO BLAKE
77. WAQTD NUMBER OF EMPLPOYEES REPORTING TO KING
78. WAQTD DETAILS OF THE EMPLOYEES REPORTING
New Section 1 Page 4
TO JONES
79. WAQTD ENAMES OF THE EMPLOYEES REPORTING
TO BLAKE'S MANAGER
80. WAQTD NUMBER OF EMPLOYEES REPORTING TO
FORD'S MANAGER

SUB QUERY :
Understand well from video

What is a Subquery? What are its types?


A subquery is a query within another query, also known as a nested query or inner query. It is used to restrict or
enhance the data to be queried by the main query, thus restricting or enhancing the output of the main query
respectively.

For example, here we fetch the contact information for students who have enrolled for the maths subject:

SELECT name, email, mob, address


FROM myDb.contacts
WHERE roll_no
IN ( SELECT roll_no FROM myDb.students
WHERE subject = 'Maths');

There are two types of subquery - Correlated and Non-Correlated.


 A correlated subquery cannot be considered as an independent query, but it can refer to the column in a table
listed in the FROM of the main query.
 A non-correlated subquery can be considered as an independent query and the output of the subquery is
substituted in the main query.

 What is Sub Query ?

A Subquery or Inner query or a Nested query is a query within another SQL query.
It involves 2 select statements.
New Section 1 Page 5
Syntax
SELECT column(s)
FROM table_name
WHERE col_name operator ( subquery );

 Explain ? ( draw )

 Why ? When ?
 Types of Sub Query
 Single Row Sub Query
 Multi Row Sub Query
 Sub Query Operators
 ALL
 ANY
 Nested Sub Query .

SQL Sub Queries


Example
Get names of all students who scored more than class average.
Step 1. Find the avg of class Step
Step 2. Find the names of students with marks > avg

71. WAQTD SMITHS REPORTING MANAGER'S


NAME SELECT ENAME
FROM EMP
WHERE EID=( SELECT
MGR FROM EMP
WHERE ENAME ='SMITH' );

72. WAQTD ADAMS MANAGER'S MANAGER


NAME SELECT ENAME
FROM EMP
New Section 1 Page 6
WHERE EID=( SELECT
MGR FROM EMP
WHERE ENAME ='ADAMS' );

73. WAQTD DNAME OF JONES


MANAGER SELECT DNAME
FROM EMP
WHERE DEPTNO = ( SELECT DEPTNO
FROM EMP
WHERE EID=( SELECT
MGR FROM EMP
WHERE ENAME ='JONES' ));

74. WAQTD MILLER'S MANAGER'S SALARY


SELECT SAL
FROM EMP
WHERE EID=( SELECT
MGR FROM EMP
WHERE ENAME ='MILLER' );

75. WAQTD LOC OF SMITH'S MANAGER'S


MANAGER. SELECT LOC
FROM EMP
WHERE DEPTNO = (SELECT
DEPTNO FROM EMP
WHERE EID = ( SELECT
MGR FROM EMP
WHERE EID=( SELECT
MGR FROM EMP
WHERE ENAME ='JONES' )));

76. WAQTD NAME OF THE EMPLOYEES REPORTING TO


BLAKE SELECT ENAME
FROM EMP
WHERE MGR=( SELECT
EID FROM EMP
WHERE ENAME ='BLAKE' );

77. WAQTD NUMBER OF EMPLPOYEES REPORTING TO


KING SELECT COUNT(ENAME)
FROM EMP
WHERE MGR=( SELECT
EID FROM EMP
New Section 1 Page 7
WHERE ENAME ='KING' );

78. WAQTD DETAILS OF THE EMPLOYEES REPORTING TO


JONES
SELECT *
FROM
EMP
WHERE MGR=( SELECT
EID FROM EMP
WHERE ENAME ='JONES' );

79. WAQTD ENAMES OF THE EMPLOYEES REPORTING


TO BLAKE'S MANAGER
SELECT
ENAME FROM
EMP
WHERE MGR =( SELECT
EID FROM EMP
WHERE EID = ( SELECT
MGR FROM EMP
WHERE ENAME ='BLAKE' ) );

OR

SELECT
ENAME FROM
EMP
WHERE MGR =( SELECT MGR
FROM EMP
WHERE ENAME ='BLAKE' );

80. WAQTD NUMBER OF EMPLOYEES REPORTING TO


FORD'S MANAGER
SELECT
COUNT(ENAME) FROM
EMP
WHERE MGR =( SELECT
MGR FROM EMP
WHERE ENAME ='FORD' );

New Section 1 Page 8


JOINS

"The process of retrieval of data from multiple tables


simultaneously is known as JOINS ".

The SQL Join clause is used to combine records (rows) from two or more
tables in a SQL database based on a related column between the two.

Join is used to combine rows from two or more tables, based on a


related column between them.

Types of JOINS .

New Section 1 Page 9


We have 5 types of joins

1. CARTESIAN JOIN / CROSS JOIN


2. INNER JOIN / EQUI JOIN

3. OUTER JOIN
i. LEFT OUTER JOIN
ii. RIGHT OUTER JOIN
iii. FULL OUTER JOIN
4. SELF JOIN
5. NATURAL JOIN .

1. CARTESIAN JOIN / CROSS JOIN :

In Cartesian Join a record from table 1 will be merged with


All the records of table 2 .
Cross join can be defined as a cartesian product of the two tables included in the join. The table after join contains the
same number of rows as in the cross-product of the number of rows in the two tables. If a WHERE clause is used in
cross join then the query will work like an INNER JOIN

EMP DEPT

ENAME DEPTNO DNAME DEPTNO


A 20 D1 10
B 30 D2 20
C 10 D3 30

New Section 1 Page


 Number of Columns in the Result table : will be equivalent
to the summations of columns present in both the tables .

Number of Col = Number of Col T1 + Number of Col T2


2+2
= 4 Columns

 Number of Rows in the Result table : will be equivalent to


the product of number of rows present in the both the tables .

Number of Rows = Number of Rows T1 x Number of Rows T2


3x3
= 9 Rows .

Result Table :

ENAME DEPTNO DNAME DEPTNO


A 20 D1 10
A 20 D2 20
A 20 D3 30
B 30 D1 10
B 30 D2 20
B 30 D3 30
C 10 D1 10
C 10 D2 20
C 10 D3 30

SYNTAX:

1. ANSI [ American National Standard Institute ]

SELECT Column_Name
FROM Table_Name1 CROSS JOIN Table_Name2 ;

2. Oracle

SELECT Column_Name
FROM Table_Name1 , Table_Name2 ;

Example :

1. WAQTD ename and dept name for all the employees .

New Section 1 Page


SELECT ENAME , DNAME
FROM EMP , DEPT ;

SELECT ENAME , DNAME


FROM EMP CROSS JOIN DEPT
;

2. INNER JOIN :

"It is used to Obtain only Matching Records "


Or " A records which has a Pair " .
Retrieves records that have matching values in both
tables involved in the join. This is the widely used
join for queries.
Returns records that have matching values in
both tables

Syntax

SELECT column(s)
FROM tableA
INNER JOIN tableB
ON tableA.col_name = tableB.col_name;

SELECT *
FROM student
INNER JOIN course
ON student.student_id = course.student_id;

New Section 1 Page


EMP DEPT
ENAME DEPTNO DNAME DEPTNO
A 20 D1 10
B 30 D2 20
C 10 D3 30

JOIN Condition : It is a condition on which the two tables


Are merged .

Syntax: Table_Name1.Col_Name = Table_Name2.Col_Name

Join Condition :EMP.DEPTNO = DEPT.DEPTNO

20 = 10 False 30 = 10 False 10 = 10 True


20 = 20 True 30 = 20 False 10 = 20 False
20 = 30 False 30 = 30 True 10 = 30 False

Result Table :

ENAME EMP.DEPTNO DNAME DEPT.DEPTNO


A 20 D2 20
B 30 D3 30
C 10 D1 10

New Section 1 Page


SYNTAX:

1. ANSI [ American National Standard Institute ] SELECT

Column_Name

FROM Table_Name1 INNER JOIN Table_Name2


ON < JOIN_CONDITION> ;

SELECT *
FROM EMP INNER JOIN DEPT
ON EMP.DEPTNO = DEPT.DEPTNO ;

2. Oracle

SELECT Column_Name
FROM Table_Name1 , Table_Name2
1. WAQTD ename and dept name for all the employees .

SELECT ENAME , DNAME


FROM EMP , DEPT
WHERE EMP.DEPTNO = DEPT.DEPTNO ;

2. WAQTD ename and loc for all the employees working


as Manager .

SELECT ENAME , LOC


FROM EMP , DEPT
WHERE EMP.DEPTNO = DEPT.DEPTNO AND JOB
='MANAGER' ;

3. WAQTD ename , sal and dname of the employee working


as Clerk in dept 20 with a salary of more than 1800 .

SELECT ENAME , SAL , DNAME


FROM EMP , DEPT
WHERE EMP.DEPTNO =DEPT.DEPTNO AND
EMP.DEPTNO = 20 AND JOB ='CLERK' AND SAL > 1800 ;

4. WAQTD ename deptno , dname and loc of the employee


earning more than 2000 in New York .

New Section 1 Page


SELECT ENAME , EMP.DEPTNO , DNAME
FROM EMP , DEPT
WHERE EMP.DEPTNO = DEPT.DEPTNO AND SAL > 2000
AND LOC ='NEW YORK' ;

ASSIGNMENT ON INNER JOIN :

1. NAME OF THE EMPLOYEE AND HIS LOCATION OF ALL


THE EMPLOYEES .
WAQTD DNAME AND SALARY FOR ALL THE EMPLOYEE WORKING IN ACCOUNTING.

2. WAQTD DNAME AND ANNUAL SALARY FOR ALL


EMPLOYEES WHOS SALARY IS MORE THAN 2340
4.WAQTD ENAME AND DNAME FOR EMPLOYEES
HAVING CAHARACTER 'A' IN THEIR DNAME
5. WAQTD ENAME AND DNAME FOR ALL THE
EMPLOYEES WORKING AS SALESMAN
6. WADTD DNAME AND JOB FOR ALL THE EMPLOYEES
WHOS JOB AND DNAME STARTS WITH CHARACTER 'S'
7. WAQTD DNAME AND MGR NO FOR
EMPLOYEES REPORTING TO 7839
8. WAQTD DNAME AND HIREDATE FOR EMPLOYEES
HIRED AFTER 83 INTO ACCOUNTING OR RESEARCH DEPT
9.WAQTD ENAME AND DNAME OF THE EMPLOYEES WHO
ARE GETTING COMM IN DEPT 10 OR 30
10.WAQTD DNAME AND EMPNO FOR ALL THE EMPLOYEES
WHO'S EMPNO ARE (7839,7902) AND ARE WORKING IN LOC
NEW YORK.

Answers :

1. NAME OF THE EMPLOYEE AND HIS LOCATION OF ALL


THE EMPLOYEES .
SELECT ENAME ,
LOC FROM EMP ,
DEPT
WHERE EMP.DEPTNO = DEPT.DEPTNO ;

2. WAQTD DNAME AND SALARY FOR ALL THE


EMPLOYEE WORKING IN
ACCOUNTING.
SELECT DNAME ,
SAL FROM EMP ,
DEPT
WHERE EMP.DEPTNO =
DEPT.DEPTNO AND DNAME
='ACCOUNTING';

3. WAQTD DNAME AND ANNUAL SALARY FOR


ALL EMPLOYEES WHOS SALARY
New Section 1 Page
IS MORE THAN 2340
SELECT DNAME ,
SAL*12 FROM EMP ,
DEPT
WHERE EMP.DEPTNO =
DEPT.DEPTNO AND SAL > 2340 ;

4. WAQTD ENAME AND DNAME FOR EMPLOYEES


HAVING CAHARACTER 'A'
IN THEIR DNAME
SELECT ENAME ,
DNAME FROM EMP ,
DEPT
WHERE EMP.DEPTNO =
DEPT.DEPTNO AND ENAME LIKE '%A
%' ;

5. WAQTD ENAME AND DNAME FOR ALL THE EMPLOYEES


WORKING AS SALESMAN
SELECT ENAME , DNAME Customer
CNAME CID
TNXO 101
WORKING AS Y 102
SALESMAN SELECT LZL THEM1PS03WHOS
LO
ENAME , DNAME FROM
E YEE
EMP , DEPT
WHERE EMP.DEPTNO =
DEPT.DEP AND JOB ='SALESMAN'
;

6. WADTD DNAME AND JOB


FOR A JOB AND DNAME
STARTS WITH CHARACTER 'S'
SELECT DNAME
,JOB FROM EMP ,
DEPT
WHERE EMP.DEPTNO = DEPT.DEPTNO AND JOB
LIKE 'S%' AND DNAME LIKE 'S%' ;

7. WAQTD DNAME AND MGR NO FOR


EMPLOYEES REPORTING TO 7839
SELECT DNAME ,
MGR FROM EMP ,
DEPT
WHERE EMP.DEPTNO =
DEPT.DEPTNO AND MGR = 7839 ;

8. WAQTD DNAME AND HIREDATE FOR EMPLOYEES


HIRED AFTER 83 INTO
ACCOUNTING OR RESEARCH DEPT

New Section 1 Page


SELECT DNAME ,
HIREDATE FROM EMP ,
DEPT
WHERE EMP.DEPTNO = DEPT.DEPTNO
AND HIREDATE > '31-DEC-83' AND DNAME
IN ('ACCOUNTING' ,'RESEARCH' );

9. WAQTD ENAME AND DNAME OF THE EMPLOYEES


WHO ARE GETTING COMM
IN DEPT 10 OR 30
SELECT ENAME ,
DNAME FROM EMP ,
DEPT
WHERE EMP.DEPTNO = DEPT.DEPTNO
AND COMM IS NOT NULL AND EMP.DEPTNO IN ( 10 , 30 ) ;

10. WAQTD DNAME AND EMPNO FOR ALL THE


EMPLOYEES WHO'S EMPNO ARE
(7839,7902) AND ARE WORKING IN LOC NEW YORK.
SELECT DNAME ,
EMPNO FROM EMP ,
DEPT
WHERE EMP.DEPTNO = DEPT.DEPTNO
AND EMPNO IN (7839,7902) AND LOC = 'NEW YORK' ;

OUTER JOIN

"It is used to Obtain Un-Matched Records "

1. Left Outer Join :

"It is used to obtain Un-Matched Records of Left Table


Along with Matching Records ".

Returns all records from the left table, and the matched
records from the right table

Retrieves all the records/rows from the left and the matched records/rows
from the right table

Syntax
SELECT column(s)
FROM tableA
LEFT JOIN tableB
ON tableA.col_name = tableB.col_name;
New Section 1 Page
SELECT *
FROM student as s
LEFT JOIN course as c
ON s.student_id = c.student_id;

New Section 1 Page


SYNTAX:

1. ANSI [ American National Standard Institute ]

SELECT Column_Name
FROM Table_Name1 LEFT [OUTER] JOIN Table_Name2
ON < JOIN_CONDITION> ;

SELECT *
FROM EMP LEFT JOIN DEPT
ON EMP.DEPTNO = DEPT.DEPTNO ;

2. Oracle

SELECT Column_Name
FROM Table_Name1 , Table_Name2
WHERE Table1.Col_Name = Table2.Col_Name (+) ;

SELECT *
FROM EMP , DEPT
WHERE EMP.DEPTNO = DEPT.DEPTNO (+) ;

 WAQTD names and dnames of all the employees even


though the employees Don’t work in any dept .

SELECT ENAME , DNAME


FROM EMP , DEPT
WHERE EMP.DEPTNO = DEPT.DEPTNO(+) ;

ENAME DNAME
A D2
C D1
B Null
D Null

2. Right Outer Join :


New Section 1 Page
"It is used to obtain Un-Matched Records of Right
Table Along with Matching Records ".
Retrieves all the records/rows from the right and the matched records/rows from
the left table.

Returns all records from the right table, and the matched
records from the left table

Syntax
SELECT column(s)
FROM tableA
RIGHT JOIN tableB

ON tableA.col_name = tableB.col_name;

SELECT *
FROM student as s
RIGHT JOIN course as c
ON s.student_id = c.student_id;

New Section 1 Page


SYNTAX:

1. ANSI [ American National Standard Institute ] SELECT Column_Name


FROM Table_Name1 RIGHT[OUTER] JOIN Table_Name2
ON < JOIN_CONDITION> ;

SELECT *
FROM EMP RIGHT JOIN DEPT
ON EMP.DEPTNO = DEPT.DEPTNO ;

2. Oracle

SELECT Column_Name
FROM Table_Name1 , Table_Name2
WHERE Table1.Col_Name (+) = Table2.Col_Name ;

SELECT *
FROM EMP , DEPT
WHERE EMP.DEPTNO(+) = DEPT.DEPTNO ;
New Section 1 Page
 WAQTD names and dnames of all the employees even
though the there are no employees in a dept .

SELECT ENAME , DNAME


FROM EMP , DEPT
WHERE EMP.DEPTNO(+) = DEPT.DEPTNO ;

ENAME DNAME
A D2
C D1
Null D3
Null D4

1. Full Outer Join :

"It is used to obtain Un-Matched Records of both Left


& Right Table Along with Matching Records ".

Returns all records when there is a match in either left or


right table

Retrieves all the records where there is a match in either the left or right table.

LEFT JOIN UNION RIGHT JOIN

New Section 1 Page


SYNTAX:

1. ANSI [ American National Standard Institute ] SELECT Column_Name


FROM Table_Name1 FULL [OUTER] JOIN Table_Name2
ON < JOIN_CONDITION> ;

SELECT *
FROM EMP FULL JOIN DEPT
ON EMP.DEPTNO = DEPT.DEPTNO ;

 WAQTD names and dnames of all the employees and depts


even though the employees Don’t work in any dept and a
dept having no employees .

SELECT ENAME , DNAME


FROM EMP FULL OUTER DEPT
ON EMP.DEPTNO = DEPT.DEPTNO;
New Section 1 Page
ENAM DNAM
E E
A D2
C D1
B Null
D Null
Null D3
Null D4

SELF JOIN :

"Joining a table by itself is known as Self Join "

It is a regular join but the table is joined with itself.

A self-JOIN is a case of regular join where a table is joined to itself based on some relation between its own
column(s). Self-join uses the INNER JOIN or LEFT JOIN clause and a table alias is used to assign different names to
the table within the query

Syntax SELECT column(s) FROM table as a JOIN table as b ON a.col_name = b.col_name;

Why ? / When ?

"Whenever the data to select is in the same table but present


In different records we use self-join ".

Example :

New Section 1 Page


EMP E1 EMP E2
EID ENAME E1.MGR E2.EID ENAME MGR
1 ALLEN 3 1 ALLEN 3
2 SMITH 1 2 SMITH 1
3 MILLER 2 3 MILLER 2

Join Condition : E1.MGR = E2.EID

Result table :

E1.eid E1.ename E1.mgr E2.eid E2.ename E2.mgr


1 ALLEN 3 3 MILLER 2
2 SMITH 1 1 ALLEN 3
3 MILLER 2 2 SMITH 1
SYNTAX:

1. ANSI [ American National Standard Institute ] SELECT Column_Name


FROM Table_Name1 JOIN Table_Name2
ON < JOIN_CONDITION> ;

SELECT *
FROM EMP E1 JOIN EMP E2
ON E1.MGR = E2.EID ;

2. Oracle:

SELECT Column_Name
FROM Table_Name1T1 , Table_Name2 T2 WHERE < Join_Condition > ;

SELECT *
FROM EMP E1 , EMP E2 WHERE E1.MGR = E2.EID ;
1. WAQTD Ename and Manager's name for all the employees .

SELECT E1.ENAME , E2.ENAME


FROM EMP E1 , EMP E2
WHERE E1.MGR = E2.EMPNO ;

2. WAQTD Ename , sal along with manager's name


and manager's salary for all the employees .

New Section 1 Page


SELECT E1.ENAME , E1.SAL , E2.ENAME , E2.SAL
FROM EMP E1 , EMP E2
WHERE E1.MGR = E2.EMPNO ;

3. WAQTD ename , manager's name along with their


deptno If employee is working as clerk .

SELECT E1.ENAME , E2.ENAME , E1.DEPTNO ,


E2.DEPTNO
FROM EMP E1 , EMP E2
WHERE E1.MGR = E2.EMPNO AND E1.JOB='CLERK' ;

4. WAQTD ename , manager's job if manager works as Analyst .

SELECT E1.ENAME , E2.JOB


FROM EMP E1 , EMP E2
WHERE E1.MGR = E2.EMPNO
AND E2.JOB ='ANALYST' ;

5. WAQTD ename and manager's name along with their job


if emp and manager are working for same designation .

SELECT E1.ENAME , E2.ENAME , E1.JOB , E2.JOB


FROM EMP E1 , EMP E2
WHERE E1.MGR = E2.EMPNO
AND E1.JOB = E2.JOB ;

6. WAQTD ename emp salary manager's name manager's


salary If manager earns more than employee .

SELECT E1.ENAME , E1.SAL , E2.ENAME , E2.SAL


FROM EMP E1 , EMP E2
WHERE E1.MGR = E2.EMPNO
AND E2.SAL > E1.SAL ;
7. WAQTD ename and manager's name along with
manager's commission if manager earns commission .

SELECT E1.ENAME , E2.ENAME , E2.COMM


FROM EMP E1 , EMP E2
WHERE E1.MGR = E2.EMPNO
AND E2.COMM IS NOT NULL ;

NOTE : TO join 'N' number of tables we need to write 'N-1'


number of join conditions

ASSIGNMENT ON SELF JOIN :

1. WAQTD NAME OF THE EMPLOYEE AND HIS


MANAGER'S NAME IF EMPLOYEE IS WORKING AS CLERK

New Section 1 Page


2. WAQTD NAME OF THE EMPLOYEE AND
MANAGER'S DESIGNATION IF MANAGER WORKS IN
DEPT 10 OR 20

3. WAQTD NAME OF THE EMP AND MANAGERS SALARY IF


EMPLOYEE AND MANAGER BOTH EARN MORE THAN
2300

4. WAQTD EMP NAME AND MANAGER'S HIREDATE


IF EMPLOYEE WAS HIRED BEFORE1982

5. WAQTD EMP NAME AND MANAGER'S COMM IF


EMPLOYEE WORKS AS SALESMAN AND
MANAGER WORKS IN DEPT 30

6. WAQTD EMP NAME AND MANAGER NAME AND


THEIR SALARIES IF EMPLOYEE EARNS MORE THAN
MANAGER

7. WAQTD EMP NAME AND HIREDATE , MANAGER


NAME AND HIREDATE IF
MANAGER WAS HIRED BEFORE EMPLOYEE

8. WAQTD EMP NAME AND MANAGER NAME IF BOTH


ARE WORKING IN SAME JOB

9. WAQTD EMP NAME AND MANAGER NAME IF


MANAGER IS WORKING AS ACTUAL MANAGER

10. WAQTD EMP NAME AND MANAGER NAME ALONG


WITH THEIR ANNUAL SALARIES IF EMPLOYEE WORKS
IN DEPT 10 , 20 AND MANAGER'S SAL IS GREATER THAN
EMPLOYEES SALARY .

11. WAQTD EMPLOYEE'S NAME AND


MANAGER'S DESIGNATION FOR ALL THE
EMPLOYEES

12. WAQTD EMPLOYEE'S NAME AND MANAGER'S


SALARY FOR ALL THE EMPLOYEES IF MANAGER'S
SALARY ENDS WITH 50

Examples :

EMP DEPT

EMP.DEPTNO = DEPT.DEPTNO

New Section 1 Page


E1 E2

E1.MGR = E2.EMPNO

E1
E2 E3

E1.MGR = E2.EMPNO
E2.MGR = E3.EMPNO
E1.MGR = E2.EMPNO

E1 D1 E2 D2

E1.DEPTNO = D1.DEPTNO E2.DEPTNO = D2.DEPTNO

5. NATURAL JOIN :

"It behaves as INNER JOIN if there is a relation between the given


two tables , else it behaves as CROSS JOIN" .

Syntax:

ANSI :
SELECT Col_Name
FROM Table_Name1 NATURAL JOIN Table_Name2;

Emp DEPT
ENAME DEPTNO DNAME DEPTNO
A 20 D1 10
B 30 D2 20
C 10 D3 30
Result Table : has a relation ( inner join )
DEPTNO ENAME DNAME
20 A D2
30 B D3
10 C D1

Emp
CUSTOMER
ENAME DEPTNO
New Section 1 Page
CNAME CID
X 101
Y 102
Z 103

Result Table : has no relation ( cross join )

ENAME DEPTNO CNAME CID


A 20 X 101
A 20 Y 102
A 20 Z 103
B 30 X 101
B 30 Y 102
B 30 Z 103
C 10 X 101
C 10 Y 102
C 10 Z 103

QUESTIONS:

1. WAQTD NAME OF THE EMPLOYEE AND HIS


MANAGER'S NAME IF EMPLOYEE IS WORKING AS CLERK
SELECT E1.ENAME , E2.ENAME
FROM EMP E1 , EMP E2
WHERE E1.MGR = E2.EMPNO
AND E1.JOB = 'CLERK';

2. WAQTD NAME OF THE EMPLOYEE AND


MANAGER'S DESIGNATION IF MANAGER WORKS IN
DEPT 10 OR 20 SELECT E1.ENAME , E2.JOB
FROM EMP E1 , EMP E2
WHERE E1.MGR = E2.EMPNO
AND E2.DEPTNO IN ( 10 , 20 );

3. WAQTD NAME OF THE EMP AND MANAGERS SALARY IF


EMPLOYEE AND MANAGER BOTH EARN MORE THAN
2300 SELECT E1.ENAME , E2.SAL
FROM EMP E1 , EMP E2
WHERE E1.MGR = E2.EMPNO
AND E1.SAL > 2300 AND E2.SAL>2300 ;

4. WAQTD EMP NAME AND MANAGER'S HIREDATE


IF EMPLOYEE WAS HIRED BEFORE1982
New Section 1 Page
SELECT E1.ENAME , E2.HIREDATE
FROM EMP E1 , EMP E2
WHERE E1.MGR = E2.EMPNO
AND E1.HIREDATE < '01-JAN-82'
;

5. WAQTD EMP NAME AND MANAGER'S COMM IF


EMPLOYEE WORKS AS SALESMAN AND
MANAGER WORKS IN DEPT 30
SELECT E1.ENAME , E2.COMM
FROM EMP E1 , EMP E2
WHERE E1.MGR = E2.EMPNO
AND E1.JOB = 'SALESMAN' AND E2.DEPTNO = 30 ; ;

6. WAQTD EMP NAME AND MANAGER NAME AND


THEIR SALARIES IF EMPLOYEE EARNS MORE THAN
MANAGER SELECT E1.ENAME, E1.SAL , E2.ENAME ,
E2.SAL
FROM EMP E1 , EMP E2
WHERE E1.MGR =
E2.EMPNO AND E1.SAL >
E2.SAL ;

7. WAQTD EMP NAME AND HIREDATE , MANAGER


NAME AND HIREDATE IF
MANAGER WAS HIRED BEFORE EMPLOYEE
SELECT E1.ENAME ,E1.HIREDATE , E2.ENAME , E2.HIREDATE
FROM EMP E1 , EMP E2
WHERE E1.MGR = E2.EMPNO
AND E2.HIREDATE < E1.HIREDATE ;

8. WAQTD EMP NAME AND MANAGER NAME IF BOTH


ARE WORKING IN SAME JOB
SELECT E1.ENAME , E2.ENAME
FROM EMP E1 , EMP E2
WHERE E1.MGR = E2.EMPNO
AND E1.JOB = E2.JOB ;

9. WAQTD EMP NAME AND MANAGER NAME IF


MANAGER IS WORKING AS ACTUAL MANAGER
SELECT E1.ENAME , E2.ENAME
FROM EMP E1 , EMP E2
WHERE E1.MGR = E2.EMPNO
AND E2.JOB = 'MANAGER';

10. WAQTD EMP NAME AND MANAGER NAME ALONG


WITH THEIR ANNUAL SALARIES IF EMPLOYEE WORKS
IN DEPT 10 , 20 AND MANAGER'S SAL IS GREATER THAN
EMPLOYEES SALARY .

New Section 1 Page


SELECT E1.ENAME , E1.SAL*12 , E2.ENAME , E2.SAL*12
FROM EMP E1 , EMP E2
WHERE E1.MGR = E2.EMPNO
AND E1.DEPTNO IN ( 10,20) AND E2.SAL > E1.SAL ;
11. WAQTD EMPLOYEE'S NAME AND
MANAGER'S DESIGNATION FOR ALL THE
EMPLOYEES SELECT E1.ENAME , E2.JOB
FROM EMP E1 , EMP E2
WHERE E1.MGR = E2.EMPNO
;

12. WAQTD EMPLOYEE'S NAME AND MANAGER'S


SALARY FOR ALL THE EMPLOYEES IF MANAGER'S
SALARY ENDS WITH 50
SELECT E1.ENAME , E2.SAL
FROM EMP E1 , EMP E2
WHERE E1.MGR =
E2.EMPNO AND E2.SAL LIKE
'%50' ;

Union

The UNION operator combines and returns the result-set retrieved by two or more SELECT statements.
It is used to combine the result-set of two or more SELECT statements. Gives UNIQUE records.

To use it
every SELECT should have same no. of columns
columns must have similar data types
columns in every SELECT should be in same order

Syntax
New Section 1 Page
SELECT column(s)
FROM tableA
UNION SELECT column(s) FROM tableB

What are UNION, MINUS and INTERSECT commands?


The UNION operator combines and returns the result-set retrieved by two or more SELECT statements.
The MINUS operator in SQL is used to remove duplicates from the result-set obtained by the second SELECT query
from the result-set obtained by the first SELECT query and then return the filtered results from the first.
The INTERSECT clause in SQL combines the result-set fetched by the two SELECT statements where records from
one match the other and then returns this intersection of result-sets.
Certain conditions need to be met before executing either of the above statements in SQL –
 Each SELECT statement within the clause must have the same number of columns
 The columns must also have similar data types
 The columns in each SELECT statement should necessarily have the same order

New Section 1 Page


SELECT name FROM Students /* Fetch the union of queries */
UNION
SELECT name FROM Contacts;
SELECT name FROM Students /* Fetch the union of queries with duplicates*/
UNION ALL
SELECT name FROM Contacts;

SELECT name FROM Students /* Fetch names from students */


MINUS /* that aren't present in contacts */
SELECT name FROM Contacts;

SELECT name FROM Students /* Fetch names from students */


INTERSECT /* that are present in contacts as well */
SELECT name FROM Contacts;

CO - RELATED SUB QUERY

" A query written inside another query such that the outer query and the
inner query are Dependent on each other , this is known as Co-Related Sub-
Query ".

WORKING PRINCIPLE :

New Section 1 Page


Let us consider two queries inner and outer query respectively ,
1. Outer query executes first but partially
2. The partially executed output is given as an input to the inner Query
3. The inner query executes completely and generates an output
4. The output of inner query is fed as an input to the Outer query
and Outer
Query produces the result .
5. Therefore, we can state that the outer query and the inner query both
are INTERDEPENDENT ( dependent on each other ) .

NOTE :
i. In co-related sub query a Join condition is a must , And must be
written only in the Inner Query .
ii. Co-Related sub query works with the principles of both SUB
QUERY & JOINS .

DIFFERENCE BETWEEN SUB QUERY AND CO RELATED SUB


QUERY .
SUB QUERY CO-RELATED SUB QUERY
Inner query executes first Outer query executes first
Outer query is dependent on inner Both are interdependent
query
Join condition not mandatory Join condition is mandatory and
must be written in inner query
Outer query executes Once Outer query executes Twice .

1. WAQTD dnames in which there are employees working .

SELECT DNAME
FROM DEPT D
New Section 1 Page
WHERE D.DEPTNO IN ( SELECT E.DEPTNO
FROM EMP E
WHERE D.DEPTNO = E.DEPTNO ) ;

2. WAQTD dname in which there are no employees working .

SELECT DNAME
FROM DEPT D
WHERE D.DEPTNO NOT IN ( SELECT E.DEPTNO
FROM EMP E
WHERE D.DEPTNO = E.DEPTNO ) ;

EXISTS & NOT EXISTS OPERATORS :

1. EXISTS : " Exists Op is a Unary Op ( One Operand ) which can accept


One Operand Towards RHS and that Operand has to
be A Co-related Sub Query "
 Exists Op returns true if the Sub Query returns Any
value other than Null.

2. NOT EXISTS : " Not Exists Op is a Unary Op ( One Operand )


which can accept
One Operand Towards RHS and that Operand has to be
A Co-related Sub Query "
 Not Exists Op returns true if the Sub Query returns NULL .

To Find MAX & MIN salary :


To find MAXIMUM salary :

SELECT SAL FROM EMP E1


WHERE ( SELECT COUNT( DISTINCT SAL ) FROM EMP E2
WHERE E1.SAL < E2.SAL ) = N-1 ;

2nd , 4th , 5th , 7th MAX salary

SELECT SAL
FROM EMP E1
WHERE ( SELECT COUNT( DISTINCT SAL )
FROM EMP E2
WHERE E1.SAL < E2.SAL ) in ( 1 , 3, 4 , 6 ) ;

To find MINUMUM salary :

SELECT SAL FROM EMP E1


WHERE ( SELECT COUNT( DISTINCT SAL ) FROM EMP E2
New Section 1 Page
WHERE E1.SAL > E2.SAL ) = N-1 ;

SINGLE ROW FUNCTIONS


1. LENGTH( )
2. CONCAT( )
3. UPPER( )
4. LOWER( )
5. INITCAP( )
6. REVERSE( )
7. SUSBTR( )
8. INSTR( )
9. REPLACE( )
10. MOD( )
11. TRUNC( )
12. ROUND( )
13. MONTHS_BETWEEN( )
14. LAST_DAY( )
15. TO_CHAR( )
16. NVL( )

1. LENGTH : "It is used to count the number of characters


present In the given string ".

SYNTAX: LENGTH ( 'string' )

Example :

 WAQT count number of characters present in 'SMITH' .

SELECT LENGTH ( ENAME )


FROM EMP LENGTH(ENAME)
WHERE ENAME ='SMITH' ;
5
SELECT LENGTH( 'SMITH' )
FROM DUAL ;

SELECT LENGTH( 'HELLO WORLD' )

11 FROM DUAL;

New Section 1 Page


NOTE : DUAL TABLE
It is a DUMMY table which has 1 col and 1 row .
Which is used to output the result .

 DESC DUAL ;

 SELECT *
FROM DUAL ;

2. CONCAT( ) : "It is used to join the given two strings '


SYNTAX : CONCAT ( 'string1' , 'String2' )

Example :

Input : Smith
Output : Mr. Smith

SELECT CONCAT( 'Mr. ' , ENAME )


FROM EMP
WHERE ENAME ='SMITH' ;

3. UPPER( ) : "It is used to convert a given string to upper case "

SYNTAX: UPPER ( 'string' )

4. LOWER( ) :"It is used to convert a given string to lower case "

SYNTAX: LOWER( 'string' )

5. INITCAP( ):"It is used to convert a given string to initial capital


letter case ".
SYNTAX: INITCAP( 'string' )

6. REVERSE( ): "It is used to reverse a given string ".

SYNTAX: REVERSE( 'string' )

Example :
REVERSE( 'SMITH' )
SELECT REVERSE( 'SMITH' ). HTIMS
FROM DUAL ;
UPPER( 'smith' )
SELECT UPPER( 'smith' ).
SMITH
FROM DUAL ;

SELECT LOWER( 'SMITH' ). LOWER( 'SMITH' )


smith1 Page
New Section
FROM DUAL ;

SELECT INITCAP( 'SMITH' ).


FROM DUAL ; INITCAP( 'SMITH' )
Smith

7. SUBSTR : "It is used to extract a part of string


from the given Original string " .

SYNTAX: SUBSTR ( 'Original_String' , Position [ , Length ] )

 WAQT extract first 3 characters of the emp names .

SELECT SUBSTR(ENAME, 1,3)


FROM EMP;

 WAQT extract last 3 characters of the employee names .

SELECT SUBSTR(ENAME, -3 )
FROM EMP;

 WAQT to display first half of employee names .

ENAME OUTPU
T
SMITH SM
MILLER MIL
JONES JO
WARD WA

SELECT SUBSTR( ENAME , 1 , LENGTH( ENAME ) / 2 )


FROM EMP ;

SMITH SUBSTR( ENAME , 1 , LENGTH( ENAME ) / 2 )

 WAQT to display second half of employee names .

ENAME OUTPU
T
SMITH ITH
MILLER LER
JONES NES
WARD RD
New Section 1 Page
SELECT SUBSTR( ENAME , LENGTH( ENAME ) / 2 + 1 )
FROM EMP ;

SMITH SUBSTR( ENAME , LENGTH( ENAME ) / 2


+1)
SUBSTR( 'SMITH' , LENGTH ( 'SMITH' ) / 2
+1)
SUBSTR( 'SMITH' , 5 / 2 +1)
SUBSTR( 'SMITH' , 3)
ITH

WARD SUBSTR( ENAME , LENGTH( ENAME ) /


2+1 )
SUBSTR( 'WARD' , LENGTH ('WARD' ) /
2+1 )
SUBSTR( 'WARD' , 4 / 2 +1)
SUBSTR( 'WARD' , 3)
RD
8. REPLACE ( ) : "It is used to replace a string with another string in
The original string.
Null
SYNTAX:REPLACE ( 'Original_String' , 'string' [, 'new_String' ] )

Example REPLACE ( 'BANANA' , 'A' , 'C' ) BCNCNC


:
Example REPLACE ( 'BANANA' , 'N' , BAABCAABCA
: 'ABC' )
Example REPLACE ( 'OPPO' , 'O' , 'J' ) JPPJ
:
Example REPLACE ( 'BANANA' , 'A' ) BNN
:
Example REPLACE ( 'ENGINEERING' , 'E' NGINRING
: )

NOTE : if the third argument is not mentioned the default


Value of it is Null .

1. WAQTD the number of times char 'A' is present in BANANA !!!

SELECT LENGTH('BANANA') - LENGTH ( REPLACE( 'BANANA','A' )


FROM DUAL ;

Length ( 'BANANA' ) -
LENGTH( REPLACE('BANANA','A') ) Length
('BANANA') - LENGH ('BNN' )
6-3
New Section 1 Page
= 3 times 'A' is present in BANANA

2. WAQTD to count number of time 'A' is present in 'MALAYALAM'

SELECT LENGTH('MALAYALAM') -
LENGTH ( REPLACE(
'MALAYALAM','A' )
FROM DUAL ;

9. INSTR ( ) : "it is used to obtain the position in which the string is present in the Original string ".
It is used to search for a string in the Original string if present it returns the POSITION
Else it returns 0 ".

Syntax: INSTR( 'Original_String' , 'String' , Position [, Occurrence] )

Note : if occurrence is not Mentioned then , the default value of Occurrence is 1 .

B A N A N A
1 2 3 4 5 6

Example : INSTR( 'BANANA' , 'A' , 1 , 1 ) POS: 2


Example : INSTR( 'BANANA' , 'A' , 2 , 1 ) POS: 2
Example : INSTR( 'BANANA' , 'A' , 1 , 2 ) POS: 4
Example : INSTR( 'BANANA' , 'A' , 1 , 3 ) POS: 6
Example : INSTR( 'BANANA' , 'A' , 1 , 4 ) POS: 0
Example : INSTR( 'BANANA' , 'A' , 4 , 2 ) POS: 6
Example : INSTR( 'BANANA' , 'A' , 2 ) POS: 2
Example : INSTR( 'BANANA' , 'N' , 2 , 1) POS: 3
Example : INSTR( 'BANANA' , 'O' , 1 ,1 ) POS: 0
Example : INSTR( 'BANANA' , 'NA' , 2 , 2 ) POS: 5
Example : INSTR( 'BANANA' , 'A' , 3 , 3 ) POS: 0
Example : INSTR( 'BANANA' , 'ANA' , 1 , 2 ) POS: 4

1. WAQTD NAMES OF THE EMPLOYEES IF THEY HAVE CHAR 'A' PRESENT IN THEIR NAMES

SELECT ENAME
FROM EMP
WHERE INSTR( ENAME , 'A' , 1 ,1 ) > 0 ;

2. WAQTD NAMES OF THE EMPLOYEES IF THEY HAVE CHAR 'A' PRESENT ATLEAST TWICE IN
THEIR NAMES

SELECT ENAME
FROM EMP
WHERE INSTR( ENAME , 'A' , 1 , 2 ) > 0 ;
New Section 1 Page
3. WAQTD NAMES OF THE EMPLOYEES IF THEY HAVE CHAR 'A' PRESENT ATLEAST THRICE IN
THEIR NAMES

SELECT ENAME
FROM EMP

WHERE INSTR( ENAME , 'A' , 1 , 3 ) > 0 ;

4. WAQTD NAMES OF THE EMPLOYEES IF THEY HAVE CHAR 'A' EXACTLY TWICE

SELECT ENAME
FROM EMP
WHERE INSTR( ENAME , 'A' , 1 , 2 ) > 0 AND INSTR( ENAME , 'A' , 1 , 3 ) = 0 ;

OR

SELECT ENAME
FROM EMP
WHERE ( LENGTH( ENAME ) - LENGTH( REPLACE( ENAME ,'A') ) ) = 2;

ALLEN INSTR('ALLEN','A',1,2) Pos:0 INSTR('ALLEN','A',1,3) Pos:0


ADAMS INSTR('ADAMS','A',1,2) Pos:3 INSTR('ADAMS','A',1,3) Pos:0
AATISH INSTR('AATISH','A',1,2) Pos:2 INSTR('AATISH','A',1,3) Pos:0
AAA INSTR('AAA' ,'A',1 ,2) Pos:2 INSTR('AAA' ,'A',1 ,3) Pos:3
MALAYALAM INSTR('MALAYALAM' , 'A' , Pos: INSTR('MALAYALAM' , 'A' , 1, 3 Pos:6
1, 2 ) 4 )

ALLEN LENGTH( 'ALLEN' ) - LENGTH( REPLACE( 'ALLEN' ,A' ) ) =2


5 - LENGTH( 'LLEN' )
5-4
1 != 2
ADAMS 5 - LENGTH('DMS' )
5-3
2 =2
AAAAO 5 - LENGTH('O')
5-1
4 != 2

SINGLE ROW FUNCTIONS

10. MOD( )
New Section 1 Page
11. TRUNC( )
12. ROUND( )
13. MONTHS_BETWEEN( )
14. LAST_DAY( )
15. TO_CHAR( )
16. NVL( )
10. MOD( ) : "It is used to obtain modulus/remainder of the given number "

Syntax: MOD ( m , n )
n)m(

Example : SELECT MOD( 5 , 2 )


FROM DUAL ; 1

1 . WAQTD ENAMES OF THE EMPLOYEES WHO EARN SALARY IN MULTIPLES OF 3

SELECT ENAME
FROM EMP
WHERE MOD( SAL , 3 ) = 0 ;

2. WAQTD DETAILS OF THE EMPLOYEE WHO HAVE ODD EID

SELECT *
FROM EMP
WHERE MOD( EID , 2 ) = 1 ;

11. ROUND( ) : " It is used to Round-off the given number based on the scale value "

Syntax: ROUND ( Number [, Scale ] ) The default value of scale is 0

Example : ROUND ( 5.6 ) 6


LHS RHS
Example : ROUND ( 5.5 ) 6
Example : ROUND ( 5.4 ) 5
Example : ROUND ( 9.9 ) 10 Before the Decimal
After the Decimal
Example : ROUND ( 9.4 ) 9 -ve SCALE
Example : ROUND (8.6 , 0 ) 9 +ve SCALE
Decimal

When the scale is -ve it indicated the digits before the decimal
And the digit count begins from 1 . When the scale is +ve it indicated the
Example : ROUND ( 8421.12 , -1 ) 8420 digits after the decimal
Example : ROUND ( 8426.12 , -1 ) 8430 And the digit
5.6 6 Rounding off tocount
unitsbegins
place from 0 .
Example : ROUND ( 154264.12 , -2 15430
) 0
Example : ROUND ( 338222 , -4 ) 34000
0

New Section 1 Page


ROUND ( 8421 .12 , -1 )
( 124.23541 , 0 ) = 124
Example : ROUND ( 124.23541 , 0 ) 124
( 124.23541 , 0 ) = 124
And the digit count begins from 0 .
( 124.23541 , 1 ) = 124.2
Example : ROUND ( 124.23541 , 0 ) 124
( 123.6712638723 , 6 ) =
Example : ROUND ( 124. 23541 , 1 ) 124.2
Example : ROUND ( 124. 23541 , 2 ) 124.24 123.671264
Example : ROUND ( 124. 2354391 , 5 ) 124.23544

10. TRUNC( ): "It is similar to ROUND() but it always rounds-off the given number to the lower value "

Syntax: TRUNC( Number [, Scale ] )

Example : TRUNC ( 5.6 ) 5


Example : TRUNC ( 5.5 ) 5
Example : TRUNC ( 5.4 ) 5
Example : TRUNC ( 9.9 ) 9
Example : TRUNC ( 9.4 ) 9
Example : TRUNC (8.6 , 0 ) 8
Example: TRUNC( 451258.32541 , -5) 400000

NOTE :
DATE COMMANDS :
i. SYSDATE : " it is used to obtain Todays Date "
ii. CURRERNT_DATE : " it is also used to obtain todays date "
iii. SYSTIMESTAMP : "It is used to obtain date , time and time zone "

SQL> SELECT SYSDATE


2 FROM DUAL ;

SYSDATE

17-MAY-20

SQL> SELECT CURRENT_DATE


2 FROM DUAL ;

New Section 1 Page


CURRENT_D 17-MAY-20

SQL> SELECT SYSTIMESTAMP


2 FROM DUAL ;

SYSTIMESTAMP

17-MAY-20 05.05.52.356000 PM +05:30

12. MONTHS_BETWEEN( ) :"It is used to Obtain the number of months present between the
Given two dates "

Syntax: MONTHS_BETWEEN ( DATE1 , DATE2 )

SELECT TRUNC( MONTHS_BETWEEN( SYSDATE , HIREDATE ) ) || ' Months'


FROM EMP

TRUNC(MONTHS_BETWEEN(SYSDATE,HIREDATE))||'MONTH

473 Months
470 Months

13. LAST_DAY( ): " it is used to Obtain the last day in the particular of the given date" .

Syntax: LAST_DAY( DATE ) ;

SQL> SELECT LAST_DAY( SYSDATE ) SYSDATE = 08-JUL-2020


2 FROM DUAL ;

LAST_DAY

31-JUL-20

14. TO_CHAR( ) :"It is used to convert the given date into String format based on the Model given "

Syntax: TO_CHAR( DATE , 'Format _ Models')

Format Models :
i. YEAR : TWENTY TWENTY
ii. YYYY : 2020
iii. YY : 20
iv. MONTH : JULY
v. MON : JUL

New Section 1 Page


vi. MM : 07
vii. DAY : WEDNESDAY
viii. DY : WED
ix. DD : 08
x. D : 4 ( day of the week )
xi. HH24 : 17 hours
xii. HH12 : 5 hours
xiii. MI : 22 minutes
xiv. SS : 53 seconds
xv. 'HH12:MI:SS' : 5 : 22 : 53
xvi. 'DD-MM-YY' : 17 - 05 - 20
xvii. 'MM-DD-YYYY' : 05 - 17 – 2020

1. WAQTD DETAILS OF THE EMPLOYEE WHO WAS HIRED ON A SUNDAY .

SELECT *
FROM EMP
WHERE TO_CHAR( HIREDATE , 'DAY' ) = 'SUNDAY' ;

2. WAQTD DETAILS OF AN EMPLOYEE HIRED ON MONDAY AT 10AM

SELECT *
FROM EMP
WHERE TO_CHAR( HIREDATE , 'D' ) = 2 AND TO_CHAR( HIREDATE , 'HH24' ) = 10 ;
15. NVL( ) : [ NULL VALUE LOGIC ] " It is used to eliminate the side effects of using null in arithmetic
operations " .

WAQTD NAME AND TOTAL SALALRY OF ALL THE EMPLOYEES? SELECT ENAME , SAL + COMM
ENAME SAL COMM
FROM EMP ;
A 500 100
B 1000 NULL ENAME SAL+COMM
C 2000 200 A 600
D 2000 NULL B NULL
C 2200
D NULL

Null value logic : Syntax : NVL ( Argument1 , Argument2 )

Argument 1 : Here write any column / exp which can result In null .
Argument 2 : Here we write a numeric value which will be substituted
if argument 1 results in Null ,
If argument 1 is NOT NULL then the same value will be considered .

SELECT ENAME , SAL + NVL ( COMM , 0 )


New Section 1 Page
FROM EMP ;

A 500 + NVL ( 100 , 0 ) 500 + 100 600


B 1000 + NVL ( null , 0 ) 1000 + 0 1000
C 2000 + NVL ( 200 , 0 ) 2000+200 2200
D 2000 + NVL( null , 0 ) 2000 + 0 2000

After using NVL


ENAME SAL+nvl(COMM ,0)
A 600
ENAME SAL+nvl(COMM ,0)
A 600
B 1000
C 2200
D 2000

1. List employees whose name having 4 characters


SELECT *
FROM EMP
WHERE LENGTH(ENAME)=4 ;

2. List employees whose job is having 7 characters


SELECT *
FROM EMP
WHERE LENGTH(JOB)=4;

3. Find out how many times letter 'S' occurs in 'qspiders'


SELECT LENGTH('QSPIDERS') - LENGTH( REPLACE( 'QSPIDERS' , 'S' ) )
FROM DUAL ;

4. List the employees whose job is having last 3 characters as 'man'


SELECT *
FROM EMP
WHERE SUBSTR( JOB , -3 ) = 'MAN' ;

5. List employees whose job is having first 3 characters as 'man'.


SELECT *
FROM EMP
WHERE SUBSTR( JOB , 1 , 3 ) = 'MAN' ;

6. Display all the names whose name is having exactly 1 'L'


SELECT ENAME
FROM EMP
New Section 1 Page
WHERE INSTR( ENAME , 'L' , 1,1 ) != 0 AND INSTR( ENAME , 'L' , 1, 2 ) = 0 ;

OR

SELECT ENAME
FROM EMP
WHERE LENGTH( ENAME ) - LENGTH( REPLACE( ENAME , 'L' ) ) = 1 ;

7. Display dept names which are having letter 'O'


SELECT DNAME
FROM DEPT
WHERE INSTR(DNAME,'O',1,1 ) !=0 ;

9. Calculate number of L in string 'HELLLLL'


SELECT LENGTH('HELLLLL') - LENGTH( REPLACE( 'HELLLLL' , 'L' ) )
FROM DUAL ;

10. Display all the employees whose job has a string 'MAN'
SELECT *
FROM EMP
WHERE INSTR(JOB,'MAN',1,1 ) !=0 ;

11. Display all the employees whose job starts with string 'MAN'
SELECT *
FROM EMP
WHERE INSTR(JOB,'MAN',1,1 ) =1 ;

OR

SELECT *
FROM EMP
WHERE SUBSTR( JOB ,1,3) = 'MAN' ;

12. Display all the employees whose job ends with string 'MAN'
SELECT *
FROM EMP
WHERE SUBSTR( JOB , -3 ) = 'MAN' ;

13. Display first 3 characters of ename in lower case and rest everything in upper case.
If ename is 'QSPIDERS' then display this as ‘qspIDERS’
SELECT LOWER(SUBSTR('QSPIDERS',1,3)) || UPPER( SUSBTR('QSPIDERS' , 4) )
FROM DUAL ;
New Section 1 Page
14. Display the result from emp table as below.
SMITH is a CLERK and gets salary 2000
Here SMITH is ename column, CLERK is JOB and 2000 is SAL column and rest everything is literal
strings.
SELECT ENAME || ' IS A '|| JOB || ' AND GETS SALARY ' || SAL
FROM EMP
WHERE ENAME = 'SMITH' ;

15.list the employees hired on a Wednesday


SELECT *
FROM EMP
WHERE TO_CHAR( HIREDATE , 'DY' ) = WED ;

16.list the employees hired on a leap year


SELECT *
FROM EMP
WHERE MOD( TO_CHAR( HIREDATE , 'YY' ) , 4 ) = 0 ;

17.list the employees hired on a Sunday in the month of may


SELECT *
FROM EMP
WHERE TO_CHAR( HIREDATE , 'DY' ) = 'SUN' AND TO_CHAR( HIREDATE , 'MON' ) = 'MAY' ;

STATEMENTS ARE CLASSIFIED INTO 5 DIFFERENT TYPES


 DATA DEFINITION LANGUAGE ( DDL )
 DATA MANIPULATION LANGUAGE ( DML )
 TRANSACTION CONTROL LANGUAGE ( TCL )
 DATA CONTROL LANGUAGE ( DCL )
 DATA QUERY LANGUAGE ( DQL )

1. DATA DEFINITION LANGUAGE ( DDL ):


" DDL is used to construct an object in the database and deals with the Structure of the Object "

It has 5 statements :
1. CREATE
2. RENAME
3. ALTER
4. TRUNCATE
5. DROP

1. CREATE : " IT IS USED TO BUILD / CONSTRUCT AN OBJECT "


New Section 1 Page
Object / Entity can be a Table or a View ( Virtual Table ) .

How to Create a Table :

 Name of the table


� Tables cannot have same names .



Syntax to create a table :

CREATE TABLE Table_Name (


Column_Name1 datatype constraint_type ,
Column_Name2 datatype constraint_type ,
Column_Name3 datatype constraint_type ,
.
.
Column_NameN datatype constraint_type
);

Example :

CREATE TABLE CUSTOMER (


CID Number(2) primary key , CNAME
Varchar(10) ,
CNO Number(10) not null check( length( CNO ) = 10 ) ,
ADDRESS Varchar(15)
);

NOTE :
To Describe the table:
CUSTOMER PRODUCT

Syntax: DESC Table_Name ; CID

New Section 1 Page


1. RENAME : "IT IS USED TO CHANGE THE NAME OF THE OBJECT "

Syntax: RENAME Table_Name TO New_Name ;

Example :
RENAME Customer TO Cust ;

2. ALTER :" IT IS USED TO MODIFY THE STRUCTURE OF THE TABLE "

 TO ADD A COLUMN :

Syntax: ALTER TABLE Table_Name


ADD Column_Name Datatype Constraint_type ;

Example : ALTER TABLE Cust


ADD MAIL_ID Varchar(15) ;

 TO DROP A COLUMN :
3. Syntax: ALTER TABLE Table_Name DROP COLUMN Column_Name ;
Example : ALTER TABLE Cust
DROP COLUMN MAIL_ID ;

 TO RENAME A COLUMN :

Syntax: ALTER TABLE Table_Name


RENAME COLUMN Column_Name TO new_Column_Name ;

Example : ALTER TABLE Cust


RENAME COLUMN CNO TO PHONE_NO ;

 TO MODIFY THE DATATYPE :

Syntax: ALTER TABLE Table_Name


MODIFY COLUMN_NAME New_Datatype;

Example : ALTER TABLE Cust


MODIFY CNAME CHAR(10) ;

 TO MODIFY NOT NULL CONSTRAINTS :

New Section 1 Page


Syntax: ALTER TABLE Table_Name
MODIFY COLUMN_NAME Existing_datatype [NULL]/NOT NULL;

Example : ALTER TABLE Cust


MODIFY ADDRESS Varchar(15) Not Null ;

2. TRUNCATE : " IT IS USED TO REMOVE ALL THE RECORDS FROM THE TABLE
PREMANENTLY "

Syntax: TRUNCATE TABLE Table_Name ;

Cust
Cid Cname Phone_no Address
1 A 1234567890 BANGALORE
2 B 1234567899 MYSORE
3 C 1234567880 MANGALORE

Example : TRUNCATE TABLE Cust ;

Cust
Cid Cname Phone_no Address

1. DROP :" IT IS USED TO REMOVE THE TABLE FROM THE DATABASE "

Syntax: DROP TABLE Table_Name ;

Syntax: DROP TABLE Table_Name ;


Example :
DATABASE Bin Folder
Cust

Cid Cname Phone_no Address Bin$123abc


DROP
1 A 1234567890 BANGALORE
2 B 1234567899 MYSORE Address
3 C 1234567880 MANGALORE

TO RECOVER THE TABLE :

Syntax: FLASHBACK TABLE Table_Name TO


BEFORE DROP ;

New Section 1 Page


Example :
DATABASE Bin Folder

Address : BIN$123ABCXYZ
Cust

FLASHBACK

FLASHBACK TABLE Cust


TO BEFORE DROP ;

TO DELETE THE TABLE FROM BIN FOLDER :

Syntax: PURGE TABLE Table_Name ;

Example : PURGE TABLE Cust ;

Database Bin folder Trash

Cust PURGE
DROP Gone
BIN$123ABC Forever

FLASHBACK

NOTE : DDL STATEMENTS ARE AUTO-COMMIT STATEMENTS


DATA MANIPULATION LANGUAGE ( DML )

It is used to Manipulate the Object by performing insertion , updating and deletion .

1. INSERT
2. UPDATE
3. DELETE

1. INSERT : It is used to insert / create records in the table .

New Section 1 Page


Syntax: INSERT INTO Table_Name VALUES( v1 , v2 , v3 …… ) ;

CUSTOMER
CID CNAME CNO ADDDRESS
NUMBER(2) VARCHAR(10) NUMBER(10 VARCHAR(20
) )

INSERT INTO CUSTOMER VALUES( 1 , 'DINGA' , 9876543210 ,'BANGALORE' ) ;


CID CNAME CNO ADDDRESS
NUMBER(2) VARCHAR(10) NUMBER(10 VARCHAR(20
) )
1 DINGA 9876543210 BANGALORE
INSERT INTO CUSTOMER VALUES( 2 , 'DINGI' , 9876543211 ,'MANGALORE' ) ;
CID CNAME CNO ADDDRESS
NUMBER(2) VARCHAR(10) NUMBER(10 VARCHAR(20
) )
1 DINGA 9876543210 BANGALORE
2 DINGI 9876543211 MANGALORE

PRODUCT
PID PNAME PRICE CID
NUMBER(2) VARCHAR(10) NUMBER(6,2) NUMBER(3)

INSERT INTO PRODUCT VALUES( 11 , 'iPhone' , 10000 , 2 );


PID PNAME PRICE CID
NUMBER(2) VARCHAR(10) NUMBER(6,2) NUMBER(3)
11 iPhone 10000 2
INSERT INTO PRODUCT VALUES( 22 , 'Mac Book' , 20000 , 1 );
PID PNAME PRICE CID
NUMBER(2) VARCHAR(10) NUMBER(6,2) NUMBER(3)
11 iPhone 10000 2

22 Mac Book 20000 1

2. UPDATE :It is used to modify an existing value .

Syntax: UPDATE Table_Name


SET Col_Name = Value , Col_Name = Value ,,,,,
[WHERE stmt ] ;

New Section 1 Page


CID CNAME CNO ADDDRESS
NUMBER(2) VARCHAR(10) NUMBER(10 VARCHAR(20
) )
1 ABHI 1234567890 BANGALORE
2 ABDUL 9876543210 MANGALOR
E

 WAQT update the phone number of Abdul to 7778889994

UPDATE
CUSTOMER SET
CNO = 7778889994
WHERE CNAME ='ABDUL' ;

CID CNAME CNO ADDDRESS


NUMBER(2) VARCHAR(10) NUMBER(10 VARCHAR(20
) )
1 ABHI 1234567890 BANGALORE
2 ABDUL 7778889994 MANGALOR
E

 WAQT change the address of the customer to Mysore whose cid is 1 .

UPDATE CUSTOMER
SET ADDRESS = 'MYSORE'
WHERE CID = 1 ;

CID CNAME CNO ADDDRESS


NUMBER(2) VARCHAR(10) NUMBER(10 VARCHAR(20
) )
1 ABHI 1234567890 MYSORE
2 ABDUL 7778889994 MANGALOR
E

3. DELETE : It is used to remove a particular record from the table .


4. Syntax: DELETE FROM Table_Name [ WHERE stmt ];
1 ABHI 1234567890 BANGALORE
2 ABDUL 1234567891MANGALOR
E
 WAQT remove abdul from the list of customers .

DELETE FROM CUSTOMER


WHERE CNAME ='ABDUL' ;

New Section 1 Page


CID CNAME CNO ADDDRESS
NUMBER(2) VARCHAR(10) NUMBER(10 VARCHAR(20
) )
1 ABHI 1234567890 BANGALORE

ASSIGNMENT ON DML STATEMENTS :

1. WAQT update the salary of employee to double their salary if


He is working as a manager .

2. WAQT change the name of SMITH to SMIITH .

3. WAQT modify the job of KING to 'PRESIDENT' .

4. WAQT to change name of ALLEN to ALLEN MORGAN .

5. WAQT hike the salary of the employee to 10% . If employees earn less than 2000 as a salesman .

6. WAQ TO delete the employees who don’t earn commission .

7. WAQ to remove all the employees hired before 1987 in dept 20

8. Differentiate between TRUNCATE and DELETE statements .

TRUNCATE DELETE
Belongs to DDL Belongs to DML

Removes all the records from the Removes a particular record from the
Table permanently . Table .
Auto COMMIT Not auto COMMIT .

3. TRANSACTION CONTROL LANGUAGE ( TCL )

New Section 1 Page


"It is used to control the transactions done on the database ".
The DML Operations performed on the Database are known as Transactions such as Insertion ,
Updating and Deletion .

We have 3 Statements :

1. COMMIT
2. ROLLBACK
3. SAVEPOINT

1. COMMIT : "This statement is used to SAVE the transactions into the DB ".

Syntax: COMMIT ;

Example : Query WORKPLACE DATABASE

 CREATE T1 NAME SAL


NAME SAL

 INSERT INTO T1
VALUES( 'A' , 100

COMMIT ; ); NAME SAL NAME SAL


A 100 A 100

 INSERT INTO T1 NAME SAL NAME SAL


VALUES( 'B' , 200
A 100 A 100
 INSERT INTO T1
VALUES( 'C' , 300 B 200 B 200
COMMIT ; ); C 300

VALUES( 'C' , 300 ) ; B 200


B 200
COMMIT ; C 300 C 300

New Section 1 Page


NAME SAL
 UPDATE T1 SET A 1000
SAL = 1000
WHERE NAME = 'A' ;
B 200
C 300

 COMMIT ; NAME SAL


A 1000
B 200
C 300
2. ROLLBACK :

This statement is used to Obtain only the saved data from the DB .

It will bring you to the point where you have committed for the last time .

SYNTAX: ROLLBACK ;

3. SAVEPOINT :

This statement is used to mark the positions or restoration points . (nothing related to DB ) .

SYNTAX: SAVEPOINT Savepoint_Name ;

Example :

Query WORKPLACE SAVEPOINT

 INSERT INTO T1 NAME SAL Savepoints


VALUES( 'A',100) ;
 SAVEPOINT S1 ; A 100 S1
 INSERT INTO T1 B 200
VALUES( 'B' , 200 ) ;
 INSERT INTO T1 C 300 S2
VALUES( 'B' , 200 ) ;
 INSERT INTO T1 VALUES( 'C' , 300 ) ;
 SAVEPOINT S2 ;
 INSERT INTO T1
VALUES( 'D' , 400 ) ;

New Section 1 Page


 INSERT INTO T1
VALUES( 'E' , 500 ) ;
 SAVEPOINT S3 ;
 INSERT INTO T1
VALUES( 'F' , 600 ) ;

C 300 S2
D 400
E S3
500
F 600
ROLLBACK TO S3

ROLLBACK TO S1

New Section 1 Page


SYNTAX: ROLLBACK TO Savepoint_Name ;

4. DATA CONTROL LANGUAGE :

"This statement is used to control the flow of data between the users ".

We have 2 statements :

1. GRANT
2. REVOKE

1. GRANT : THIS STATEMENT IS USED TO GIVE PERMISSION TO A USER .

SYNTAX: GRANT SQL_STATEMENT


ON TABLE_NAME
TO USER_NAME ;

2. REVOKE : THIS STATEMENT IS USED TO TAKE BACK THE PERMISSION


FROM THE USER .

SYNTAX: REVOKE SQL_STATEMENT


ON TABLE_NAME FROM
USER_NAME ;
Example :

User 1 : SCOTT

User 1 : SCOTT
User 2 : HR

EMP SELECT *
ENAM SAL FROM SCOTT.EMP ;
E
A 100
B 200

New Section 1 Page


GRANT SELECT ON EMP
TO HR ;

EMP

ENAM SAL
E
A 100
B 200

REVOKE SELECT ON EMP


FROM HR ;

ENAME SAL SELECT *


A 100 FROM SCOTT.EMP ;
B 200

TRY !!!!

SQL> SHOW USER ; USER is "SCOTT"


SQL> CONNECT
Enter user-name: HR Enter password:
***** Connected.
SQL> SHOW USER ; USER is "HR

SQL> SHOW USER ; USER is "SCOTT"


SQL> CONNECT
Enter user-name: HR Enter password:
***** Connected.
SQL> SHOW USER ; USER is "HR

New Section 1 Page


What is Normalization ?

" It is the process of reducing a large table into smaller tables in order to remove
redundancies and anomalies by identifying their functional dependencies is
known as Normalization. "

Or

"The process of decomposing a large table into smaller table is known as


Normalization."

Or

New Section 1 Page


"Reducing a table to its Normal Form is known as Normalization. "

T1 T3

Or

Normalization represents the way of organizing structured data in the database efficiently. It
includes the creation of tables, establishing relationships between them, and defining rules for those
relationships. Inconsistency and redundancy can be kept in check based on these rules, hence,
adding flexibility to the database.

What is Normal Form?

A table without redundancies and anomalies are said to be in Normal Form.

Levels of Normal From .


1. First Normal Form (1NF)
2. Second Normal Form (2NF)
3. Third Normal Form (3NF)
4. Boyce - Codd Normal Form (BCNF)

Note : If any Table / entity is reduced to 3NF , then the table is said to be normalized.

1. First Normal Form (1NF ) :


- No duplicates records.
New Section 1 Page
- Multivalued data should not be presen .

QSPIDERS
QID NAME COURSE
QID NAME C1 C2 C3
1 A JAVA
1 A JAVA MT
2 B JAVA , SQL
2 B JAVA SQL
3 C MT , SQL
3 C SQL MT
1 A MT

First Normal Form: A relation is in first normal form if every attribute in that relation is a singlevalued attribute. If a
relation contains a composite or multi-valued attribute, it violates the first normal form.

Let's consider the following students table. Each student in the table, has a name, his/her address, and the books they
issued from the public library –

Students Table

Student Address Books Issued Salutation

Until the Day I Die


Amanora (Emily Carpenter),
Sara Park Town Inception Ms.
94 (Christopher Nolan)

The Alchemist
62nd Sector (Paulo Coelho),
Ansh A- 10 Inferno (Dan Mr.
Brown)

Beautiful Bad (Annie


24th Ward), Woman 99
Sara Street (Greer Macallister) Mrs.
Park
Avenue

Windsor
Ansh Street 777 Dracula (Bram Mr.
Stoker)

New Section 1 Page


As we can observe, the Books Issued field has more than one value per record, and to convert it
into 1NF, this has to be resolved into separate individual records for each book issued.
Check the following table in 1NF form -
Students Table (1st Normal Form)

Student Address Books Issued Salutation

Amanora Until the Day I Die


Sara Park Town (Emily Carpenter) Ms.
94
Amanora Inception
Sara Park Town (Christopher Nolan) Ms.
94
The Alchemist
62nd Sector
(Paulo
Ansh A- 10 Mr.
Coelho)

62nd Sector
Inferno (Dan
Ansh A- 10 Mr.
Brown)

24th
Street Beautiful Bad
Sara Mrs.
Park (Annie Ward)
Avenue
24th
Woman 99 (Greer
Street
Sara Macallister) Mrs.
Park
Avenue
Windsor Dracula
Ansh Street 777 (Bram Mr.
Stoker)

New Section 1 Page


2. Second Normal Form ( 2NF )
- Table should be in 1NF
- Table should not have Partial Functional Dependency .

EMPLOYEE - ( EID , ENAME , SAL , DEPTNO , DNAME , LOC )


Eid ename sal Deptno dname Loc
1 A 100 10 D1 L1
2 B 120 20 D2 L2
3 C 320 10 D1 L1
4 D 251 10 D1 L1

Eid - ename ,sal


Deptno - dname , loc

:- ( Eid , deptno ) -> ( Ename , Sal , Dname , Loc ) composite key attribute
results in PFD

R1 - ( EID , ENAME , SAL )


R2 - ( DEPTNO , DNAME , LOC ) Eid ename sal
1 A 100 Deptno dname Loc
2 B 120 10 D1 L1
3 C 320 20 D2 L2
4 D 251

o Second Normal Form:


A relation is in second normal form if it satisfies the conditions for the first normal form and
does not contain any partial dependency. A relation in 2NF has no partial dependency, i.e., it
has no non-prime attribute that depends on any proper subset of any candidate key of the table.
Often, specifying a single column Primary Key is the solution to the problem. Examples –

New Section 1 Page


Example 1 - Consider the above example. As we can observe, the Students Table in the 1NF
form has a candidate key in the form of [Student, Address] that can uniquely identify all
records in the table. The field Books Issued (non-prime attribute) depends partially on the
Student field. Hence, the table is not in 2NF. To convert it into the 2nd Normal Form, we will
partition the tables into two while specifying a new Primary Key attribute to identify the
individual records in the Students table. The Foreign Key constraint will be set on the other table
to ensure referential integrity.
Students Table (2nd Normal Form)

Student_ID Student Address Salutation


Amanora
1 Sara Park Ms.
Town 94
62nd
2 Ansh Sector A- Mr.
10
24th
Street
3 Sara Mrs.
Park
Avenue
Windsor
4 Ansh Street Mr.
777
Books Table (2nd Normal Form)

Student_ID Book Issued

1 Until the Day I Die (Emily


Carpenter)
1 Inception (Christopher Nolan)

2 The Alchemist (Paulo Coelho)

2 Inferno (Dan Brown)

New Section 1 Page


3 Beautiful Bad (Annie Ward)

3 Woman 99 (Greer Macallister)

4 Dracula (Bram Stoker)

EXAMPLE 2: Consider the following dependencies in relation to R (W, X, Y, Z)

WX -> [W and X together determine


Y XY - Y] [X and Y together
> Z determine Z]

Here, WX is the only candidate key and there is no partial dependency, i.e., any proper subset of WX doesn’t
determine any non-prime attribute in the relation.

o Third Normal Form


A relation is said to be in the third normal form, if it satisfies the conditions for the second
normal form and there is no transitive dependency between the non-prime attributes, i.e., all
non-prime attributes are determined only by the candidate keys of the relation and not by any
other non-prime attribute.

Example 1 - Consider the Students Table in the above example. As we can observe, the Students Table in
the 2NF form has a single candidate key Student_ID (primary key) that can uniquely identify all records
in the table. The field Salutation (non- prime attribute), however, depends on the Student Field rather than
the candidate key. Hence, the table is not in 3NF. To convert it into the 3rd Normal Form, we will once
again partition the tables into two while specifying a new Foreign Key constraint to identify the salutations
for individual records in the Students table. The Primary Key constraint for the same will be set on the
Salutations table to identify each record uniquely.

Students Table (3rd Normal Form)

Student_ID Student Address Salutation_ID

Amanora Park
1 Sara Town 94 1

New Section 1 Page


62nd Sector
2 Ansh A- 10 2

24th Street
Park
3 Sara 3
Avenue

Windsor
4 Ansh Street 777 1

Books Table (3rd Normal Form)

Student_ID Book Issued

1 Until the Day I Die (Emily Carpenter)

1 Inception (Christopher Nolan)

2 The Alchemist (Paulo Coelho)

2 Inferno (Dan Brown)

3 Beautiful Bad (Annie Ward)

3 Woman 99 (Greer Macallister)

4 Dracula (Bram Stoker)


salutations Table (3rd Normal Form)

Salutation_ID Salutation

1 Ms.

2 Mr.

3 Mrs.

Example 2 - Consider the following dependencies in relation to R(P,Q,R,S,T)

New Section 1 Page


P -> [[P together determine C]
QR RS
-> T Q [B and C together determine D]
-> S T
-> P

For the above relation to exist in 3NF, all possible candidate keys in the above relation should be {P, RS, QR, T}

3. Third Normal Form ( 3NF )


- Table should be in 2NF .
Table should not have Transitive Functional Dependency

Employee - ( EID , Ename , Sal , comm , Pin code , state , country )

EID -> ENAME :- Transitive Functional Dep


SAL
COMM
PINCODE -> STATE
COUNTRY
R1- ( eid , ename , comm )
R2- ( pincode , state , country )

New Section 1 Page


Boyce-Codd Normal Form
A relation is in Boyce-Codd Normal Form if satisfies the conditions for third normal form and
for every functional dependency, Left-Hand-Side is super key. In other words, a relation in
BCNF has non-trivial functional dependencies in form X –> Y, such that X is always a super
key. For example - In the above example, Student_ID serves as the sole unique identifier for
the Students Table and Salutation_ID for the Salutations Table, thus these tables exist in
BCNF. The same cannot be said for the Books Table and there can be several books with
common Book Names and the same Student_ID.

What is Denormalization?

Denormalization is the inverse process of normalization, where the normalized schema is converted
into a schema that has redundant information. The performance is improved by using redundancy
and keeping the redundant data consistent. The reason for performing denormalization is the
overheads produced in the query processor by an over-normalized structure.

What is Cursor? How to use a Cursor?

A database cursor is a control structure that allows for the traversal of records in a database. Cursors, in addition,
facilitates processing after traversal, such as retrieval, addition, and deletion of database records. They can be viewed
as a pointer to one row in a set of rows.

Working with SQL Cursor:


New Section 1 Page 1
1. DECLARE a cursor after any variable declaration.The cursor declaration must always be associated with a
SELECT Statement.
2. Open cursor to initialize the result set. The OPEN statement must be called before fetching rows from the result set.
3. FETCH statement to retrieve and move to the next row in the result set
4. Call the CLOSE statement to deactivate the cursor.
5. Finally use the DEALLOCATE statement to delete the cursor definition and release the associated resources.

DECLARE @name VARCHAR(50) /* Declare All Required Variables */


DECLARE db_cursor CURSOR FOR /* Declare Cursor Name*/
SELECT name FROM myDB.students
WHERE parent_name IN ('Sara', 'Ansh')
OPEN db_cursor /* Open cursor and Fetch data into @name */
FETCH next FROM db_cursor INTO @name
CLOSE db_cursor /* Close the cursor and deallocate the resources */
DEALLOCATE db_cursor

What are Entities and Relationships?


Entity:
An entity can be a real-world object, either tangible or intangible, that can be easily identifiable.
For example, in a college database, students, professors, workers, departments, and projects can be referred to as
entities.
Each entity has some associated properties that provide it an identity.

Relationships:
Relations or links between entities that have something to do with each other. For example - The employee's table in
a company's database can be associated with the salary table in the same database.

List the different types of relationships in SQL.

 One-to-One - This can be defined as the relationship between two tables where each record in
one table is associated with the maximum of one record in the other table.
 One-to-Many & Many-to-One - This is the most commonly used relationship where a record
in a table is associated with multiple records in the other table.
 Many-to-Many - This is used in cases when multiple instances on both sides are needed for
defining a relationship. Self-Referencing Relationships - This is used when a table needs to
define a relationship with itself.

New Section 1 Page 2


o What are the TRUNCATE, DELETE and DROP statements?

DELETE statement is used to delete rows from a table.

DELETE FROM Candidates


WHERE CandidateId > 1000;

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

TRUNCATE TABLE Candidates;

DROP command is used to remove an object from the database. If you drop a table, all the rows in the table
are deleted and the table structure is removed from the database.

DROP TABLE Candidates;

What are the difference between DROP and TRUNCATE statements?

If a table is dropped, all things associated with the tables are dropped as well. This includes - the relationships
defined on the table with other tables, the integrity checks and constraints, access privileges and other grants
that the table has. To create and use the table again in its original form, all these relations, checks, constraints,
privileges and relationships need to be redefined. However, if a table is truncated, none of the above problems
exist and the table retains its original structure.

 What is the difference between DELETE and TRUNCATE statements?


The TRUNCATE command is used to delete all the rows from the table and free the space containing the
table.
The DELETE command deletes only the rows from the table based on the condition given in the where clause
or deletes all the rows from the table if no condition is specified. But it does not free the space containing the
table.

 What is OLTP?
OLTP stands for Online Transaction Processing, is a class of software applications capable of supporting
transaction-oriented programs. An essential attribute of an OLTP system is its ability to maintain concurrency.
To avoid single points of failure, OLTP systems are often decentralized. These systems are usually designed
for a large number of users who conduct short transactions. Database queries are usually simple, require sub-
second response times, and return relatively few records. Here is an insight into the working of an OLTP system
[ Note - The figure is not important for interviews ] -

New Section 1 Page 3


 What are the differences between OLTP and OLAP?

OLTP stands for Online Transaction Processing, is a class of software applications capable of supporting transaction-oriented programs.
An important attribute of an OLTP system is its ability to maintain concurrency. OLTP systems often follow a decentralized
architecture to avoid single points of failure. These systems are generally designed for a large audience of end-users who conduct short
transactions. Queries involved in such databases are generally simple, need fast response times, and return relatively few records. A
number of transactions per second acts as an effective measure for such systems.

OLAP stands for Online Analytical Processing, a class of software programs that are characterized by the relatively low
frequency of online transactions. Queries are often too complex and involve a bunch of aggregations. For OLAP
systems, the effectiveness measure relies highly on response time. Such systems are widely used for data mining or
maintaining aggregated, historical data, usually in multi- dimensional schemas.

 What is Collation? What are the different types of Collation Sensitivity?

Collation refers to a set of rules that determine how data is sorted and compared. Rules defining the
correct character sequence are used to sort the character data. It incorporates options for specifying
New Section 1 Page 4
case sensitivity, accent marks, kana character types, and character width.
Below are the different types of collation sensitivity:

Case sensitivity: A and a are treated differently.


Accent sensitivity: a and á are treated differently.
Kana sensitivity: Japanese kana characters Hiragana and Katakana are treated differently.
Width sensitivity: Same character represented in single-byte (half-width) and double-byte (full-
width) are treated differently.

 What is a Stored Procedure?


A stored procedure is a subroutine available to applications that access a relational database management
system (RDBMS). Such procedures are stored in the database data dictionary. The sole disadvantage of stored
procedure is that it can be executed nowhere except in the database and occupies more memory in the
database server. It also provides a sense of security and functionality as users who can't access the data
directly can be granted access via stored procedures.

DELIMITER $$
CREATE PROCEDURE FetchAllStudents()
BEGIN
SELECT * FROM myDB.students;

What is a Recursive Stored Procedure?

A stored procedure that calls itself until a boundary condition is reached, is called a recursive stored
procedure. This recursive function helps the programmers to deploy the same set of code several times as and
when required. Some SQL programming languages limit the recursion depth to prevent an infinite loop of
procedure calls from causing a stack overflow, which slows down the system and may lead to system crashes.

DELIMITER $$ /* Set a new delimiter => $$


CREATE PROCEDURE */
calctotal( /* Create the procedure
*/ IN number INT, /* Set Input and Ouput
New Section 1 Page 5
 How to create empty tables with the same structure as another table?
Creating empty tables with the same structure can be done smartly by fetching the records of one table into a
new table using the INTO operator while fixing a WHERE clause to be false for all records. Hence, SQL
prepares the new table with a duplicate structure to accept the fetched records but since no records get fetched
due to the WHERE clause in action, nothing is inserted into the new table.

SELECT * INTO Students_copy


FROM Students WHERE 1 = 2;

 What is Pattern Matching in SQL?


SQL pattern matching provides for pattern search in data if you have no clue as to what that word should be.
This kind of SQL query uses wildcards to match a string pattern, rather than writing the exact word. The LIKE
operator is used in conjunction with SQL Wildcards to fetch the required information.

Using the % wildcard to perform a simple search

The % wildcard matches zero or more characters of any type and can be used to define wildcards both before
and after the pattern. Search a student in your database with first name beginning with the letter K:

SELECT *
FROM students
WHERE first_name LIKE 'K%'

Omitting the patterns using the NOT keyword

Use the NOT keyword to select records that don't match the pattern. This query returns all students whose first
name does not begin with K.

SELECT *
FROM students
WHERE first_name NOT LIKE 'K%'

Matching a pattern anywhere using the % wildcard twice


Search for a student in the database where he/she has a K in his/her first name.
New Section 1 Page 6
SELECT *
FROM students
WHERE first_name LIKE '%Q%'

Using the _ wildcard to match pattern at a specific position

The _ wildcard matches exactly one character of any type. It can be used in conjunction with % wildcard. This
query fetches all students with letter K at the third position in their first name.

SELECT *
FROM students
WHERE first_name LIKE ' K%'

Matching patterns for a specific length


The _ wildcard plays an important role as a limitation when it matches exactly one character. It limits the length and
position of the matched results. For example -

SELECT * /* Matches first names with three or more letters */


FROM students
WHERE first_name LIKE ' %'

SELECT * /* Matches first names with exactly four characters */

 SQL Injection:
Insertion or ‘Injection’ of some SQL Query from the input data of the client to the application is called SQL
Injection. They can perform CRUD operations on the database and can read to vulnerabilities and loss of data.

It can occur in 2 ways:

 Data is used to dynamically construct an SQL Query.


 Unintended data from an untrusted source enters the application.
New Section 1 Page 7
The consequences of SQL Injections can be Confidentiality issues, Authentication breaches, Authorization
vulnerabilities, and breaking the Integrity of the system.

The above image shows an example of SQL injections, through the use of 2 tables - students and library.

Here the hacker is injecting SQL code -

UNION SELECT studentName, rollNo FROM students

into the Database server, where his query is used to JOIN the tables - students and library. Joining the 2 tables, the
result of the query is returned from the database, using which the hacker gains access to the information he needs
thereby taking advantage of the system vulnerability. The arrows in the diagram show the flow of how the SQL
Injection causes the vulnerability in the database system, starting from the hacker’s computer.

New Section 1 Page 8


PostgreSQL Interview Questions
What is PostgreSQL?

 PostgreSQL was first called Postgres and was developed by a team led by Computer Science Professor
Michael Stonebraker in 1986.
New Section 1 Page 9
 It was developed to help developers build enterprise-level applications by upholding data integrity by
making systems fault-tolerant.
 PostgreSQL is therefore an enterprise-level, flexible, robust, open- source, and object-relational DBMS
that supports flexible workloads along with handling concurrent users.
 It has been consistently supported by the global developer community. Due to its fault-tolerant nature,
PostgreSQL has gained widespread popularity among developers.

Sr. Basis of
No. Comparison SQL PL/SQL

It is a database programming
It is a database Structured Query Language .
1. Definition language using SQL.

Variables, constraints, and data


Variables are not available in SQL. types features are available in
2. Variables PL/SQL.

Control Structures are available


No Supported Control Structures like for
like, for loop, while loop, if, and
loop, if, and other.
3. Control structures other.

Nature of It is an application-oriented
It is a Data-oriented language.
4. Orientation language.

PL/SQL block performs Group of


Operation as a single block
Query performs the single operation in SQL.
resulting in reduced network
5. Operations traffic.

Declarative/
Procedural SQL is a declarative language. PL/SQL is a procedural language.
6. Language

PL/SQL can’t be embedded in


SQL can be embedded in PL/SQL.
7. Embed SQL.

Interaction with It does not interact directly with the


It directly interacts with the database server.
8. Server database server.

Exception SQL does not provide error and exception PL/SQL provides error and
9. Handling handling. exception handling.

10. Writes It is used to write queries using DDL (Data The code blocks, functions,
Definition Language) and DML (Data procedures triggers, and packages

New Section 1 Page


Sr. Basis of
No. Comparison SQL PL/SQL

Manipulation Language) statements. can be written using PL/SQL.

SQL does not offer a high processing speed PL/SQL offers a high processing
11. Processing Speed for voluminous data. speed for voluminous data.

You can use PL/SQL to develop


You can fetch, alter, add, delete, or
applications that show information
manipulate data in a database using SQL.
12. Application from SQL in a logical manner.

How do you define Indexes in PostgreSQL?


Indexes are the inbuilt functions in PostgreSQL which are used by the queries to perform search more
efficiently on a table in the database.

Consider that you have a table with thousands of records and you have the below query that only a few
records can satisfy the condition, then it will take a lot of time to search and return those rows that abide by
this condition as the engine has to perform the search operation on every single to check this condition.

This is undoubtedly inefficient for a system dealing with huge data.

Now if this system had an index on the column where we are applying search, it can use an efficient method
for identifying matching rows by walking through only a few levels. This is called indexing.

Select * from some_table where table_col=120

How will you change the datatype of a column?


This can be done by using the ALTER TABLE statement as shown below:

Syntax:

ALTER TABLE tname


ALTER COLUMN col_name [SET DATA] TYPE new_data_type;

What is the command used for creating a database in PostgreSQL?

The first step of using PostgreSQL is to create a database. This is done by using the createdb command as
shown below: createdb db_name
After running the above command, if the database creation was successful, then the below message is shown:

CREATE DATABASE New Section 1 Page


How can we start, restart and stop the PostgreSQL server?

To start the PostgreSQL server, we run:

service postgresql start

Once the server is successfully started, we get the below message:

Starting PostgreSQL: ok

To restart the PostgreSQL server, we run:

service postgresql restart

Once the server is successfully restarted, we get the message:

Restarting PostgreSQL: server stopped


ok

To stop the server, we run the command:

service postgresql stop

Once stopped successfully, we get the message:

Stopping PostgreSQL: server stopped


ok

What are partitioned tables called in PostgreSQL?

Partitioned tables are logical structures that are used for dividing large tables into smaller structures that are
called partitions. This approach is used for effectively increasing the query performance while dealing with
large database tables. To create a partition, a key called partition key which is usually a table column or an
expression, and a partitioning method needs to be defined. There are three types of inbuilt partitioning
methods provided by Postgres:

Range Partitioning: This method is done by partitioning based on a range of values. This method is most
commonly used upon date fields to get monthly, weekly or yearly data. In the case of corner cases like value
belonging to the end of the range, for example: if the range of partition 1 is 10-20 and the range of partition 2
is 20-30, and the given value is 10, then 10 belongs to the second partition and not the first.

List Partitioning: This method is used to partition based on a list of known values. Most commonly used
New Section 1 Page
when we have a key with a categorical value. For example, getting sales data based on regions divided as
countries, cities, or states.

Hash Partitioning: This method utilizes a hash function upon the partition key. This is done when there are
no specific requirements for data division and is used to access data individually. For example, you want to
access data based on a specific product, then using hash partition would result in the dataset that we require

The type of partition key and the type of method used for partitioning determines how positive the
performance and the level of manageability of the partitioned table are.

Define tokens in PostgreSQL?

A token in PostgreSQL is either a keyword, identifier, literal, constant, quotes identifier, or any symbol that
has a distinctive personality. They may or may not be separated using a space, newline or a tab. If the tokens
are keywords, they are usually commands with useful meanings. Tokens are known as building blocks of any
PostgreSQL code.

What is the importance of the TRUNCATE statement?

TRUNCATE TABLE name_of_table statement removes the data efficiently and quickly from
the table.
The truncate statement can also be used to reset values of the identity columns along with data cleanup as
shown below:

TRUNCATE TABLE name_of_table


RESTART IDENTITY;

We can also use the statement for removing data from multiple tables all at once by mentioning the table names
separated by comma as shown below:

TRUNCATE TABLE
table_1,
table_2,
table_3;

What is the capacity of a table in PostgreSQL?

The maximum size of PostgreSQL is 32TB.

Define sequence.

A sequence is a schema-bound, user-defined object which aids to generate a sequence of integers. This
is most commonly used to generate values to identity columns in a table. We can create a sequence by
using the CREATE
SEQUENCE statement as shown below:

New Section 1 Page


To get the next number 101 from the sequence, we use the nextval() method as shown below:

SELECT nextval('serial_num');

We can also use this sequence while inserting new records using the INSERT command:

INSERT INTO ib_table_name VALUES (nextval('serial_num'), 'interviewbit');

What are string constants in PostgreSQL?

They are character sequences bound within single quotes. These are using during data insertion or updation to
characters in the database.
There are special string constants that are quoted in dollars. Syntax:
$tag$<string_constant>$tag$ The tag in the constant is optional and when we are not specifying the tag,
the constant is called a double-dollar string literal.

How can you get a list of all databases in PostgreSQL?

This can be done by using the command \l -> backslash followed by the lower- case letter L.

How can you delete a database in PostgreSQL?

This can be done by using the DROP DATABASE command as shown in the syntax below:

DROP DATABASE database_name;

If the database has been deleted successfully, then the following message would be shown:

DROP DATABASE

What are ACID properties? Is PostgreSQL compliant with ACID?

ACID stands for Atomicity, Consistency, Isolation, Durability. They are database transaction properties which
are used for guaranteeing data validity in case of errors and failures.

Atomicity: This property ensures that the transaction is completed in all-or- nothing way.

Consistency: This ensures that updates made to the database is valid and follows rules and restrictions.

Isolation: This property ensures integrity of transaction that are visible to all other transactions.

Durability: This property ensures that the committed transactions are stored permanently in the database.
PostgreSQL is compliant with ACID properties.

Can you explain the architecture of PostgreSQL?


New Section 1 Page
The architecture of PostgreSQL follows the client-server model.
The server side comprises of background process manager, query processer, utilities and shared memory space which work together to
build PostgreSQL’s instance that has access to the data. The client application does the task of connecting to this instance and requests
data processing to the services. The client can either be GUI (Graphical User Interface) or a web application. The most commonly used
client for PostgreSQL is pgAdmin

What do you understand by multi-version concurrency control?

MVCC or Multi-version concurrency control is used for avoiding unnecessary database locks when 2 or more
requests tries to access or modify the data at the same time.
This ensures that the time lag for a user to log in to the database is avoided. The transactions are recorded when
anyone tries to access the content.
For more information regarding this, you can refer here.

What do you understand by command enable-debug?

The command enable-debug is used for enabling the compilation of all libraries and applications. When this
is enabled, the system processes get hindered and generally also increases the size of the binary file. Hence,
it is not recommended to switch this on in the production environment. This is most commonly used by
developers to debug the bugs in their scripts and help them spot the issues. For more information regarding
how to debug, you can refer here.

How do you check the rows affected as part of previous transactions?

SQL standards state that the following three phenomena should be prevented whilst concurrent transactions.
SQL standards define 4 levels of transaction isolations to deal with these phenomena.
New Section 1 Page
Dirty reads: If a transaction reads data that is written due to concurrent uncommitted transaction, these reads are
called dirty reads.

Phantom reads: This occurs when two same queries when executed separately return different rows. For example, if
transaction A retrieves some set of rows matching search criteria. Assume another transaction B retrieves new rows
in addition to the rows obtained earlier for the same search criteria. The results are different.

Non-repeatable reads: This occurs when a transaction tries to read the same row multiple times and gets different
values each time due to concurrency. This happens when another transaction updates that data and our current
transaction fetches that updated data, resulting in different values.

To tackle these, there are 4 standard isolation levels defined by SQL standards. They are as follows:

Read Uncommitted – The lowest level of the isolations. Here, the transactions are not isolated and can read data that are
not committed by other transactions resulting in dirty reads.

Read Committed – This level ensures that the data read is committed at any instant of read time. Hence, dirty reads
are avoided here. This level makes use of read/write lock on the current rows which prevents
read/write/update/delete of that row when the current transaction is being operated on.

Repeatable Read – The most restrictive level of isolation. This holds read and write locks for all rows it operates on.
Due to this, non-repeatable reads are avoided as other transactions cannot read, write, update or delete the rows.

Serializable – The highest of all isolation levels. This guarantees that the execution is serializable where execution
of any concurrent operations are guaranteed to be appeared as executing serially.

What can you tell about WAL (Write Ahead Logging)?

Write Ahead Logging is a feature that increases the database reliability by logging changes before any
changes are done to the database. This ensures that we have enough information when a database crash
occurs by helping to pinpoint to what point the work has been complete and gives a starting point from the
point where it was discontinued.
For more information, you can refer here.

What is the main disadvantage of deleting data from an existing table using the DROP TABLE command?

DROP TABLE command deletes complete data from the table along with removing the complete table
structure too. In case our requirement entails just remove the data, then we would need to recreate the table
to store data in it. In such cases, it is advised to use the TRUNCATE command.

How do you perform case-insensitive searches using regular expressions in PostgreSQL?

To perform case insensitive matches using a regular expression, we can use POSIX

New Section 1 Page


(~*) expression from pattern matching operators. For example:

'interviewbit' ~* '.*INTervIewBit.*'

How will you take backup of the database in PostgreSQL?

We can achieve this by using the pg_dump tool for dumping all object contents in the database into a single file. The
steps are as follows:
Step 1: Navigate to the bin folder of the PostgreSQL installation path.

C:\>cd C:\Program Files\PostgreSQL\10.0\bin

Step 2: Execute pg_dump program to take the dump of data to a .tar folder as shown below:

pg_dump -U postgres -W -F t sample_data > C:\Users\admin\pgbackup\sample_data.tar

The database dump will be stored in the sample_data.tar file on the location specified.

Does PostgreSQL support full text search?

Full-Text Search is the method of searching single or collection of documents stored on a computer in a full-
text based database. This is mostly supported in advanced database systems like SOLR or ElasticSearch.
However, the feature is present but is pretty basic in PostgreSQL.

What are parallel queries in PostgreSQL?


Parallel Queries support is a feature provided in PostgreSQL for devising query plans capable of exploiting multiple
CPU processors to execute the queries faster.

Differentiate between commit and checkpoint.

New Section 1 Page


The commit action ensures that the data consistency of the transaction is maintained and it ends the current
transaction in the section. Commit adds a new record in the log that describes the COMMIT to the memory.

Whereas, a checkpoint is used for writing all changes that were committed to disk up to SCN which would
be kept in data file headers and control files.

Conclusion:

SQL is a language for the database.


It has a vast scope and robust capability of creating and manipulating a variety of database objects using
commands like CREATE, ALTER, DROP, etc., and also in loading the database objects using commands like
INSERT.
It also provides options for Data Manipulation using commands like DELETE, TRUNCATE and also does
effective retrieval of data using cursor commands like FETCH, SELECT, etc.
There are many such commands which provide a large amount of control to the programmer to interact with
the database in an efficient way without wasting many resources.
The popularity of SQL has grown so much that almost every programmer relies on this to implement their
application's storage functionalities thereby making it an exciting language to learn.
Learning this provides the developer a benefit of understanding the data structures used for storing the
organization's data and giving an additional level of control and in-depth understanding of the application.
PostgreSQL being an open-source database system having extremely robust and sophisticated ACID,
Indexing, and Transaction supports has found widespread popularity among the developer community.
===================================================================
------------------------------------------------------------------------------------------------------------------

References and Resources:

PostgreSQL Tutorial
SQL Guide
SQL Server Interview Questions
MySQL Interview Questions
DBMS Interview Questions
PL SQL Interview Questions
MongoDB Interview Questions
Database Testing Interview Questions
New Section 1 Page
SQL Vs NoSQL
SQL Vs MySQL

PostgreSQL vs MySQL

Difference Between SQL and PLSQL

SQL IDE

SQL Projects
MySQL Commands

==========================================================================
==========================================================================
==========================================================================

Differences between SQL and NoSQL


The table below summarizes the main differences between SQL and NoSQL databases.

SQL Databases NoSQL Databases

Document: JSON documents, Key-


Data Storage Tables with fixed value: key-value pairs, Wide-column:
Model rows and columns tables with rows and dynamic columns,
Graph: nodes and edges

Developed in the Developed in the late 2000s with a


Development 1970s with a focus focus on scaling and allowing for rapid
History on reducing data application change driven by agile and
duplication DevOps practices.

Oracle, MySQL, Document: MongoDB and CouchDB,


Examples Microsoft SQL Key-value: Redis and DynamoDB,
Server, and Wide-column: Cassandra and HBase,
PostgreSQL Graph: Neo4j and Amazon Neptune
New Section 1 Page
SQL Databases NoSQL Databases

Document: general purpose, Key-value:


large amounts of data with simple
lookup queries, Wide-column: large
Primary
General purpose amounts of data with predictable query
Purpose
patterns, Graph: analyzing and
traversing relationships between
connected data

Schemas Rigid Flexible

Vertical (scale-up
Horizontal (scale-out across commodity
Scaling with a larger
servers)
server)

Multi-Record Most do not support multi-record ACID


ACID Supported transactions. However, some — like
Transactions MongoDB — do.

Joins Typically required Typically not required

Many do not require ORMs. MongoDB


Requires ORM
Data to Object documents map directly to data
(object-relational
Mapping structures in most popular programming
mapping)
languages.

New Section 1 Page

You might also like