Professional Documents
Culture Documents
SQL- Abid 4
SQL- Abid 4
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.
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:
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.
CREATE / INSERT
READ / RETRIEVE
UPDATE / MODIFY
DELETE / DROP
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.
SQL follows a simple standard format MySQL has numerous variants and gets frequent
10. without many or regular updates. updates.
SQL NoSQL
These databases are not suited for hierarchical data These databases are best suited for
storage. hierarchical data storage.
To use Databases:
MYSQL use db_name;
SQL SERVERDrop down/In query.
CREATE DATABASE db_name;
CREATE DATABASE IF NOT EXISTS db_name;
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.
Database
DBMS
"It is a type of DBMS software in which we store the data in the form of Tables (Rows & Columns) ".
1. The data entered into a cell must always be a single valued data.
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.
USE db_name;
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);
ADD Column
DROP Column
RENAME Table
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.
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.
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( $ , & , @ , !
…).
Example:
STUDENT
Scale is not mandatory, and the default value of scale Is zero (0).
'DD-MON-YY' OR 'DD-MON-YYYY'
'22-JUN-20' '22-JUN-2020'
SYNTAX: DATE
5. Large Object
SQL Datatypes
In MySQL there are three main data types: string, numeric, and date and time.
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
BLOB(size) For BLOBs (Binary Large Objects). Holds up to 65,535 bytes of data
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
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)
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)
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.
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.
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
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
5-17 bytes
decimal(p,s) Fixed precision and scale numbers.
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
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
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.
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
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
sql_variant Stores up to 8,000 bytes of data of various data types, except text, ntext, and timestamp
Text Use for text or combinations of text and numbers. 255 characters maximum
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
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
Lookup Wizard Let you type a list of options, which can then be chosen from a drop-down list 4 bytes
---------------------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------------------
bit 0 1
varbinary(max) The maximum length of 231 bytes(SQL Server 2005 only).(Variable Length binary data)
DATETIME A data type is used to store both the data,date, and time in the record.
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?
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.
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 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.
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)
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.
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'
Child Table
Parent Tables
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:
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.
" 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.
SYNTAX:
SELECT * / [DISTINCT] Column_Name / Expression [ALIAS] FROM
Table_Name ;
ORDER OF EXECUTION
1. FROM Clause
2. SELECT Clause
NOTE:
Select ename ,
hiredate From emp ;
DEPT :
DEPTNO DNAME LOC
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
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
SNAME
SNAME
SELECT DISTINCT BRANCH
FROM STUDENT ;
BRANCH
ECE BRANCH
CSE ECE
ME CSE
ECE ME
CSE CIVIL
CIVIL
EXPRESSION
Example: 5 * 10
EMP
EID ENAME SAL
1 A 100
2 B 200
2 C 100
ALIAS
Select sal*12
From emp ;
SAL*12
1200
2400
1200
SYNTAX :
SELECT * / [DISTINCT] Column_Name / Expression [ALIAS] FROM
Table_Name
WHERE <Filter_Condition> ;
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).
ORDER OF EXECUTION
1. FROM
2. WHERE
3. SELECT
WHERE Clause
Example :
SELECT ENAME
FROM EMP
WHERE SAL > 300 ;
SELECT *
FROM
EMP
WHERE SAL < 1000 ;
EMP :
WAQTD name and hiredate of an employee hired
on '09-JUN-1981'
SELECT *
FROM
EMP
WHERE ENAME ='MILLER' ;
SELECT *
FROM
EMP
WHERE HIREDATE > '01-JAN-1982' > ;
OPERATORS IN SQL
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
CONCATENATION Operator :
Symbol : ||
Ename
ALLEN
MARTIN
SMITH
LOGICAL OPERATORS
ANSWERS :
Syntax:
Syntax:
Example :
Example :
SELECT ENAME
FROM EMP
WHERE SAL IS NULL ;
SELECT ENAME
FROM EMP
WHERE COMM IS NULL ;
WAQTD name , sal and comm of the emp if the emp doesn’t
earn both .
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 ;
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 .
Example :
SELECT *
FROM
EMP
WHERE ENAME ='SMITH' ;
SELECT *
FROM EMP
WHERE ENAME LIKE 'S%' ;
SELECT *
FROM
EMP
WHERE ENAME LIKE '%S' ;
WAQTD names of the employees who have character 'S' in
their names .
SELECT *
WAQTD names that starts with 'J' and ends with 'S' .
SELECT ENAME
FROM EMP
WHERE ENAME LIKE 'J%S' ;
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%' ;
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' ;
SELECT ENAME
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 ( )
Note: All aggregate functions described above ignore NULL values except for the COUNT function.
group by
NOTE :
Examples :
3. SELECT COUNT(*)
FROM EMP
WHERE SAL > 1500 AND DEPTNO = 20 ;
SELECT COUNT(*)
FROM EMP
WHERE ENAME LIKE '%E%' ;
SELECT COUNT(*)
FROM EMP
WHERE JIREDATE >'31-DEC-1982' AND HIREDATE
<'01- JAN-1985' AND DEPTNO IN ( 10 , 30 ) ;
SELECT COUNT(*)
FROM EMP
WHERE COMM IS NOT NULL ;
SELECT COUNT(*)
FROM EMP
WHERE DEPTNO IN ( 10 , 30 ) AND COMM IS NOT
NULL AND SAL IS NULL ;
ASSIGNEMENT ON MRF( )
ANSWERS :
A scalar function returns a single value based on the input value. Following are the widely used SQL scalar
functions:
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 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.
SYNTAX:
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 :
NOTE :
Questions :
ANSWERS :
SELECT DEPTNO,
AVG(SAL) FROM EMP
WHERE DEPTNO NOT IN 20
GROUP BY DEPTNO;
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:
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 :
6. WAQTD job and total salary of each job , if the total salary
Of each job is greater than 3450 .
NOTE :
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 .
Working Principle :
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
SELECT ENAME
FROM EMP
WHERE SAL > 2500 ;
SELECT ENAME
FROM EMP
WHERE SAL < ( SELECT SAL
FROM EMP
WHERE ENAME = 'MILLER' );
SELECT *
FROM
EMP
WHERE JOB = ( SELECT JOB
FROM EMP
WHERE ENAME ='KING' );
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 ;
SELECT *
FROM EMP
WHERE SAL > ( SELECT SAL
FROM EMP
WHERE ENAME ='SMITH' ) AND SAL < ( SELECT SAL
FROM EMP
WHERE ENAME ='KING' ) ;
10. WAQTD name and hiredate of the employees who's name ends
with 'S' and hired after James .
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');
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' ) ;
14. WAQTD Ename and SAL for all the employees earning more
than JONES .
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
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 );
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
SELECT DEPTNO
FROM EMP
WHERE ENAME ='MILLER' ;
SELECT DNAME
FROM
DEPT
WHERE DEPTNO = ( SELECT DEPTNO
FROM EMP
WHERE ENAME ='MILLER' ) ;
SELECT
LOC FROM
DEPT
WHERE DEPTNO = ( SELECT DEPTNO
FROM EMP
WHERE ENAME ='ADAMS' ) ;
SELECT ENAME
FROM EMP
WHERE DEPTNO = ( SELECT DEPTNO
FROM DEPT
WHERE LOC ='L2' ) ;
SELECT COUNT(*)
FROM EMP
WHERE DEPTNO = ( SELECT DEPTNO
FROM DEPT
WHERE DNAME ='D3' ) ;
SELECT *
SELECT *
FROM EMP
WHERE JOB = ( SELECT JOB
FROM EMP
WHERE ENAME ='MILLER' ) AND DEPTNO = (
SELECT DEPTNO FROM DEPT WHERE LOC ='NEW
YORK' ) ;
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 .
ASSIGNMENT ON CASE 2 :
SELECT
LOC FROM
DEPT
WHERE DEPTNO = ( SELECT DEPTNO
FROM EMP
WHERE COMM IS NOT NULL AND DEPTNO = 40 ) ;
SELECT ENAME
FROM EMP
WHERE SAL = MAX( SAL ) ;
SELECT ENAME
FROM EMP
WHERE SAL = ( SELECT MAX( SAL )
FROM EMP ) ;
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
SELECT DNAME
20
FROM DEPT
WHERE DEPTNO = ( SELECT DEPTNO
FROM EMP
WHERE ENAME = 'ALLEN' ) ;
"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
SAL
1000
2000 1000 > ALL ( 2000 , 1500 , 2500 )
3000 1000 > 2000 False
1500 1000 > 1500 False
2500 1000 > 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 ) ;
SELECT ENAME
FROM EMP
WHERE SAL < ALL ( SELECT SAL
FROM EMP
WHERE JOB='SALESMAN' ) ;
SELECT ENAME
FROM EMP
WHERE SAL < ANY ( SELECT SAL
FROM EMP
WHERE JOB ='SALESMAN' ) ;
SELECT ENAME
FROM EMP
WHERE SAL > ALL ( SELECT SAL
FROM EMP
WHERE ENAME ='ADAMS' ) ;
" A sub query written inside a sub query is known as Nested Subquery "
SELECT MIN(SAL )
FROM EMP
WHERE SAL > ( SELECT MIN(SAL )
FROM EMP
WHERE SAL > ( SELECT MIN ( SAL )
FROM EMP ) ) ;
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 :
CASE 1 :
SELECT ENAME
FROM EMP
WHERE EID = ( SELECT MGR
FROM EMP
WHERE ENAME ='SMITH' ) ;
SELECT ENAME
FROM EMP
WHERE EID = ( SELECT MGR
FROM EMP
WHERE EID = ( SELECT MGR
FROM EMP
SELECT DNAME
FROM DEPT
WHERE DEPTNO = ( SELECT DEPTNO
FROM EMP
WHERE EID = ( SELECT MGR
FROM EMP
WHERE ENAME ='KING' ) ) ;
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
SELECT ENAME
FROM EMP
WHERE MGR = ( SELECT EID
FROM EMP
WHERE ENAME ='KING' ) ;
SELECT DNAME
FROM DEPT
WHERE DEPTNO = ( SELECT DEPTNO
FROM EMP
WHERE MGR = ( SELECT EID
FROM EMP
WHERE JOB ='PRESIDENT' ) ) ;
SELECT *
FROM DEPT
WHERE DEPTNO = ( SELECT DEPTNO
FROM EMP
WHERE MGR = ( SELECT EID
FROM EMP
WHERE ENAME ='MILLER' ));
SUB QUERY :
Understand well from video
For example, here we fetch the contact information for students who have enrolled for the maths subject:
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 .
OR
SELECT
ENAME FROM
EMP
WHERE MGR =( SELECT MGR
FROM EMP
WHERE ENAME ='BLAKE' );
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.
Types of JOINS .
3. OUTER JOIN
i. LEFT OUTER JOIN
ii. RIGHT OUTER JOIN
iii. FULL OUTER JOIN
4. SELF JOIN
5. NATURAL JOIN .
EMP DEPT
Result Table :
SYNTAX:
SELECT Column_Name
FROM Table_Name1 CROSS JOIN Table_Name2 ;
2. Oracle
SELECT Column_Name
FROM Table_Name1 , Table_Name2 ;
Example :
2. INNER JOIN :
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;
Result Table :
Column_Name
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 .
Answers :
OUTER JOIN
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;
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 (+) ;
ENAME DNAME
A D2
C D1
B Null
D Null
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;
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 .
ENAME DNAME
A D2
C D1
Null D3
Null D4
Retrieves all the records where there is a match in either the left or right table.
SELECT *
FROM EMP FULL JOIN DEPT
ON EMP.DEPTNO = DEPT.DEPTNO ;
SELF JOIN :
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
Why ? / When ?
Example :
Result table :
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 .
Examples :
EMP DEPT
EMP.DEPTNO = DEPT.DEPTNO
E1.MGR = E2.EMPNO
E1
E2 E3
E1.MGR = E2.EMPNO
E2.MGR = E3.EMPNO
E1.MGR = E2.EMPNO
E1 D1 E2 D2
5. NATURAL 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
QUESTIONS:
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
" 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 :
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 .
SELECT DNAME
FROM DEPT D
New Section 1 Page
WHERE D.DEPTNO IN ( SELECT E.DEPTNO
FROM EMP E
WHERE D.DEPTNO = E.DEPTNO ) ;
SELECT DNAME
FROM DEPT D
WHERE D.DEPTNO NOT IN ( SELECT E.DEPTNO
FROM EMP E
WHERE D.DEPTNO = E.DEPTNO ) ;
SELECT SAL
FROM EMP E1
WHERE ( SELECT COUNT( DISTINCT SAL )
FROM EMP E2
WHERE E1.SAL < E2.SAL ) in ( 1 , 3, 4 , 6 ) ;
Example :
11 FROM DUAL;
DESC DUAL ;
SELECT *
FROM DUAL ;
Example :
Input : Smith
Output : Mr. Smith
Example :
REVERSE( 'SMITH' )
SELECT REVERSE( 'SMITH' ). HTIMS
FROM DUAL ;
UPPER( 'smith' )
SELECT UPPER( 'smith' ).
SMITH
FROM DUAL ;
SELECT SUBSTR(ENAME, -3 )
FROM EMP;
ENAME OUTPU
T
SMITH SM
MILLER MIL
JONES JO
WARD WA
ENAME OUTPU
T
SMITH ITH
MILLER LER
JONES NES
WARD RD
New Section 1 Page
SELECT SUBSTR( ENAME , LENGTH( ENAME ) / 2 + 1 )
FROM EMP ;
Length ( 'BANANA' ) -
LENGTH( REPLACE('BANANA','A') ) Length
('BANANA') - LENGH ('BNN' )
6-3
New Section 1 Page
= 3 times 'A' is present in BANANA
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 ".
B A N A N A
1 2 3 4 5 6
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
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;
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(
SELECT ENAME
FROM EMP
WHERE MOD( SAL , 3 ) = 0 ;
SELECT *
FROM EMP
WHERE MOD( EID , 2 ) = 1 ;
11. ROUND( ) : " It is used to Round-off the given number based on the scale value "
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
10. TRUNC( ): "It is similar to ROUND() but it always rounds-off the given number to the lower value "
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 "
SYSDATE
17-MAY-20
SYSTIMESTAMP
12. MONTHS_BETWEEN( ) :"It is used to Obtain the number of months present between the
Given two dates "
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" .
LAST_DAY
31-JUL-20
14. TO_CHAR( ) :"It is used to convert the given date into String format based on the Model given "
Format Models :
i. YEAR : TWENTY TWENTY
ii. YYYY : 2020
iii. YY : 20
iv. MONTH : JULY
v. MON : JUL
SELECT *
FROM EMP
WHERE TO_CHAR( HIREDATE , 'DAY' ) = 'SUNDAY' ;
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
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 .
OR
SELECT ENAME
FROM EMP
WHERE LENGTH( ENAME ) - LENGTH( REPLACE( ENAME , 'L' ) ) = 1 ;
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' ;
It has 5 statements :
1. CREATE
2. RENAME
3. ALTER
4. TRUNCATE
5. DROP
Example :
NOTE :
To Describe the table:
CUSTOMER PRODUCT
Example :
RENAME Customer TO Cust ;
TO ADD A COLUMN :
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 :
2. TRUNCATE : " IT IS USED TO REMOVE ALL THE RECORDS FROM THE TABLE
PREMANENTLY "
Cust
Cid Cname Phone_no Address
1 A 1234567890 BANGALORE
2 B 1234567899 MYSORE
3 C 1234567880 MANGALORE
Cust
Cid Cname Phone_no Address
1. DROP :" IT IS USED TO REMOVE THE TABLE FROM THE DATABASE "
Address : BIN$123ABCXYZ
Cust
FLASHBACK
Cust PURGE
DROP Gone
BIN$123ABC Forever
FLASHBACK
1. INSERT
2. UPDATE
3. DELETE
CUSTOMER
CID CNAME CNO ADDDRESS
NUMBER(2) VARCHAR(10) NUMBER(10 VARCHAR(20
) )
PRODUCT
PID PNAME PRICE CID
NUMBER(2) VARCHAR(10) NUMBER(6,2) NUMBER(3)
UPDATE
CUSTOMER SET
CNO = 7778889994
WHERE CNAME ='ABDUL' ;
UPDATE CUSTOMER
SET ADDRESS = 'MYSORE'
WHERE CID = 1 ;
5. WAQT hike the salary of the employee to 10% . If employees earn less than 2000 as a salesman .
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 .
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 ;
INSERT INTO T1
VALUES( 'A' , 100
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 ) .
Example :
C 300 S2
D 400
E S3
500
F 600
ROLLBACK TO S3
ROLLBACK TO S1
"This statement is used to control the flow of data between the users ".
We have 2 statements :
1. GRANT
2. REVOKE
User 1 : SCOTT
User 1 : SCOTT
User 2 : HR
EMP SELECT *
ENAM SAL FROM SCOTT.EMP ;
E
A 100
B 200
EMP
ENAM SAL
E
A 100
B 200
TRY !!!!
" 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
Or
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.
Note : If any Table / entity is reduced to 3NF , then the table is said to be normalized.
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
The Alchemist
62nd Sector (Paulo Coelho),
Ansh A- 10 Inferno (Dan Mr.
Brown)
Windsor
Ansh Street 777 Dracula (Bram Mr.
Stoker)
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)
:- ( Eid , deptno ) -> ( Ename , Sal , Dname , Loc ) composite key attribute
results in PFD
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.
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.
Amanora Park
1 Sara Town 94 1
24th Street
Park
3 Sara 3
Avenue
Windsor
4 Ansh Street 777 1
Salutation_ID Salutation
1 Ms.
2 Mr.
3 Mrs.
For the above relation to exist in 3NF, all possible candidate keys in the above relation should be {P, RS, QR, T}
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.
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.
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.
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.
TRUNCATE command is used to delete all the rows from the table and free the space containing the table.
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.
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 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 ] -
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.
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:
DELIMITER $$
CREATE PROCEDURE FetchAllStudents()
BEGIN
SELECT * FROM myDB.students;
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.
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%'
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%'
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%'
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.
The above image shows an example of SQL injections, through the use of 2 tables - students and library.
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.
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.
Nature of It is an application-oriented
It is a Data-oriented language.
4. Orientation language.
Declarative/
Procedural SQL is a declarative language. PL/SQL is a procedural language.
6. Language
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
SQL does not offer a high processing speed PL/SQL offers a high processing
11. Processing Speed for voluminous data. speed for voluminous data.
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.
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.
Syntax:
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:
Starting PostgreSQL: ok
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.
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.
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:
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;
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:
SELECT nextval('serial_num');
We can also use this sequence while inserting new records using the INSERT command:
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.
This can be done by using the command \l -> backslash followed by the lower- case letter L.
This can be done by using the DROP DATABASE command as shown in the syntax below:
If the database has been deleted successfully, then the following message would be shown:
DROP DATABASE
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.
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.
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.
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.
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.
To perform case insensitive matches using a regular expression, we can use POSIX
'interviewbit' ~* '.*INTervIewBit.*'
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.
Step 2: Execute pg_dump program to take the dump of data to a .tar folder as shown below:
The database dump will be stored in the sample_data.tar file on the location specified.
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.
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:
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
SQL IDE
SQL Projects
MySQL Commands
==========================================================================
==========================================================================
==========================================================================
Vertical (scale-up
Horizontal (scale-out across commodity
Scaling with a larger
servers)
server)