HT
Techtutors
Institute for
Data Analytics
‘\ccasno2n, 729628008 MBlnogtechttersin @ vowtectuorsin
ae
| | l Wh
Introduction to SQL ste
SQL stands for Structured Query language, pronounced a5 “S-Q.1” or sometimes as “See. Quel’
‘Developed at IBM by Donald D.chamberin and Raymond F.Bayce in early 70s.
Data and Database -A database isan organized collection of structured information, or data typically
stored electronically na computer system.
Relational databases like MySQl Database, Oracle, MS SQ. Server, Sybase, ete. use ANSI SQL.
Features of SQL
SQL vs NoSQL.
‘SQL is primarily called ROBMS or Relational Databases whereas NoSOL.s a Nor-eatonal or
Distributed Database
SOL databases are table based databases whereas NoSOL databases can be document based,
key-value pairs, graph databases,
‘TecntutorsFeatures of SQL si
iy
Well defined standards and easy to learn.
Structured Query Language (SQL is the standard language used for
writing queries in a databases. It was approved by ISO
{international Standard Organization) and ANSI(American National
Standards Institute).
No coding needed.
Interactive language
Portability
‘Multiple data view
Installing SQL Express e.
alee
Environment
htty hoenixnap.com/kb/instal ress
key features:
1. Easy-to-use version for entnplevel databases,
2. No requirement for purchasing a license fortis edition
3, Features such as restoring and easy backup with support of
Microsoft
4. Comprises monitoring tools for efficient and efective
database management.
FechtutorsData types of SQL Sen
‘The data type of a column defines what value the column can hold: integer, character,
‘money, date and time, binary, and s0 on.
SQL Data Types
Each column in a database table's required to have @ name and a data type.
[An SQL developer must decide what type of data that willbe stored Inside eech column wen
Creating a table. The data type is a guideline for SQL to understand what type of data is
fexpected inside ofeach column, and i also identifies how SQL wil interact withthe stored data
‘Tecntutors
>
Data types of SQL wenTypes of SQLCOMMANDS aime
‘SAL Statements/Commands:
Some DDL COMMANDS Ste
CREATE Its tablerdatabase in al
Example
(OREATE DATABASE databasename;
ASE SALES
‘TecntutorsSome DDL COMMANDS
ALTER itis used to alter the structure ofthe database. This change could be ether to mod the
characteristics of an existing atibute or probably to add anew atte
Example
Here we want toad new column of “contact” in orders table:
ALTER TABLE ORDERS ADD CONTACT VARCHAR(20};
Here we want to drop 8 particular column:
‘Tecntutors
Some DDL COMMANDS wt
DROP:The D0? TABLE statement is used to drop an existing table ina database
iy
Example
DROP TABLE TABLE NAME:
“Thi wll ernove table from the databace,
DROP DATABASE DATABASE_NAME,
‘This wil remove the database,
‘TecntutorsSome DDL COMMANDS sae
‘TRUNCATE itis used 0 delete all the rows rom the table anlfree the apace containing he tebe,
Example
‘TRUNCATE TABLE Orders
‘Tecntutors
DATA CONTROL LANG. S
$0 Serer
DCL commands are use to grant and take back authority from any database user
Syntax:
—-GRANT Permissions Syntax
GRANT
ON 10
~-REVORE Permissions Syntax
REVOKE oN FROM
‘TecntutorsSome DML COMMANDS tie
INSERT :The INSERT staternent is 2 SOL quay. tis used to insert data into the row af able.
LUPDATE :This command is used to update or madity the value ofa column inthe table,
DELETE :tis used o remove one or more ow froma table,
‘SELECT: Tho SELECT stalomentis used to select data fom databace
Some DML COMMANDS
INSERT :The INSERT statement is a SQL query Its used to insert data into the row of a table,
Example
insert into DIVISIONS values
rope)
Insert into DIVISIONS values(1Europe)(2'North America),(3!Scandinavia),'4'South America);
insert into DIVISIONS (Divisionid DivisionName) values (S/america);
Insert into DIVISIONS(DivisionName) values(africa);
‘TecntutorsWHERE CLAUSE
‘The Hie louse Is used to iter records.
It is used to extract only those records that fll a specified condition
waERE_ condstson:
WuERE categoryanen" [vonens clothes
WHERE CLAUSE
SELECT CategoryId,Description FROM CATEGORIES:
WHERE CategoryName="women"s clothes’
SELECT CategoryId,Description FROM CATEGORIES
(WHERE CategoryName="baby clothes";
>
Sl sever
‘Tecntutors
>
Sl sever
‘TecntutorsSome DML COMMANDS wae
LUPDATE This command is used 0 update or modify the value of acolumn in the tableSome DML COMMANDS Line
DELETE itis used to remove one or more row from a tbe
DELETE FROM table_name WHERE condition;
Dolete All Records:
It's possible to delete all rows ina table without deleting te table. This means thatthe table
structure, attributes, and indexes will be intact:
DELETE FROM table name:
Some DML COMMANDS Ste
‘The se 110% statement is used to select data from a database,
Here, columnt, colurn2,... are the field names ofthe table you want to select data from. If
You want to select all the felds available in the table, use the following syntax:
felect * from CATEGORIES;ry
Some TCL COMMANDS se
1. Transaction Control Language commands are use to manage tarsactions inthe database,
Transactional contol commands ar used only DML Commands such 2s INSERT, UPDATE and
2
DELETE,
‘COMMIT, ROLLBACK and SAVEPOINT are the TCL commands used in SOL
COMMIT command is used to permanently save any transaction into the database.
ROLLBACK command restores the database to the last committed state, ROLLBACK also
used with the savepoint.
‘SAVEPOINT command is USED to save a transaction temporarily. This way users can rollback to
the point whenever its needed.
>
Si Server
SQL Commands are Sequential
Commands are executed in the order they are encountered.
DDL and DML commands can be mixed
For example, you can define a table, fill it up with contents, and
delete a columns.
That is, table definitions (relation schema) can be changed
during the lifespan of a database.
~The ability of doing so doesn’t imply it is a good practice.
Itis best the schema/design of a database is well thought
through before its useSQL constraints nike
‘SQL constraints are used to speciy rules forthe data in a table.
Constraints are usad ta limit the type of data that can go into a table. This ensures the accuracy
and rliabilty of the data in the table. If there is any violation between the constraint and the
data action, the action is aborted
+ Nlo® Sout = Ensures that @ column cannot have a NULL value
UNIQUE Ensures that all values ina column are diferent
PRIMARY s2¥ =A combination of a ior 2 and on0U. Uniquely Identifies each row in
a table
+ FoRCTEN xy - Prevents actions that would destroy links between tables
‘© culecx ~ Ensures that the values in 2 column satisfies a specic condition
© DEFAULT ~ Sets a default value for a column if no value is specified
‘Tecntutors
NOT NULL constraint saw
By default, a column can hold NULL values.
‘The Nov NULL eonstraine enforces a column to NOT accept NULL values.
‘This enforces afield to alvays contain a value, which means that you cannot insert a new
record, oF update a record without adding a value to this el
EXAMPLE:
1. ALTER TABLE offices ALTER COLUMN OfficeStatePravince VARCHAR(50) NOT
NULL
2. insert into offices values(5,'234 Sun Street’,98122,'Seattle',null,(206) 567
'5670"/(206) 567 5690'/USA');
3. UPDATE Offices SET OfficeStateProvince="WB’ WHERE OfficeCountry="France’
‘TecntutorsUnique key constraints sre
The Unique Constraint ensures the uniqueness of all values and no duplicate values
are entered in a column of a table.
The unique constraints can be created using CREATE or ALTER TABLE. Add unique
constraints after columns definitions in the CREATE TABLE statement.
Syntax
[ADD CONSTRAINT UNIQUE ()
# Both Unique constraint and Primary key constraint enforce uniqueness. It Is
recommended to use Unique constraint instead of Primary key constraint
whenever you want to enforce uniqueness in a column,
Unlike Primary key constraint, Unique constraints allow only one NULL value,
‘Tecntutors
Unique key constraints sie
‘* Aunique index is automatically created when a unique key constraint is
created,
‘© SQL Server raises an error whenever a duplicate value is inserted or
updated,
«When a Unique index is added to an existing column in a table, the
database engine first checks for the uniqueness of the specified column
data. If a duplicate entry is found, then the engine returns an error and
does not add the constraint.
* Aunique key in a table can be referenced by a Foreign Key from another
table.
EXAMPLE: alter table divisions add unique(DivisionID)
b. insert into Divisions values(1, 'Europe') //ERROR
©. ALTER TABLE divisions DROP CONSTRAINT UC;
‘Tecntutorscheck constraints whe
# A check constraint can be created with any logical Boolean that returns fs oF
False based on logical operators. For example, @ boolean expression Salas >
2000 and Salary < 4000 specifies that the value in the saisry column must be
‘more than 2000 and less than #000,
+ Aboolean expression of check constraint can use multiple columns.
* Asingle column can have multiple check constraints.
# Check constraints reject values that evaluate to False. If yau try to insert
value outside the check constraint value range then SQL engine throws an error
stating that the insert statement conflicted with the CHECK constraint and the
statement was terminated.
# Accheck constraint does not evaluate @ NULL value. So NULL can be inserted
without restriction. Use NOT NULL constraint to restrict the NULL values.
* Check constraints are not validated during the Delete statements.
+ You can enable or disable check constraints instead of deleting them.
‘Tecntutors
check constraints ake
In SQL Server, a check constraint is used to specify the limitation on the values of a
column when inserting or updating.
For example, use check constraint if a column required a date value in
specific range, or a value must be in some specific format e.g. value in the
zip_code column must be of 5 digits.
Syntax:
[ADD CONSTRAINT CHECK (60000);
2. update Employee_budget set [target per employee}=12000
sxpretsion>)
‘Tecntutorscheck constraints whe
>
DEFAULT key constraints = =--
The
v
ALTER TABLE [dbo].[Employee_budget]
ADD CONSTRAINT CHKTARGET CHECK ([target per employee]>60000
AND EmployeeID<=9);
Insert into Employee_budget values(9,6100);
ALTER TABLE Employee_budget
DROP CONSTRAINT CHKTARGET;
‘Tecntutors
constraint Is used to set a default value fora column,
‘The default value wil be added to all new records, f no other value s species.
The
constraint can also be used to insert system values, By using functions ke Garb816
[AUIER TABLE DIVISIONS ADD CONSTRAINT DEPAULE NAME ORFAULT ‘Rurope’ YOR Divisiontiane;
Anaert into Divisions (Division) values (5)
adds “Eucope’ by dafeult in next zow after insertion
Ansert into Divisione (DivieiontD) values (6) > —
will add null value in divisionlane column after dropping constraint,
‘TecntutorsPrimary key constraints = ««
‘The PRIMARY KEY constraint uniquely identifies each record in a table.
@ Atable can have only one primary key.
A primary key can be defined on one column or the combination of multiple
columns known as a composite primary key.
A primary key cannot exceed 16 columns and a total key length of 900 bytes.
The primary key uniquely identifies each row in a table. It is often defined on
the identity column.
© The Primary key column do not allow NULL or duplicate values. It will raise
an error if try to do so.
‘* Allcolurns defined within the primary key constraint must be defined as a
NOT NULL column,
‘Tecntutors
Primary key constraints Lew
buen ME ssn, 00 ARE HEF aot) //n tie Eo bee
Sh) PE tye te te an tt
2s tee uate pn Dt tt ely yee)
3. a ee eer pet BUM A: IR
4, NGERT mo smployee budget VALUES (7280000) ;
‘TecntutorsForeign key constraints wae
‘The foreign key establishes the relationship between the two tables and enforces
referential integrity in the SQL Server.
A foreign key column can be linked to a primary key or a unique key column of
the same or another table.
‘© The table having the foreign key constraint is called the child table, and the
table being referenced by the foreign key is called the parent table.
‘* Avalue other than NULL is entered in the column of the foreign key constraint,
that value must already exist in the referenced column of the parent table. Else
you will get a foreign key violation error.
* Foreign key constraints can reference tables within the same database in the
* Foreign key constraints can be defined to reference another column in the same
table, This is referred to as a self-reference
‘TecntutorsForeign key constraints wae
‘© A foreign key constraint on a single column (Column level constraint) can
reference only one column in the parent table and should have the same data
type as the referenced column
A foreign key constraint defined at the table level (on a combination of
columns) should have the same number of reference columns as the number of
columns defined in the constraint list. The data type of each column in the
constraint must be the same as the corresponding column in the column list.
‘© There is no limit on the number of foreign key constraints a table can contain
that references other tables.
‘© Foreign key constraints are not enforced on temporary tables,
CONSTRAINT FOREIGN KEY ()
REFERENCES ()
‘Tecntutors
Foreign key constraints se
Create a Foreign key in an Existing Table:
ust ont cae
so cotati foregone AoNS60 (sat
Neresaucxs (Coolumn_pame>)
Delete a Foreign Key:
ALTER TABLE
DROP CONSTRAINT Greater than
‘SELECT “ FROM Divisions WHERE DivisionID >7
< Less than
se Greater than or equa to ‘SELECT * FROM Divisions WHERE DivisionID >=7
= Less than or equal to ‘SELECT * FROM Divisions WHERE DivisionID <>7
SET OPERATORS Bn
Its used to combine the result of 2 or more Tables a8 single set of values,
4. Union
2. Unien ai
3. Intersect
4 Excopt
Rules on Set Operations:
‘© The result sets of all queries must have the same number of columns.
+ In every result set the data type of each column must match the data type of ts
corresponding column in the fist result
‘©The records from the top query must mate!
positional ordering ofthe records from the
bottom quer
‘+ The column names or aliases must be found out by the frst select statement
Techtutorsv
SET OPERATORS rain
Examples:
‘elect * from [dbo] {Employee_budget] UNION SELECT * FROM [dbo] [Employoe_ Salary}
‘elect * from [dbo] [Employee_budget] UNION ALL SELECT” FROM [dbol{Employee_ Salary]
seloct “from {dbo} {Employee _budget]
EXCEPT SELECT * FROM [dbo}{Employee_ Salary]
"from [dbo Emloye budget] INTERSECT SELECT "FROM [obol{Employee Sly]
fechtutors
SPECIAL OPERATORS Lew
4. Between
2 In
3 Uke
4 shal
Betwoen:Betueon is used to felch values from a given Range. Between operator is oretum the values fom source
Itcan be applied on smal o big range values only We should use and operator when we implement between operators
EXAMPLE: SELECT FROM Offices WHERE OFFICE BETWEEN 1 AND 3;
Inst works nthe oven tof valuos Inthe gen condition
+ Its an extension of Or operator
‘* The perfomance of in operators faster than OR operator. When we use OR operator we wil repeat te column
‘names again and again in the query but when we use in operaioe there is no need o repeat the column name in
‘he query In OR operator query length wil be increased,
EXAMPLE: select rom OFFICES whore Offs nt.) lac flom OFFICES wher Oice NOT 4.8)
‘TechtutorsSPECIAL OPERATORS few
2. -troprosontsa single char inthe expression.
8. [}Rrepresents a group of char
Example: select * from Divisions where DivisionName ike’
‘SELECT * FROM Divisions WHERE DivisionName LIKE ‘E(n-z%
SELECT” FROM Divisions WHERE DivislnNiame LKE'S_ a
‘Tecntutors
CREATE TABLE saw
Create Table Using Another Table
‘Acopy of an existing table can also be created using CREATE TABLE,
‘The new abe gets the same column definitions All columns or specific columns canbe selected
you create anew table using an existing abe, the new table wil be file with the existing values from the ol able.
‘SELECT * INTO New.table,name FROM old.table name;
select into test table from ofices
+ SELECT Office officoCity INTO city FROM Offices;
[SELECT "INTO New table name FROM old table name WHERE [condition |;
«SELECT Office, officecity INTO office1 FROM Offices where office between 1 and 4;
‘TecntutorsAGGREGATE FUNCTIONS...
1 APPROX_COUNT_DISTINCT: tt ovalustes an expression for each owin a group, and returns the approximate
‘urbe of urique non-null values in group.
41. SELECT APPROX COUNT DISTINCT(office) AS Distinct Office FROM [dbol{Oftcos};
2. SELEGT APPROX_COUNT DISTINCTIDWvisionIO) as DIS_ID FROM Divisions;
2.COUNT: function n SOL Server is 8 part ofthe aggregate function used for calculating the total number of rows
‘resent in the table When the result Set does not have any ows i etums NULL tis usually used withthe SELECT
statement, and ts tur ype is INT.
‘The COUNT( isa builtin function, which accepts a single parameter that can bea column or valid expression and returns
2 single result to surnmarize the Input dataset. This function doesnot ignore the NULL values as it considers them too
‘whe ealeulating the query’ resutt can also work with the WHERE, GROUP BY, ORDER BY, nd HAVING clauses to get
the fitered result
SELECT COUNT(expression) FROM table name(s)
IWHERE condltions;
‘Tecntutors
AGGREGATE FUNCTIONS...
1. COUNT(): is used with the SELECT statement to get the total numberof rows present ina result set. The esu
‘etcan contain nan nul ull,andduplleates rows,
2. COUNT(ALL expression): This function is used to get the total ruber of rows present inthe table without
contsining nui rows,
3. COUNT(DISTINCT expression}: This functions used to calculate only the unique numberof rows present inthe
table without containing nul values
‘SELECT COUNT‘) AS “Total Employee’ FROM Employee, Salary,
‘select count(istinct Dlisiontvame) AS “name from [abel [Wisin
‘select count DivsionName) AS “name" from fdbo}{Owsions
select count DivsionName)AS “name” from [bo]|Divsions] where dvisionideS
‘TecntutorsCLAUSES IN SQL wie
Clauses are in-built functions availabe tous in SQL.
‘wth te help of lausos, wo ean deal with data easly stored in te table,
Clauses help us fiter and analyze data quick. When we have large amounts of data stored inthe database, we
use Clauses to query and get data require bythe use.
CLAUSES IN SQL nie
Order By Clauses in SQL Server
‘The SQL Server Order By used to sort the data in ether Ascending or Descanding order.
SYNTAX:
SELECT columni, ..,columN FROM TableName ORDER BY column}, ...,column
‘ASCIDESC;
\We add ASC for ascending and DSC for descending with the column name in the query to display the
result rows in an ordered form,
SELECT EMPIDOFFICE FROM abc
‘ORDER BY EMPID Fentut
fechtutorsCLAUSES IN SQL woe
‘SQL GROUP BY Clause
The GROUP BY clause is used to group rows that have the same values in the result set.
SELECT Column FROM Table WHERE condition GROUP BY Column (ORDER BY Column];
SELECT EMPID,SUM(YEAR SALARY) FROM abe
Group BY ENPID
‘Fechtutors
CLAUSES IN SQL sew
SQL HAVING Clause
‘Actually, this clause is introduced to apply functions in the query with the WHERE clause. In SQL, the
HAVING clause was added because the WHERE clause could not be applied with aggregate functions.
SYNTAXSELECT Colunn FROM Table WHERE condition GROUP BY Column HAVING condition
[ORDER BY Column) ;
SELECT EMPID,SUM(YEAR_SALARY) FROM abe
GROUP BY EPID
mavina sow(resn_satany) > 20000; ‘FechtutorsCLAUSES IN SQL
SQL TOP Clause
The TOP clause is used to determine the numberof record rows to be shown in the result. This TOP clause
is used with SELECT statement specially implemented on large tables with many records,
SYNTAXSELECT TOP no|percentage ColunMlane(s) FROM TableName WHERE condition;
SELECT * FROM abe WHERE OFFICE <= 3:
SELECT TOP 3 * FROM [dbo] . [abc] ORDER BY Office DESC;
‘Fechtutors
IN AND NOT IN OPERATORS...
SSQLIN and NOT IN operators used to speciy mule values ina WHERE clause.
‘SQL IN ‘condition used oatow multiple valve in a WHERE clause conditon, SQL IN condition you can use when you
ged to use multiple OR condition
'SQL.IN condion alow only specie value in INSERT, UPDATE, DELETE, SELECT statement
SQL NOTIN :
‘SOL NOTIN condition used to exclude the defined multiple valve na WHERE clause condton. SOL NOT IN condition
‘ao identity by NOT operator.
NOTIN condition use with WHERE clause to exclude defines multiple vakins fram record data
SEISCr Pho abo WHERE empid MOF DH (1,510);
‘FechtutorsDATE FUNCTIONS INSQL 2.
Function Description
ETDATE Returns the current date and time
ATEPARTO Returns a single part ofa date/time
PATEADD() ‘Adds or subtracts a specified time interval from a date
DATEDIEE Returns the time between two dates
‘COMVERTO, Displays date/time data in different formats
SQL Server comes with the following data types for storing a date or a date/time value inthe database:
DATE - format YY¥Y-tiM-DD
DATETIME - format: YYYY-HM-DD HH:M:SS
SSMALLDATETIME = format: YYYY-MM-DD Hi:MI:SS
TIMESTAMP - format: @ unique number
‘Fechtutors
DATE FUNCTIONS INSQL
1 The GETOATE() function returns the current date and time from the SQL Server.
SELECT GETDATE() AS CurrentDaterine
2.The DATEPART() function is used to return a single part of a date/time, such as year, month, cay, hour,
SELECT DATRPART(year, GETDATE())
| DATEPART (ponth, °10/12/2022')
‘FechtutorsDATE FUNCTIONS INSQL 2.
3.The DATEADD() function adds or subtracts @ specified time interval from a date.
DaTEADD (datepart,munber, date)
SELECT DATEADD (month, 2, '20060830")
SELECT DATEADD (YEAR, 2, '2006-08-32")
4.The DATEDIFF() function returns the time between two dates.
DATEDIFE (datepart,startdate,enddate)
SELECT DATEDIFF (day, '2014-06-05', 2014-08-05") AS DiefDate
‘Fechtutors
DATE FUNCTIONS INSQL
5.The CONVERT() function is a genera function that converts an expression of one data type to another:
“The CONVERT() function can be used to display date/time data in different formats.
SPTAX: CONVERT (da
s_type Length) expression, style)
SELECT CONVERT (OATE, SYSDATEDIME()) ,CONVERT (DATE, SYSDATETINEOFPSET()) ,COUVERT
(DATE, SYSUTCATETTNR()) CONVERT (DATE, CURRENT_TIMESTAMP) CONVERT (DATR, GETDATE())
{:CONVERT (DATE, GETUTCOATE()) :
SELECT CONVERT (TIME, SYSDATETIME()) ,CONVERT (TIME, SYSOATETINEOFYSET()) , CONVERT
(2m, SYSUTCORTETINE()) CONVERT (TIME, CURRENE_SIMESTAMP) CONVERT (TIME, GETDATE())
Lowers (r1ME, GETOTCOATE()) ‘FechtutorsCASES IN SQL sew
The SQL CASE Statement:
‘The CASE statement goes through consitions and returns a value when the fst condkion Is mat (ike an Ishen-oise
statement). So, once a condition is tue it wil stop reading and etum the result Ifo conditions are tue, it retuns
th value in the ELSE cause. If there is no ELSE part and no conditons are tu, it returns NULL
case
WHEN conten THEN eesut
WHEN conationt THEN reeuin
ELSE recut
no, ‘FechtutorsCASES IN SQL
SELECT omployee. i, DEPARTMENT. 1D,
case.
WHEN DEPARTMENT_ID > 50 THEN "The dept is greater than 50”
WHEN department
= 60 THEN The department no Is 60"
ELSE "The department nos under 60
END AS QuantiyText
FROM omployess:
CASES IN SQL
SELECT EMPLOYEE. 0, RST MAME.DESIGNATION =
Risener
‘Fechtutors
sever
‘FechtutorsNORMALISATION iow
‘Database normalization isa database schema design technique, by which an existing schema is modified
‘to minimize redundancy and dependency of data,
+ Normalization split a large table into smaller tables and define relationships between them to increases the
clarity in organizing data
+The words normalization and normal form refer tothe etructure ofa databace.
+ Normatization was de
oped by IBM researcher EF. Codd Inthe 1870s.
ton increases clarity In organizing data in Databases,
‘Normalization of a Database is achioved by following a set of rules called orm" in ereating the database.
fechtutors
NORMALISATION wie
‘The database normalization process is divided int following the norma frm:
> First Normal Form (1NF)
> Second Normal Form (2NF)
> Third Normal Form (3NF)
> Boyce-Codd Normal Form (BCNF)
> Fourth Normal Form (4NF)
> Fifth Normal Form (5NF)NORMALISATION sew
First Normal Form (1NF)
Each column i unique in INF.
Sample Employoe table it esplays employons are working with multiple deparments.Employe
mein [52 | Marketing
lable following INF:
movin [32 | Sats
Matin 92 | Marketing, Sales coward [45 | Qualty Assurance
award | 45 | Guaity Assurance ye ge Toman Resource
Nex [38 | aan Resource ‘Fechtutors
NORMALISATION wow
‘Second Normal Form (2NF):The entity should be considered already in 1NF, and allatributes within the
entity should depend solely on the unique identifier of the entity.
P= = er
monitor apple monitor | 4 1 1 1
2 monitor | samsu 2 scanner | 2 1 2
0 no
3 sseanne poco 3 headph 3. le Is
r 3 poco
4 hheadph oneplu 4 34
s 4 coneplu
s
FechtutorsNORMALISATION iow
‘Third Normal Form (3NF):
‘The entity should be considered already i
‘entry (value) other than the key for the table.
H such an entity exists, move it outside into a new table.
NF is achieved, considered as the database is normalized.
2NF, and no column entry should be dependent on any other
‘Fechtutors
CASES IN SQL at
The SQL CASE Statement:
‘The CASE statement goes through canitions and returns a value when the fst condition is met (ike an i-then-else
statement). So, once @ condition is tue it wil sop reading and retum the resul Ifo conditions are bus, it returns
the value in the ELSE clause. lf there fs no ELSE part and no condlitons ae tue, returns NULL
case
LWMHEN conan THEN rasurt
WHEN conaiont THEN resuth
no, ‘FechtutorsCASES IN SQL
SELECT omployee. i, DEPARTMENT. 1D,
case.
WHEN DEPARTMENT_ID > 50 THEN "The dept is greater than 50”
WHEN department
= 60 THEN The department no Is 60"
ELSE "The department nos under 60
END AS QuantiyText
FROM omployess:
CASES IN SQL
SELECT EMPLOYEE. 0, RST MAME.DESIGNATION =
Risener
‘Fechtutors
sever
‘FechtutorsNORMALISATION iow
‘Database normalization isa database schema design technique, by which an existing schema is modified
‘to minimize redundancy and dependency of data,
+ Normalization split a large table into smaller tables and define relationships between them to increases the
clarity in organizing data
+The words normalization and normal form refer tothe etructure ofa databace.
+ Normatization was de
oped by IBM researcher EF. Codd Inthe 1870s.
ton increases clarity In organizing data in Databases,
‘Normalization of a Database is achioved by following a set of rules called orm" in ereating the database.
fechtutors
NORMALISATION wie
‘The database normalization process is divided int following the norma frm:
> First Normal Form (1NF)
> Second Normal Form (2NF)
> Third Normal Form (3NF)
> Boyce-Codd Normal Form (BCNF)
> Fourth Normal Form (4NF)
> Fifth Normal Form (5NF)NORMALISATION sew
First Normal Form (1NF)
Each column i unique in INF.
Sample Employoe table it esplays employons are working with multiple deparments.Employe
mein [52 | Marketing
lable following INF:
movin [32 | Sats
Matin 92 | Marketing, Sales coward [45 | Qualty Assurance
award | 45 | Guaity Assurance ye ge Toman Resource
Nex [38 | aan Resource ‘Fechtutors
NORMALISATION wow
‘Second Normal Form (2NF):The entity should be considered already in 1NF, and allatributes within the
entity should depend solely on the unique identifier of the entity.
P= = er
monitor apple monitor | 4 1 1 1
2 monitor | samsu 2 scanner | 2 1 2
0 no
3 sseanne poco 3 headph 3. le Is
r 3 poco
4 hheadph oneplu 4 34
s 4 coneplu
s
FechtutorsJOINS IN SQL sew
SQL JOIN:
‘A cot clause is used to combine rows from two or more tables, based on a related column between
them.
Join Fundamentals
By using joins, you can retrieve data from two or more tables based on logical elatonships between the tables. Joins Indeate
how SOL Server should use data from one table to select the rows in another table,
‘Ajpin condition defines the way two tablos aro related in a quary by:
‘+ Spectying the column from each table to be used for the jin. typical jin conalton species foreign key from
one tabe ands associated key inthe ater table
1 Spectying a logical operator for example, = or <>) tobe used in comparing vals rom the columns.
‘Fechtutors
JOINS IN SQL
SQL JOIN:
‘A.coiti clause Is used to combine rows from two or more tables, based on a related column between
them.
Join Fundamentals
By using joins, you can rerove data from two or more tables based on logical relationships between the tables sons ineate
how SQL Server should usa data from one table to salact the rows in another table,
‘Alpin condition defines the way two tables re related in a query by:
= Speciying the column from each table to be used! fo the jin. type jin coneiion specie foreign Key trom
‘one table and its associat key in tho other table
1 Spectying a logical operator for example, = or <>) tobe used in comparing values rom the columns
‘FechtutorsJOINS IN SQL
1. CROSS JOIN
2, EQUI JOIN
3. SELF JOIN
4. INNER JOIN
5, OUTER JOIN
© LEFT [outer] JOIN
© RIGHT[outer] JOIN
© FULL JOIN
JOINS IN SQL
Cross Join in SQL:
Risener
‘Fechtutors
Rl server
‘© The SOL CROSS JOIN produces a result set which isthe number of rows inthe ist table multiplied by the
‘numberof rows in the second table if no WHERE clause is used along with CROSS JOIN. This kind of result i
called as Cartesian Product
‘© I(WHERE clause's used with CROSS JOIN, It functions like an INNER JOIN,
‘© Analtemative way of achieving the same result isto use column names separated by commas after SELECT and
‘mentioning the table names involved, after a FROM clause,
‘FechtutorsJOINS IN SQL 2
Risener
EQUI JOIN : it performs a JOIN against equality oF matching colum(s) values ofthe associated tables. An equal
sign
is used as comparison operator inthe where clause to refer equality
‘You may also perform EQUI JOIN by using JOIN Keyword folowed by ON keyword ans then specifying names of the
columns along with their associated tabes to check equal
SYNTAX:
SELECT column tiet SELECT *
FROM tablet
JOIN table?
ION (join_condition)
‘table2.column_name:
‘Fechtutors
JOINS IN SQL
Self Join:
‘A salf jon isa join in which a table is joined wit itself (whichis also called Unary relationships), especially when the
table has a FOREIGN KEY which references its own PRIMARY KEY. To join a table isef means that each row ofthe
table's combined with itself and with evary other row ofthe table,
‘The se join can be viewed as a join of two copies ofthe same table. The table is not actualy copied, but SQL performs.
the command as though it were
SELECT a.column_name, bcolumn_name.
FROM tablet a, tablet b
WHERE a.common_filed = b.common fil
‘FechtutorsJOINS IN SQL ine
INNER JOIN:
‘The INNER JOIN selects all ous from both participating tables as long as there is a match between the columns. An
‘SQL INNER JOIN is same as JOIN clause, combining rows from two or more tables.
SELECT*
FROM tablet INNER JOIN tabie2
(ON tablet column_name =table2.column_name)
oR
SELECT*
FROM tablet
JOIN tabie2
(ON tablet column_nare = table2cokrmn name;
‘Fechtutors
JOINS IN SQL sai
What is the difference between Equi Join and Inner Join in SQL?
‘An equijin sa join wth a join condition containing an equalty operator. An equioin retums only the rows that have
‘equivalent values forthe specified columns.
‘An inner oin is a join of two or more tables that returns only those rows (compared using a comparison operator) that
satisfy the join condition,
What is the difference between Natural Join and Inner Join in SQL?
‘© Natural Joins a type of nner Join
‘© Inne jen provides the result based onthe matched data according tothe equality conn specifedin the query while
‘he natural Join provides the result based onthe column with he same name and same datatype present in tables tobe
fed. Moreover he sia fener in an nation ae ro
‘FechtutorsJOINS IN SQL sew
OUTER JOIN:
‘The SOL OUTER JOIN retums all rows from beth the participating tables which satisfy the jin condition along with
‘ous which 60 not satisfy the ln condition. The SQL OUTER JOIN operator (+) is used anly on one side ofthe jin
‘condition only.
“The subtypes of SQL OUTER JOIN:
+ FULOUTERJON
Select” FROM tablet table?
WHERE condition (6
‘Fechtutors
JOINS IN SQL wow
LEFT JOIN: This join returns al the rows ofthe table onthe eft side of the join and matching rows forthe table on the
right side of join, The rows for which there is no matching row on ight side, the result-set will contain nul. LEFT JOIN fs
‘also known as LEFT OUTER JOIN Syntax:
SELECT tablet .colunnt, tablei.column?, table? coluant,
FRO tablet
LEFT JOIN table?
ON tablel matching column = table? matching_column:
tablet: Firat table
table2: Second table
matching column: Colum cormen to both the tables
‘FechtutorsJOINS IN SQL ine
RIGHT JOIN: RIGHT JOIN is similar to LEFT JOIN. This join returns all the rows ofthe table on the ight side of te join
‘and matching rows forthe table on th let side of join, The rows for which there is no matching row on let side, the
resutset wll contain nul, RIGHT JOIN is also known as RIGHT OUTER JOIN. Syntax:
SELECT tablet .colunn1, table1.colum?, table? coluant,
FRow tablet
RIGHT JOIN table2
ON tablel.matching coluan = table?.matching_colunn;
table: First table.
table2: Second table
rcching column: column commen to both che tables Fentutors
JOINS IN SQL ain
FULL JOIN: FULL JOIN creates the result-set by combining result of both LEFT JOIN and RIGHT JOIN. The
result-set wll contain all the rows from both the tables, The rows for which there fs no matching, the result-set
will contain NULL values. Syntax:
SELECT tablet. colunnt tablet column?, table? colunal,
FULL Jom tabie?
ON tablel.matohing_coluan = table2.natching_colunn;
satehing column: Colin conan to oth the tables
‘FechtutorsPARTITION By in SQL P
SQL server
Database users use aggregate functions such as MAX(), MIN(), AVERAGE() and COUNT() for
performing data analysis. These functions operate on an entire table and return single aggregated data
Using the GROUP BY clause. Sometimes, we require aggregated values over a small set of rows. In this
case, the Window function combined with the aggrogate function helps achiev the desired
‘output. This function uses the OVER() clause, and it can include the following functions:
‘+ Partition By: This divides the rows or query result set into small partitions.
‘© Order By: This arranges the rows in ascending or descending order forthe pai
default order is ascending
We can use the SOL PARTITION BY clause with the OVER clause to specify the column on which we need to
Perform aggregation.
‘Fechtutors
PARTITION By in SQL P
SQL Server
SELECT first_name AS name, last_name,department,
min(salary) OVER(PARTITION BY first_name) joining date
FROM [dbo}.[Worker]
SELECT first_namo AS name, last_name,depariment,
min(salary) OVER(PARTITION BY last_name) joining_date
FROM [dbo} [Worker]
SELECT first_name AS name, last_name,salary,
SUM(salary) OVER(PARTITION BY last_name) TotalAmount,
‘Avg{salary) OVER(PARTITION BY last_name) Avgsalary,
Min(salary) OVER(PARTITION BY last_name) Minsalary,
MAX(salary) OVER(PARTITION BY last_name) Maxsalary
FROM [dbo} [Worker]
‘FechtutorsSUBQUERY in SQL
SQL server
© Asubquery is a query that is nested inside a SELECT, INSERT, UPDATE, oF DELETE statement, of
inside another subquery.
‘+ Asubquery can be used anywhere an expression is allowed.
‘¢ Asubquery is also called an inner quer
also called an outer quory or outer
cor inner select, while the statement containing a subquery is
!
‘© Many Transact-SaL statements that include subqueries can be alternatively formulated as joins.
«The SELECT query of a subquery Is always enclosed in parenthe:
‘Fechtutors
SUBQUERY in SQL
Subquery rules:
SQL Server
A subquery is subject to the following restrictions:
+ The select list of a subquery introduced with a comparison operator can include only one
expression or column name (except that EXISTS and IN operate on SELECT * or a list,
respectively)
+ Ifthe WHERE clause of an outer query Includes a column name, it must be join-compatible
with the column in the subquery select lst.
+ The DISTINCT keyword cannot be used with subqueries that include “GROUP BY.
+ ORDER BY can only be specified when ToP is also specified.
‘FechtutorsSUBQUERY in SQL >
SQL server
‘SELECT columnist (5) FROM table_name
WHERE eolumn.name OPERATOR
(SELECT columnist) FROM table name WHERED
EXAMPLE:
1.Fetch worker detail whose salary is more than 100000;
ind worker details with maximum salary.
3.Find worker details that do not have any departments.
4. Find all details of workers who earn more than the average salary In their department.
‘Fechtutors
VIEWS in SQL e
SQL Server
[AVIEW in SQL Sorver is ke a vitual table that contains data from one or multiple tables. It doesnot hold any data and
{doesnot ext physically inthe database. Similar toa SOL tabla, the vow name should be unique in a database. it contsins a sat
(of predefined SOL queres to fetch data from the database.
=e:
/—\,
‘FechtutorsVIEWS in SQL
(CREATE VIEW [WORKER DEPT IT] AS
‘SELECT FIRST_NAME, LAST NAME
FROM WORKER
WHERE DEPARTMENT = "ADMIN"
SELECT * FROM [dbo),WORKER DEPT IT]
SQL server
‘FechtutorsVIEWS in SQL
MODIFICATION :
ALTER VIEW (dbo) [WORKER DEPT IT]
as
SELECT WFirst_ Namo, W.Last Name,5.BONUS_AMOUNT
FROM WORKER W JOIN Sonus 8
(ON WWORKER ID = B.WORKER_REF_ID
WHERE SALARY >100000;
VIEWS in SQL
MODIFICATION :UPDATION IN TABLE THROUGH A VIEW
UPDATE [dbo} [WORKER DEPT IT]
SET BONUS_AMOUNT=10000
WHERE LAST NAME ='singhar
INSERTION IN TABLE THROUGH A VIEW
INSERT INTO [abo]. WORKER DEPT ITFIRST NAME, LAST_NAME)
VALUES ( ‘Arun’, ‘Singh);
SQL server
‘Fechtutors
SQL Server
‘FechtutorsSTORED PROCEDURES in SQI,>
What is a Stored Procedure?
[A stored procedure Is prepared SQL code that you can save, so the code can be reused over and over again
So if you have an SQL query that you write over and over again, save It as a stored procedure, and then just calito
‘You can also pass parameters to a stored procedure, so thatthe stored procedure can act based on the parameter
value(s) that is passed.
SYNTAX:
‘Fechtutors
STORED PROCEDURES in SQL
Server
Benefits of Using Stored Procedures:
1+ Reuse of code
4+ Easier maintenance
‘+ Improved performance
Types of Stored Procedures
“TemporaryTemporay procedures area form of user-defined procedures. The temporary procedures ave lke a permanent
procedure, excopt temporary procedures aro stored in temp,
‘System:System procedures are included with SOL Server. They are physically stored in the intemal, hidden Resource database
_andlogically appear inthe sys schama of every system- and user-defined database. ln addtion, the msdb database also
‘contains system stored procedures in he dbo schema that are used or scheduling alerts and jobs. Because systom procedures
start with he prefix sp_, we recommend that you do not use this prefix when naming user-defined procedures.
‘FechtutorsSTORED PROCEDURES in SQI,>
CREATING A STORED PROCEDURE:
Stored Procedure With One Parameter:
‘CREATE PROCEDURE SslectAlmorkers @namenvarchar3®)
‘SELECT “FROM Worker WHERE firstname = Gname
exec [dbo}{SeectAverkers] @namearun’ Fechtutors
STORED PROCEDURES in SQL>
Stored Procedure With Multiple Parameters:
(CREATE PROCEDURE SslactAllworkerst @name nvarchar(30), sal int
as.
‘SELECT * FROM Worker WHERE frst_name = @name and SALARY=@sal
‘exec [dbo] [SelectAllworkerst] @namex'monika’, @sal=100000
‘FechtutorsSTORED PROCEDURES in SQL*
LSorver
Modify a Stored Procedure:
ator procedure SelectAllworkers1 @sal int a8
SELECT*
FROM Worker
WHERE @salc>s00000;
‘exec SalectAliworkerst @ssl =0
Deleting a stored procedure:
DROP PROCEDURE []
‘Fechtutors
STORED PROCEDURES in SQL*
i Server
Displaying all the stored procedures:
‘SELECT namo AS procedure name
SCHEMA NAME(echema id) AS schema name
stype dese
soreate date
modify date
FROM sys.procedures;
‘FechtutorsINDEXES in SQL
SSQL Indexes are used in relational databases to quickly retieve data,
SQL server
They are similar to indexes atthe end ofthe books whose purpose is to find topic quickly. SQL provides Create Index, Aer
Index, and Drop Index commands that are used fo create anew index, update an existing index, and delete an index in SOL
Server
Type of Indexes
SQL Server supports two iypes of indexes
1. Chustered index
2 Non-Glustered Index
‘Fechtutors
INDEXES in SQL >
SQL Server
CREATE INDEX
The cw
08% Command Is used to create Indexes in tables (allows duplicate values).
Indexes are used to retrieve data from the database very fast. The users cannot see the indexes, they are just used
to speed up searches/queries.
create index 1X_worker_salary
‘on worker(salary ase);
Simple & Composite Indexes
‘+ Based onthe number of ealumns on which an index is created, indexes are classified into simple and composite indexes
‘© Whan indexes aro create on single columns then itis called a simple index and when tho index is created combination
vin utile columns then scaled a composts index
‘FechtutorsINDEXES in SQL
SQL server
COMPOSITE INDEX
create clustered index IX_worker on te(worker tile ase affected_from asc)
DELETING INDEX
dcop index on