0% found this document useful (0 votes)
6 views

SQL_FINAL_NOTES

Uploaded by

nikhitabhatt153
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

SQL_FINAL_NOTES

Uploaded by

nikhitabhatt153
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Introduction to SQL Server

SQL Server Database Engine:


The core component is responsible for storing, managing, and retrieving data within the
database.

SQL Server Management Studio (SSMS):


A graphical user interface for managing all aspects of SQL Server, including creating
databases, writing queries, and administering server settings.

SQL Server Agent:


A service used to schedule automated tasks like backups, data refreshes, and custom
scripts at specific times.

SQL Server Reporting Services (SSRS):


A tool for designing, deploying, and managing reports based on data from SQL Server,
allowing users to visualize and analyze information through interactive reports.

SQL Server Integration Services (SSIS):


A platform for building data integration workflows, including data extraction,
transformation, and loading (ETL) processes between different systems.

SQL Server Analysis Services (SSAS):


Used for advanced data analysis, particularly for creating data cubes and performing
complex calculations to support business intelligence applications.

Data models

Conceptual: High-level data model focusing on data requirements.

Logical: Defines the structure and constraints without detailing physical implementation.

Physical: Defines how data is stored physically on the storage medium.


Datatypes:

Int, BigInt, SmallInt, TinyInt – Store integer values of different sizes.

Decimal, Numeric, Float, Real – Store floating-point or fixed-precision numbers.

Char, Varchar – Store fixed or variable-length character strings.

NChar, NVarchar– Store Unicode character strings.

Date, Time, DateTime – Store date and time values.

Bit – Stores Boolean values (0 or 1).

NOTE:

NCHAR: Uses 2 bytes per character (fixed length). 2 bytes rest same as CHAR.

NVARCHAR: Variable length character string, supporting Unicode characters.

Miscellaneous Knowledge:
JWT TOKENS

JWT tokens are compact, URL-safe tokens used for securely transmitting information
between parties, consisting of three parts: a header, a payload, and a signature.

JWT Token Structure:

Header

Payload

Signature

Instance: A running copy of an existing service.

SQL Server: A Relational Database Management System (RDBMS) that is used to store,
retrieve, and manage data.
OLTP (Online Transaction Processing): Focuses on real-time processing of transactional
data.

SQL server: RDBMS and is used for store, retrieve, manage data

SQL Server Architecture:

• Client: End-user application (e.g., SQL Server).


• Instance: A running copy of the SQL Server database engine.
• Databases: Logical containers for data.

ACID->Atomicity, Consistency, Isolation, durability

• Atomicity: Ensures transactions are all-or-nothing.


• Consistency: Ensures database transitions from one valid state to another.
• Isolation: Ensures transactions do not affect each other.
• Durability: Ensures that data is safely stored.

Jobs: Used to schedule and execute tasks frequently.


Eg. If you are importing new customer data from an external source, you can create a Job
to run a script that loads this data into the database at a scheduled time.

Cursor: A mechanism for processing results row-by-row within a database management


system.
Eg. In scenarios like order processing systems, Cursors can be used to loop through a list
of orders, check for specific conditions (e.g., whether the order is complete or pending),
and update the status of each order accordingly.
Login: Server-level authentication object.

Normalization: The process of organizing the data to reduce redundancy.


1NF (First Normal Form): Ensures atomic values. Use Case: Storing customer phone
numbers in separate rows.
2NF (Second Normal Form): Removes partial dependencies. Use Case: Splitting order
details into separate tables.
3NF (Third Normal Form): Removes transitive dependencies. Use Case: Separating
customer and location data.
Denormalization:

Used in data warehouses for analysis and reporting purposes, denormalization removes
the need for frequent CRUD operations.

Aliases
Used to rename a column or table for readability.

SELECT column1 AS alias_name FROM table_name;

CASE Statement

Performs conditional logic in queries.

SQL Joins & Set Operations

Joins

INNER JOIN: Returns only matching records from both tables.

SELECT A.column1, B.column2 FROM TableA A


INNER JOIN TableB B ON A.common_column = B.common_column;

LEFT JOIN: Returns all records from the left table and matching ones from the right.
SELECT A.column1, B.column2 FROM TableA A
LEFT JOIN TableB B ON A.common_column = B.common_column;

RIGHT JOIN: Returns all records from the right table and matching ones from the left.

SELECT A.column1, B.column2 FROM TableA A


RIGHT JOIN TableB B ON A.common_column = B.common_column;

FULL OUTER JOIN: Returns all records when there is a match in either table.

SELECT A.column1, B.column2 FROM TableA A


FULL OUTER JOIN TableB B ON A.common_column = B.common_column;

Set Operations

UNION: Combines results of two queries (removes duplicates).

SELECT column1 FROM TableA


UNION
SELECT column1 FROM TableB;

INTERSECT: Returns common records between two queries.

SELECT column1 FROM TableA


INTERSECT
SELECT column1 FROM TableB;

EXCEPT: Returns records from the first query that are not in the second.

Temporary Tables

Temporary tables store data temporarily for a session, ensuring the correct data is fetched
and manipulated for each call.

Syntax:

WITH Name AS (SELECT * FROM ...)


SELECT * FROM Name;

Types:

Local Temporary Tables (#table_name): Available only within the current session.

Global Temporary Tables (##table_name): Available across sessions.

Table Variables: Declared using DECLARE @table_name.

Views
Views allow querying of data without modifying the original table structure.

Key Points:

Cannot be easily modified (especially for multiple table joins).

Must be recreated if structure changes.

Managing Views:

sp_helptext [view_name]; -- View definition


SELECT * FROM information_schema.views; -- List of views

Stored Procedures

Stored procedures encapsulate multiple SQL statements for efficient execution.

Syntax:

CREATE PROCEDURE procedure_name @param INT AS BEGIN


SQL STATEMENTS
END;
EXEC procedure_name;

Scope Identity: Retrieves the last inserted identity value.

Triggers

Triggers automatically execute in response to specific events in the database.

Types:

DML Triggers: Fire on INSERT, UPDATE, DELETE operations.

DDL Triggers: Fire on schema modifications (CREATE, DROP).

Logon Triggers: Fire on user login events.

Example Trigger:

CREATE TRIGGER prevent_update ON Employees


FOR UPDATE AS BEGIN
INSERT INTO Employees_history
SELECT * FROM deleted;
END;

Grant & Revoke Permissions


Used to manage access control for database objects.

Grant Permission:

GRANT SELECT ON Orders TO user_intern;

Revoke Permission:

REVOKE SELECT ON Orders FROM user_intern;

Indexing & Performance Tuning

Indexes optimize query performance by reducing search time.

Types:

Clustered Index

Non-clustered Index

Example:

CREATE INDEX idx_name ON Employees (EmployeeID);

Performance Calculation:

Binary search: log2(n) vs. Linear search: O(n)

String Functions

String Functions

LEN(): Returns the number of characters in a string (excluding trailing spaces).

RTRIM(): Removes trailing spaces from a string.

LTRIM(): Removes leading spaces from a string.

SUBSTRING(): Extracts a substring from a string starting at a specified position.

CHARINDEX(): Finds the starting position of a substring within a string.

REPLACE(): Replaces all occurrences of a substring with another substring.

UPPER(): Converts all characters in a string to uppercase.

LOWER(): Converts all characters in a string to lowercase.

CONCAT(): Concatenates two or more strings into one.

LEFT(): Returns the left part of a string with a specified number of characters.
RIGHT(): Returns the right part of a string with a specified number of characters.

TRIM(): Removes leading and trailing spaces from a string.

REPLICATE(): Repeats a string a specified number of times.

STUFF(): Deletes a part of a string and inserts another string at a specified position.

FORMAT(): Formats a value as a string based on a specified format.

Denormalization

Denormalization is used in data warehouses for better query performance by reducing


joins.

Reduces CRUD operations, useful in OLAP systems.

ETL Process & Stage Tables

ETL (Extract, Transform, Load) is used to move data into a target system.

Stage Tables: Used to aggregate columns during ETL for transformations.

ALTER FUNCTION: Used to modify existing functions.

Delimiter Handling: Spaces or special characters used as separators.

KEY DIFFERENCES:

You might also like