Sqlnotes Updated
Sqlnotes Updated
• Limitations:
• Free for development and testing purposes only (not for production use).
o Advanced analytics
o Full-text search
1. Windows Authentication
• 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.
• Used when:
Example: When accessing a remote SQL Server from another server using a defined
SQL login like username: sa.
Summary Table
Password
Managed by Windows Managed by SQL Server
management
Database Description
1. MASTER Database
Purpose:
What it stores:
• Initialization information
Important Facts:
Example Use:
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:
• Default values
Example:
If you want to get information about a table named Employees, you would use:
It’s a useful command for quickly understanding the structure and properties of
database objects.
2. MODEL Database
Purpose:
What it stores:
• 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:
3. MSDB Database
Purpose:
o Jobs
o Alerts
o Schedules
o Operators
o Maintenance plans
Key Features:
Example Query:
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.
o It's the default schema for users who are owners of the database.
Example Breakdown:
• dbo = schema.
This means: select everything from the sysjobhistory table in the dbo schema of the
msdb database.
Key Points:
• You can create your own schemas too, e.g., CREATE SCHEMA hr;
Would you like a list of other common schemas in SQL Server and their uses?
4. TEMPDB Database
Purpose:
Used for:
Key Properties:
• Performance-critical database
Example Use:
Purpose:
o System views
o System functions
Key Points:
Best Practices
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
Recommended (Modern):
Deprecated:
To revert:
Recommended:
To revert to multi-user:
ALTER DATABASE Students
SET MULTI_USER;
Important Notes:
DDL (Data Definition Language) is used to define, modify, or delete the structure of
database objects like:
• Tables
• Schemas
• Views
• Indexes
Example:
Modify a Column:
Purpose:
ALTER is used to modify the structure of an existing database object like a table. You
can:
• Delete columns
• Add constraints
• Drop constraints
7. Drop a Constraint
Would you like multiple-choice questions (MCQs) or a PDF based on these ALTER table
examples?
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:
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:
This will completely delete the SchoolDB database, including all tables, views, stored
procedures, and data within it.
3. Drop a View
Example 3:
This will delete the StudentView view, but the underlying table will not be affected.
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:
This removes the Age column from the Students table. It’s part of ALTER command
rather than DROP.
5. Drop a Constraint
Example 4:
This will drop the primary key constraint on the StudentID column, but the table and
its data remain intact.
• It is a permanent operation.
• It doesn’t just remove data, it removes the entire object structure (e.g., table
schema).
Purpose: Used to permanently remove a table or other object. Data and structure both
will be lost.
Example:
Warning: This cannot be rolled back. All data and table structure is deleted.
Example:
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.
Table Yes, removes the table No, the structure No, the structure
Structure structure. remains intact. remains intact.
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:
Behavior:
• Deletes the entire table including both the data and the table structure.
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:
Behavior:
• 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:
• Faster than DELETE as it doesn’t log individual row deletions, but the table’s
metadata is updated.
Quick Comparison:
Data Yes, removes both data Removes data only Removes all data but keeps
Removal and structure (with WHERE clause) structure
No (unless in a
Rollback Yes (if not committed) No (unless in a transaction)
transaction)
• 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.
Example 1: INSERT
This command inserts a new student record into the Students table.
Example 2: UPDATE
UPDATE Students
SET Age = 23
WHERE StudentID = 101;
This command updates the Age of the student with StudentID = 101 to 23.
Example 3: DELETE
This command deletes the record of the student with StudentID = 101.
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.
Purpose:
DQL is used for querying and retrieving data from the database. It consists mainly of the
SELECT statement.
Example 1: SELECT
This retrieves the Name and Age of all students in the Students table.
Example 2: SELECT with WHERE Clause
This retrieves the Name and Age of students whose age is greater than 20.
This calculates the average Age of all students in the Students table.
This retrieves the names of students and the courses they are enrolled in by joining
Students, Enrollments, and Courses.
Purpose:
DCL is used to control access to data within the database. It involves granting and
revoking permissions on tables and other objects.
Example 1: GRANT
This grants User1 permission to SELECT, INSERT, and UPDATE data in the Students
table.
Example 2: REVOKE
This revokes the UPDATE permission on the Students table from User1.
Grants permissions along with the ability to grant those permissions to others.
This grants User1 SELECT permissions on the Students table and allows User1 to grant
SELECT permissions to others.
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.
Example 1: COMMIT
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
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).
This sets the transaction isolation level to SERIALIZABLE, ensuring the transaction is
fully isolated from other transactions.
Summary
• DQL (Data Query Language): Retrieves data from the database (SELECT).
These data types store numeric values, both integers and decimals.
• INT:
o Storage: 4 bytes.
• BIGINT:
o Description: Stores large whole numbers.
o Storage: 8 bytes.
• SMALLINT:
o Storage: 2 bytes.
• TINYINT:
o Range: 0 to 255.
o Storage: 1 byte.
• DECIMAL(p,s) or NUMERIC(p,s):
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:
• REAL:
o Storage: 4 bytes.
• DATE:
o Description: Stores only the date part (year, month, day).
o Storage: 3 bytes.
• TIME:
o Storage: 5 bytes.
• DATETIME:
o Storage: 8 bytes.
• DATETIME2:
• SMALLDATETIME:
o Description: Stores date and time with less precision than DATETIME.
o Storage: 4 bytes.
• DATETIMEOFFSET:
o Storage: 10 bytes.
• CHAR(n):
• VARCHAR(n):
• TEXT:
• NCHAR(n):
• NVARCHAR(n):
• NTEXT:
• BINARY(n):
• VARBINARY(n):
o Description: Stores variable-length binary data.
• IMAGE:
o Storage: Up to 2 GB.
• BIT:
o Storage: 1 byte.
• UNIQUEIDENTIFIER:
o Storage: 16 bytes.
• MONEY:
o Storage: 8 bytes.
• SMALLMONEY:
o Storage: 4 bytes.
• SQL_VARIANT: Can store any data type, except TEXT, NTEXT, and IMAGE.
o Storage: Varies based on the stored value.
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.
add
drop
sp_droptype city
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.
• Abstraction: Hides underlying system data type and constraints from the user.
Syntax to Create a User-Defined Data Type:
Note: This works in older versions of SQL Server. In modern versions, use CREATE
TYPE.
Important Notes:
• UDTs can’t be created with complex logic (like constraints or validations); they
only wrap existing data types.