0% found this document useful (0 votes)
1 views32 pages

Sqlnotes Updated

The document outlines various SQL Server editions, including Express, Developer, Standard, and Enterprise, highlighting their features and limitations. It also explains types of authentication (Windows and SQL Server), system databases (master, model, msdb, tempdb, resource), and DDL commands for managing database objects. Additionally, it covers best practices for database management and the differences between DROP, DELETE, and TRUNCATE commands.

Uploaded by

Sushmitha R
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views32 pages

Sqlnotes Updated

The document outlines various SQL Server editions, including Express, Developer, Standard, and Enterprise, highlighting their features and limitations. It also explains types of authentication (Windows and SQL Server), system databases (master, model, msdb, tempdb, resource), and DDL commands for managing database objects. Additionally, it covers best practices for database management and the differences between DROP, DELETE, and TRUNCATE commands.

Uploaded by

Sushmitha R
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Types of SQL Server Editions

1. SQL Server Express Edition

• Free version of SQL Server.

• Best for: Students, learning, small applications, or testing.

• Limitations:

o Max Database Size: 10 GB per database (older versions had 4 GB).

o Limited CPU usage: 1 CPU, 1 GB RAM.

o Basic features only — No SQL Agent, limited performance tuning.

• Advantage: Lightweight and easy to install for beginners.

2. SQL Server Developer Edition

• Free for development and testing purposes only (not for production use).

• Same features as Enterprise Edition, including:

o Advanced analytics

o Performance tuning tools

o Full-text search

• Best for: Developers building and testing enterprise applications.

3. Other Editions (for reference)

• Standard Edition: Suitable for small to medium-sized businesses with fewer


resource limits.

• Enterprise Edition: Full-featured version for large-scale enterprise systems


(costly).

Types of Authentication in SQL Server

1. Windows Authentication

• Uses your Windows login (AD/OS credentials).

• More secure and easier in internal networks.


• No need to enter username/password manually.

• Best for: Systems where users are part of the same network/domain.

Example: When you log in to SQL Server from your office computer without entering
any credentials — it uses your Windows account.

2. SQL Server Authentication

• Requires manually entering a username and password.

• Used when:

o The client is outside the network.

o The application uses its own login system.

• Common in hosted environments, cloud, or cross-system connections.

Example: When accessing a remote SQL Server from another server using a defined
SQL login like username: sa.

Summary Table

Feature Windows Authentication SQL Server Authentication

Requires SQL login


Login method Uses Windows account
(username/pwd)

More secure (uses


Security level Less secure (credentials stored)
Kerberos)

Usage Intranet/organization use Internet/external connections

Password
Managed by Windows Managed by SQL Server
management

System Databases in SQL Server

SQL Server includes five primary system databases:

Database Description

master Core system-level information


model Template for all new databases

msdb Stores scheduling, jobs, alerts, etc.

tempdb Temporary storage for sessions and operations

Hidden, read-only database that contains system objects (not user


resource
accessible directly)

1. MASTER Database

Purpose:

• Stores critical system-level information.

What it stores:

• Login accounts and permissions

• System configuration settings

• List of all databases on the instance

• Initialization information

• Endpoints, linked servers, system messages

• Information about database files, locations, and startup configuration

Important Facts:

• Without the master database, SQL Server cannot start.

• Cannot delete the master database.

• Default database when SQL Server starts (unless changed).

Example Use:

-- Display all databases


sp_helpdb;

In SQL Server, the sp_help command is a system stored procedure that provides
detailed information about database objects such as tables, views, indexes, and more.
It’s commonly used to retrieve metadata information about the structure of the
database.

For example, if you want to get information about a specific table, you can use the
sp_help command as follows:
EXEC sp_help 'TableName';

Where 'TableName' is the name of the table you want information about.

The sp_help command returns several details about the object, such as:

• Column names and data types

• Default values

• Constraints (e.g., primary key, foreign key)

• Indexes associated with the table

• Other relevant metadata

Example:

If you want to get information about a table named Employees, you would use:

EXEC sp_help 'Employees';

This would return details such as:

• Column names (e.g., EmployeeID, FirstName, LastName)

• Data types for each column (e.g., INT, VARCHAR)

• Constraints and indexes on the table.

It’s a useful command for quickly understanding the structure and properties of
database objects.

2. MODEL Database

Purpose:

• Serves as a template for all newly created databases.

What it stores:

• Default settings like collation, recovery model

• Default objects (tables, procedures) that you want to replicate to every new
database

Key Points:
• When you create a new database, it inherits model's structure.

• You can customize model to include objects that will appear in new databases.

Example:

-- Create a new database (inherits from model)


CREATE DATABASE TestDB;

3. MSDB Database

Purpose:

• Stores data used by SQL Server Agent for:

o Jobs

o Alerts

o Schedules

o Operators

o Backup and Restore history

o Maintenance plans

o Database Mail configuration

Key Features:

• Crucial for automation and monitoring in SQL Server.

• Often used in administrative tasks and scheduling.

Example Use Cases:

• Automatically send emails for failed jobs

• Schedule database backups every night at 12 AM

Example Query:

-- View job history


SELECT * FROM msdb.dbo.sysjobhistory;

In SQL Server, dbo stands for Database Owner. It is a default schema used in SQL
Server databases.
Explanation:

• Schema: A schema is a container that holds database objects like tables, views,
stored procedures, etc.

• dbo (Database Owner):

o It's the default schema for users who are owners of the database.

o If no schema is specified when creating or referencing an object, SQL Server


assumes dbo.

Example Breakdown:

SELECT * FROM msdb.dbo.sysjobhistory;

• msdb = system database.

• dbo = schema.

• sysjobhistory = table name.

This means: select everything from the sysjobhistory table in the dbo schema of the
msdb database.

Key Points:

• Schemas help organize database objects.

• You can create your own schemas too, e.g., CREATE SCHEMA hr;

• dbo is common in system and user databases as the default schema.

Would you like a list of other common schemas in SQL Server and their uses?

4. TEMPDB Database

Purpose:

• Stores temporary user objects and internal operations.

Used for:

• Temporary tables and variables

• Intermediate results for sorting, grouping, ordering


• Cursors, table variables, or spooling

• Versioning for transactions (e.g., SNAPSHOT isolation)

Key Properties:

• Recreated every time SQL Server restarts

• Shared by all users and sessions

• Performance-critical database

Example Use:

-- Create a temporary table


CREATE TABLE #TempTable (
ID INT,
Name VARCHAR(50)
);

Common System Usage Example:

SELECT * FROM Customers ORDER BY Name;


-- Internally uses tempdb for sorting operation

5. RESOURCE Database (Hidden)

Purpose:

• Contains system objects like:

o System stored procedures (sp_help, sp_helpdb)

o System views

o System functions

Key Points:

• Read-only and hidden from standard view

• Not visible in SSMS

• Used internally for upgrades, rollback of system objects

• Located in C:\Program Files\Microsoft SQL


Server\MSSQL15.MSSQLSERVER\MSSQL\Binn\
Summary Table

Database Role Key Features

master Stores system-level info Logins, DB info, config

model Template DB Inherited by new DBs

msdb Automation Jobs, Alerts, Backups

tempdb Temporary workspace Sorting, Temp tables

resource Hidden read-only Contains sys objects

Best Practices

• Backup master and msdb regularly.

• Avoid modifying system databases unless necessary.

• Use tempdb efficiently; avoid large temp tables in heavy-load systems.

• Use model wisely to include default tables/settings in new databases.

Great! Let’s break down your statements and show clear examples using sp_dboption,
along with how to set a database to:

1. Offline

2. Read-Only

3. Single-user mode

Note: sp_dboption is deprecated (not recommended) in newer versions of SQL


Server.

Instead, we use ALTER DATABASE now.

But for learning purposes, I’ll show both.

1. Set a Database to Offline

Recommended (Modern Method):


ALTER DATABASE Sales
SET OFFLINE WITH ROLLBACK IMMEDIATE;

• ROLLBACK IMMEDIATE: disconnects all users immediately.

Deprecated Method (Old):

EXEC sp_dboption 'Sales', 'offline', 'TRUE';

2. Set a Database to Read-Only

Recommended (Modern):

ALTER DATABASE Pubs


SET READ_ONLY;

To make it writable again:

ALTER DATABASE Pubs


SET READ_WRITE;

Deprecated:

EXEC sp_dboption 'Pubs', 'read only', 'TRUE';

To revert:

EXEC sp_dboption 'Pubs', 'read only', 'FALSE';

3. Set a Database to Single-User Mode

Recommended:

ALTER DATABASE Students


SET SINGLE_USER WITH ROLLBACK IMMEDIATE;

To revert to multi-user:
ALTER DATABASE Students
SET MULTI_USER;

Important Notes:

• EXEC is needed in T-SQL scripts or Command Prompt to run stored procedures


like sp_dboption.

• Avoid using sp_dboption in new projects — stick to ALTER DATABASE.

What is DDL in SQL?

DDL (Data Definition Language) is used to define, modify, or delete the structure of
database objects like:

• Tables

• Schemas

• Views

• Indexes

DDL commands affect the schema of the database.

DDL Commands with Examples

DDL Command Purpose

CREATE Creates new database objects (table, view, index, etc.)

ALTER Modifies existing database objects

DROP Deletes database objects permanently

Removes all records from a table, but keeps the table


TRUNCATE
structure

RENAME (optional in some Renames a database object (not supported in all


RDBMS) systems)

1. CREATE – Create a New Table or Object


Purpose: Used to create a new table, database, view, etc.

Example:

CREATE TABLE Students (


StudentID INT PRIMARY KEY,
Name VARCHAR(50),
Age INT,
Course VARCHAR(30)
);

This creates a Students table with 4 columns.

2. ALTER – Modify an Existing Table

Purpose: Used to add, delete, or modify columns in a table.

Add a New Column:

ALTER TABLE Students ADD Email VARCHAR(100);

Modify a Column:

ALTER TABLE Students ALTER COLUMN Name VARCHAR(100);

ALTER Command in SQL

Purpose:

ALTER is used to modify the structure of an existing database object like a table. You
can:

• Add new columns

• Modify existing columns

• Rename columns (in SQL Server using sp_rename)

• Delete columns

• Add constraints

• Drop constraints

• Change data types


Syntax:

ALTER TABLE table_name action;

Examples of ALTER in SQL Server

1. Add a New Column

ALTER TABLE Students ADD Email VARCHAR(100);

Adds a new column Email of type VARCHAR(100) to the Students table.

2. Add Multiple Columns

ALTER TABLE Students


ADD City VARCHAR(50), Country VARCHAR(50);

3. Modify Column Data Type

ALTER TABLE Students


ALTER COLUMN Name VARCHAR(100);

Changes the Name column's data type to VARCHAR(100).

4. Rename a Column (SQL Server specific)

EXEC sp_rename 'Students.Name', 'FullName', 'COLUMN';

Renames the column Name to FullName.

5. Drop (Delete) a Column


ALTER TABLE Students
DROP COLUMN Country;

Removes the Country column from the Students table.

6. Add a Constraint (e.g., NOT NULL or UNIQUE)

ALTER TABLE Students


ADD CONSTRAINT UC_Email UNIQUE (Email);

Adds a unique constraint on the Email column.

7. Drop a Constraint

ALTER TABLE Students


DROP CONSTRAINT UC_Email;

Drops the unique constraint UC_Email.

8. Add a Default Constraint

ALTER TABLE Students


ADD CONSTRAINT DF_City DEFAULT 'Bangalore' FOR City;

Sets a default value for City column.

9. Add Primary Key Constraint

ALTER TABLE Students


ADD CONSTRAINT PK_StudentID PRIMARY KEY (StudentID);

10. Add Foreign Key Constraint

ALTER TABLE Students


ADD CONSTRAINT FK_DeptID FOREIGN KEY (DeptID) REFERENCES
Departments(DeptID);

11. Rename Table (Not part of ALTER, but used similarly)

EXEC sp_rename 'Students', 'StudentDetails';

Summary of ALTER TABLE Actions

Action Syntax Example

Add Column ADD column_name datatype

ALTER COLUMN column_name


Modify Column Data Type
new_datatype

Drop Column DROP COLUMN column_name

Rename Column (SQL Server) EXEC sp_rename

Add Constraint ADD CONSTRAINT

Drop Constraint DROP CONSTRAINT

Would you like multiple-choice questions (MCQs) or a PDF based on these ALTER table
examples?

Drop (Delete) a Column:

ALTER TABLE Students DROP COLUMN Age;

Absolutely! Here's a complete guide to the ALTER command in SQL with all types of
examples for modifying tables using ALTER. This command is part of DDL (Data
Definition Language) and is very commonly used in SQL Server (SSMS) and other
RDBMS.

Here are some examples for the DROP command in SQL, demonstrating its use to
remove tables, databases, views, and other objects.

1. Drop a Table
Example 1:

To remove a table named Students:

DROP TABLE Students;

This will permanently delete the Students table along with all of its data and structure.
No rollback is possible once executed (unless wrapped in a transaction).

2. Drop a Database

Example 2:

To remove a database named SchoolDB:

DROP DATABASE SchoolDB;

This will completely delete the SchoolDB database, including all tables, views, stored
procedures, and data within it.

3. Drop a View

Example 3:

To remove a view named StudentView:

DROP VIEW StudentView;

This will delete the StudentView view, but the underlying table will not be affected.

4. Drop a Column (SQL Server)

SQL Server does not directly support DROP COLUMN via DROP command. Instead, you
use ALTER TABLE. However, here's an example of dropping a column:

ALTER TABLE Students DROP COLUMN Age;

This removes the Age column from the Students table. It’s part of ALTER command
rather than DROP.
5. Drop a Constraint

Example 4:

To remove a constraint named PK_StudentID (a Primary Key constraint):

ALTER TABLE Students


DROP CONSTRAINT PK_StudentID;

This will drop the primary key constraint on the StudentID column, but the table and
its data remain intact.

Important Notes about DROP Command:

• DROP removes the object entirely (table, database, or view).

• Cannot be rolled back unless part of a transaction.

• It is a permanent operation.

• It doesn’t just remove data, it removes the entire object structure (e.g., table
schema).

3. DROP – Delete an Object Permanently

Purpose: Used to permanently remove a table or other object. Data and structure both
will be lost.

Example:

DROP TABLE Students;

Warning: This cannot be rolled back. All data and table structure is deleted.

4. TRUNCATE – Delete All Data, Keep Structure


Purpose: Removes all rows from a table but retains the table structure for future use.

Example:

TRUNCATE TABLE Students;

Difference between DELETE and TRUNCATE:

Feature DELETE TRUNCATE

Can use WHERE

Rollback possible (mostly not)

Speed Slower Faster

Log generation Heavy Minimal

5. RENAME – Rename a Table (Note: Not supported in all SQL systems)

SQL Server doesn't support RENAME directly. You use sp_rename.

Example in SQL Server:

EXEC sp_rename 'Students', 'StudentInfo';

Quick Recap Table

Command Action Can be Rolled Back?

CREATE Defines a new object

ALTER Modifies an existing object

DROP Deletes object permanently

TRUNCATE Deletes all records only

RENAME Changes object name (in most RDBMS)

Here’s a detailed explanation of the differences between DROP, DELETE, and


TRUNCATE in SQL, focusing on their usage, behavior, and impact on the database.
Difference between DROP, DELETE, and TRUNCATE in SQL

Feature DROP DELETE TRUNCATE

Deletes the entire table Removes data from a Removes all data from a
or object permanently table but retains the table but retains the
Purpose
(including structure and table structure for future table structure for future
data). use. use.

Deletes the table


Affects Deletes only the data Deletes all rows (data) in
structure and data
Data (rows). the table.
completely.

Table Yes, removes the table No, the structure No, the structure
Structure structure. remains intact. remains intact.

No (in most databases). No, once executed, the


Yes, rollback is possible
Roll- Once dropped, it cannot operation cannot be
if the transaction is not
backable be undone unless in a rolled back unless
committed.
transaction. inside a transaction.

Faster than DELETE as it


Fast, as it removes the Slower, as it removes
Speed doesn't log individual
entire table. rows one by one.
row deletions.

Does not fire triggers Does not fire triggers


Triggers (because the table is Fires DELETE triggers. (since it is a bulk
removed). operation).

When you want to delete


When you want to When you want to
all data in a table but
Use Case completely remove the remove specific rows
retain the structure for
table or object. or filter data.
reuse.

Can't be rolled back


Can't be rolled back
Transactionwithout transaction Can be rolled back using
unless used within a
Control support (in some COMMIT/ROLLBACK.
transaction.
RDBMS).

1. DROP Command

Purpose:

The DROP command is used to completely remove a database object like a table,
view, index, or schema. It deletes both the data and the structure of the object.
Example:

DROP TABLE Students;

Behavior:

• Deletes the entire table including both the data and the table structure.

• Cannot be rolled back (unless in a transaction).

• No triggers are fired.

• Fast because it doesn’t have to scan or delete each row.

2. DELETE Command

Purpose:

The DELETE command is used to remove specific rows from a table based on a
condition (WHERE clause). It only removes the data, not the table structure.

Example:

DELETE FROM Students WHERE Age > 25;

Behavior:

• Deletes data based on a condition (WHERE clause).

• Table structure remains unchanged.

• Triggers are fired (if any are defined).

• Can be rolled back if not committed.

• Slower compared to TRUNCATE because each row is logged and deleted one at
a time.

3. TRUNCATE Command

Purpose:

The TRUNCATE command removes all rows from a table but preserves the table
structure. It is more efficient than DELETE when you need to delete all records in a
table.

Example:
TRUNCATE TABLE Students;

Behavior:

• Deletes all rows but keeps the table structure intact.

• Cannot be rolled back (unless in a transaction in some systems).

• No triggers are fired (because it doesn’t log each row deletion).

• Faster than DELETE as it doesn’t log individual row deletions, but the table’s
metadata is updated.

Quick Comparison:

Feature DROP DELETE TRUNCATE

Data Yes, removes both data Removes data only Removes all data but keeps
Removal and structure (with WHERE clause) structure

Triggers No Yes, triggers are fired No triggers fired

No (unless in a
Rollback Yes (if not committed) No (unless in a transaction)
transaction)

Fast (removes Slower (row by row Faster than DELETE (bulk


Speed
everything) deletion) operation)

When you want to


Use When you want to When you want to delete all
completely remove a
Case delete specific rows data but retain the structure
table

When to Use Each?

• DROP: Use when you want to completely remove a table or database object.

• DELETE: Use when you want to delete specific rows based on a condition (with
the ability to rollback).

• TRUNCATE: Use when you want to quickly delete all rows in a table but keep the
table structure for future use.

Here is a detailed explanation of SQL commands, categorized into DML, DQL, DCL,
and TCL, with examples for each.
1. DML (Data Manipulation Language)

Purpose:

DML is used for managing data within schema objects. It involves the operations to
insert, update, delete, and retrieve data from the database.

Main Commands in DML:

• INSERT: Adds new rows to a table.

• UPDATE: Modifies existing rows in a table.

• DELETE: Removes rows from a table.

• MERGE (Optional, used in some DBMS): Combines INSERT, UPDATE, and


DELETE into one command.

Example 1: INSERT

Used to insert new records into a table.

INSERT INTO Students (StudentID, Name, Age, City)


VALUES (101, 'John Doe', 22, 'New York');

This command inserts a new student record into the Students table.

Example 2: UPDATE

Used to modify existing records in a table.

UPDATE Students
SET Age = 23
WHERE StudentID = 101;

This command updates the Age of the student with StudentID = 101 to 23.

Example 3: DELETE

Used to delete rows from a table.


DELETE FROM Students
WHERE StudentID = 101;

This command deletes the record of the student with StudentID = 101.

Example 4: MERGE (Optional)

Combines INSERT, UPDATE, and DELETE in a single statement.

MERGE INTO Students AS target


USING (SELECT * FROM NewStudents) AS source
ON target.StudentID = source.StudentID
WHEN MATCHED THEN
UPDATE SET target.Name = source.Name
WHEN NOT MATCHED THEN
INSERT (StudentID, Name, Age) VALUES (source.StudentID, source.Name,
source.Age);

This statement checks for existing records in the Students table. If a record is found, it
updates it; if not, it inserts a new record.

2. DQL (Data Query Language)

Purpose:

DQL is used for querying and retrieving data from the database. It consists mainly of the
SELECT statement.

Main Command in DQL:

• SELECT: Retrieves data from the database.

Example 1: SELECT

Basic query to retrieve data.

SELECT Name, Age


FROM Students;

This retrieves the Name and Age of all students in the Students table.
Example 2: SELECT with WHERE Clause

Used to filter data based on a condition.

SELECT Name, Age


FROM Students
WHERE Age > 20;

This retrieves the Name and Age of students whose age is greater than 20.

Example 3: SELECT with Aggregate Functions

Used to perform calculations on data.

SELECT AVG(Age) AS AverageAge


FROM Students;

This calculates the average Age of all students in the Students table.

Example 4: SELECT with JOIN

Used to combine data from multiple tables.

SELECT Students.Name, Courses.CourseName


FROM Students
JOIN Enrollments ON Students.StudentID = Enrollments.StudentID
JOIN Courses ON Enrollments.CourseID = Courses.CourseID;

This retrieves the names of students and the courses they are enrolled in by joining
Students, Enrollments, and Courses.

3. DCL (Data Control Language)

Purpose:

DCL is used to control access to data within the database. It involves granting and
revoking permissions on tables and other objects.

Main Commands in DCL:


• GRANT: Provides specific privileges to users.

• REVOKE: Removes specific privileges from users.

Example 1: GRANT

Used to give a user or role specific permissions.

GRANT SELECT, INSERT, UPDATE ON Students TO User1;

This grants User1 permission to SELECT, INSERT, and UPDATE data in the Students
table.

Example 2: REVOKE

Used to remove specific permissions from a user.

REVOKE UPDATE ON Students FROM User1;

This revokes the UPDATE permission on the Students table from User1.

Example 3: GRANT with OPTION

Grants permissions along with the ability to grant those permissions to others.

GRANT SELECT ON Students TO User1 WITH GRANT OPTION;

This grants User1 SELECT permissions on the Students table and allows User1 to grant
SELECT permissions to others.

4. TCL (Transaction Control Language)

Purpose:

TCL commands are used to manage transactions within the database. These operations
allow for committing or rolling back changes to ensure data consistency and integrity.

Main Commands in TCL:

• COMMIT: Saves all changes made during the current transaction.

• ROLLBACK: Undoes changes made during the current transaction.


• SAVEPOINT: Sets a point in the transaction to which you can later roll back.

• SET TRANSACTION: Used to set the properties of a transaction.

Example 1: COMMIT

Used to save all changes made during the current transaction.

BEGIN TRANSACTION;
UPDATE Students
SET Age = 24
WHERE StudentID = 102;
COMMIT;

This commits the UPDATE to the Students table, making the change permanent.

Example 2: ROLLBACK

Used to undo changes made during the current transaction.

BEGIN TRANSACTION;
UPDATE Students
SET Age = 24
WHERE StudentID = 102;
ROLLBACK;

This rolls back the UPDATE operation, undoing the change to the Students table.

Example 3: SAVEPOINT

Sets a save point within the transaction to which you can later roll back.

BEGIN TRANSACTION;
UPDATE Students
SET Age = 24
WHERE StudentID = 102;
SAVEPOINT SavePoint1;
UPDATE Students
SET Age = 25
WHERE StudentID = 103;
ROLLBACK TO SavePoint1;
COMMIT;

This rolls back the second update (StudentID = 103) but keeps the first update
(StudentID = 102).

Example 4: SET TRANSACTION

Used to define properties of a transaction, such as isolation level.

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;


BEGIN TRANSACTION;
UPDATE Students
SET Age = 24
WHERE StudentID = 102;
COMMIT;

This sets the transaction isolation level to SERIALIZABLE, ensuring the transaction is
fully isolated from other transactions.

Summary

• DML (Data Manipulation Language): Manages data within tables (INSERT,


UPDATE, DELETE, MERGE).

• DQL (Data Query Language): Retrieves data from the database (SELECT).

• DCL (Data Control Language): Controls access to data (GRANT, REVOKE).

• TCL (Transaction Control Language): Manages transactions (COMMIT,


ROLLBACK, SAVEPOINT, SET TRANSACTION).

1. Numeric Data Types

These data types store numeric values, both integers and decimals.

• INT:

o Description: Stores whole numbers.

o Range: -2,147,483,648 to 2,147,483,647.

o Storage: 4 bytes.

• BIGINT:
o Description: Stores large whole numbers.

o Range: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.

o Storage: 8 bytes.

• SMALLINT:

o Description: Stores small whole numbers.

o Range: -32,768 to 32,767.

o Storage: 2 bytes.

• TINYINT:

o Description: Stores very small whole numbers.

o Range: 0 to 255.

o Storage: 1 byte.

• DECIMAL(p,s) or NUMERIC(p,s):

o Description: Stores fixed precision and scale numbers.

o Range: Based on p (precision) and s (scale).

o Storage: 5 to 17 bytes.

o Example: DECIMAL(10,2) stores numbers with 10 digits, 2 of which are after the
decimal point (e.g., 12345678.90).

• FLOAT:

o Description: Stores floating-point numbers.

o Range: -1.79E+308 to 1.79E+308.

o Storage: 4 bytes (for FLOAT(24)) or 8 bytes (for FLOAT(53)).

• REAL:

o Description: Stores smaller floating-point numbers.

o Range: -3.40E+38 to 3.40E+38.

o Storage: 4 bytes.

2. Date and Time Data Types

These types are used to store dates and time values.

• DATE:
o Description: Stores only the date part (year, month, day).

o Range: '0001-01-01' to '9999-12-31'.

o Storage: 3 bytes.

• TIME:

o Description: Stores only the time part (hour, minute, second).

o Range: '00:00:00.0000000' to '23:59:59.9999999'.

o Storage: 5 bytes.

• DATETIME:

o Description: Stores both date and time.

o Range: '1753-01-01 00:00:00.000' to '9999-12-31 23:59:59.997'.

o Storage: 8 bytes.

• DATETIME2:

o Description: Stores date and time with more precision.

o Range: '0001-01-01 00:00:00.0000000' to '9999-12-31 23:59:59.9999999'.

o Storage: 6 to 8 bytes, based on precision.

• SMALLDATETIME:

o Description: Stores date and time with less precision than DATETIME.

o Range: '1900-01-01 00:00:00' to '2079-06-06 23:59:59'.

o Storage: 4 bytes.

• DATETIMEOFFSET:

o Description: Stores date and time with timezone offset.

o Range: '0001-01-01 00:00:00.0000000 +14:00' to '9999-12-31 23:59:59.9999999


-14:00'.

o Storage: 10 bytes.

3. String Data Types

These data types are used for storing text.

• CHAR(n):

o Description: Stores fixed-length character strings.


o Storage: 1 byte per character.

o Example: CHAR(10) stores a string of exactly 10 characters.

• VARCHAR(n):

o Description: Stores variable-length character strings.

o Storage: 1 byte per character.

o Example: VARCHAR(50) stores up to 50 characters but uses only the space


needed.

• TEXT:

o Description: Stores large amounts of text (deprecated in newer versions).

o Storage: Varies, up to 2 GB.

• NCHAR(n):

o Description: Stores fixed-length Unicode character strings.

o Storage: 2 bytes per character.

o Example: NCHAR(10) stores a string of exactly 10 Unicode characters.

• NVARCHAR(n):

o Description: Stores variable-length Unicode character strings.

o Storage: 2 bytes per character.

o Example: NVARCHAR(50) stores up to 50 Unicode characters.

• NTEXT:

o Description: Stores large amounts of Unicode text (deprecated in newer


versions).

o Storage: Varies, up to 2 GB.

4. Binary Data Types

These are used to store binary data (non-text data).

• BINARY(n):

o Description: Stores fixed-length binary data.

o Storage: 1 byte per character.

o Example: BINARY(10) stores 10 bytes of binary data.

• VARBINARY(n):
o Description: Stores variable-length binary data.

o Storage: 1 byte per character.

o Example: VARBINARY(50) stores up to 50 bytes of binary data.

• IMAGE:

o Description: Stores large binary data, like images or files (deprecated).

o Storage: Up to 2 GB.

5. Other Data Types

These data types serve specific purposes.

• BIT:

o Description: Stores a binary value (0 or 1).

o Storage: 1 byte.

o Example: BIT can be used to represent boolean values (TRUE or FALSE).

• UNIQUEIDENTIFIER:

o Description: Stores globally unique identifiers (GUIDs).

o Storage: 16 bytes.

o Example: NEWID() generates a new GUID.

• MONEY:

o Description: Stores currency values.

o Range: -922,337,203,685,477.5808 to 922,337,203,685,477.5807.

o Storage: 8 bytes.

• SMALLMONEY:

o Description: Stores smaller currency values.

o Range: -214,748.3648 to 214,748.3647.

o Storage: 4 bytes.

6. Other Specialized Data Types

• XML: Stores XML data.

o Storage: Varies depending on the XML content.

• SQL_VARIANT: Can store any data type, except TEXT, NTEXT, and IMAGE.
o Storage: Varies based on the stored value.

• GEOGRAPHY: Stores geospatial data.

o Storage: Varies depending on the data.

• HIERARCHYID: Stores hierarchical data.

o Storage: Varies based on the data.

Conclusion

These data types help SQL Server store a variety of information efficiently and in a
structured way. By selecting the correct data type, you can optimize storage space and
performance for your database. In SSMS, you would define these data types when
creating or altering tables to ensure the appropriate data is stored in each column.

• User defined datatypes

add

sp_addtype city , ‘nvarchar(15)’, NULL

drop

sp_droptype city

User-Defined Data Types (UDTs) in SQL Server (SSMS)

In SQL Server, a User-Defined Data Type (UDT) is a custom data type that is based on
one of the existing system data types (like int, varchar, etc.), but with a custom name
and optional constraints.

Why use UDTs?

• Standardization: Ensures consistency across multiple tables and procedures.

• Reusability: Define once, use many times.

• Abstraction: Hides underlying system data type and constraints from the user.
Syntax to Create a User-Defined Data Type:

sp_addtype type_name, base_type, 'NOT NULL' | 'NULL'

Note: This works in older versions of SQL Server. In modern versions, use CREATE
TYPE.

Example using CREATE TYPE:

-- Step 1: Create a User-Defined Data Type


CREATE TYPE PhoneNumber FROM VARCHAR(10) NOT NULL;
GO

-- Step 2: Use it in a table


CREATE TABLE Customers (
ID INT,
Name VARCHAR(50),
Contact PhoneNumber -- Using the custom type here
);

Important Notes:

• UDTs are stored in the sys.types catalog view.

• You can drop a UDT using:

DROP TYPE PhoneNumber;

• UDTs can’t be created with complex logic (like constraints or validations); they
only wrap existing data types.

Example Use Cases:

• EmailAddress → based on VARCHAR(100)

• ZipCode → based on CHAR(6)

• Price → based on DECIMAL(10, 2)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy