Posts

Showing posts with the label SQL Server Basics

Different method to Upgrade OS in Windows Cluster

When upgrading the operating system (OS) in a Windows cluster, there are a few methods you can consider. The appropriate method depends on the specific requirements, cluster configuration, and the available resources. Here are some common approaches: In-place upgrade : This method involves directly upgrading the existing OS on each node of the cluster. It can be suitable when the cluster nodes are capable of supporting the target OS version and when preserving applications, data, and configurations is a priority. To perform an in-place upgrade, follow the official documentation from Microsoft, which provides detailed instructions and considerations for each specific Windows version. Rolling upgrade : Similar to the rolling upgrade method described earlier, you can perform a rolling upgrade of the Windows cluster. In this case, you upgrade the OS on one node at a time while the other nodes continue to operate. By sequentially upgrading the nodes, you can maintain service availability th...

The Problems of Having Thousands of Databases on a Single Instance - SQL Server

Having thousands of databases on a single SQL Server instance can lead to several problems, including: Resource contention : Each database requires its own set of resources, such as memory, disk I/O, and CPU time. With thousands of databases, these resources can quickly become scarce and lead to performance problems. Maintenance challenges : Maintaining thousands of databases can be a daunting task, especially when it comes to tasks such as backups, restores, and monitoring. It can be difficult to keep track of which databases need maintenance and ensuring that all databases are properly maintained can become an overwhelming task. Security risks : With thousands of databases, it can be challenging to maintain proper security protocols. Each database may have its own set of users and permissions, making it difficult to manage access and enforce security policies across all databases. Increased risk of downtime : If one database experiences issues, it can potentially affect other databas...

Prefetching - SQL Server

Prefetching is a technique used by SQL Server to improve query performance by anticipating the data that will be needed for a query and reading it into memory in advance. This reduces the number of I/O operations required to fetch data from disk, which can significantly improve query performance. There are several mechanisms that SQL Server uses for prefetching, including: Read-Ahead : This mechanism anticipates the data pages that will be needed for a query and reads them from disk into memory in advance. This is based on a predictive algorithm that uses information from the query execution plan to determine which pages are likely to be needed. Pre-Fetching : This mechanism anticipates the related data that will be needed for a query and reads it from related tables into memory in advance. This is based on the relationships defined in the query and can significantly reduce the number of I/O operations required during query execution. Parallelism : SQL Server can use multiple threads ...

Lock and it types - SQL Server

In SQL Server, a " LOCK " is a mechanism used to ensure data consistency and prevent data corruption when multiple transactions access the same data concurrently. When a transaction needs to access a piece of data, it requests a lock on that data. If the data is already locked by another transaction, the requesting transaction may have to wait until the lock is released. There are several types of locks in SQL Server, including: Shared Lock : A shared lock allows multiple transactions to read the same data simultaneously, but it prevents any transaction from modifying the data until the lock is released. For example, when multiple transactions are reading from the same table, they acquire shared locks on the table to ensure that they don't interfere with each other. Exclusive Lock : An exclusive lock is acquired when a transaction needs to modify data, and it prevents any other transaction from reading or modifying the same data until the lock is released. For example, wh...

Checkpoint and its types - SQL Server

Checkpoint is a mechanism in SQL Server that writes all the modified pages from the buffer cache to disk. This process ensures that all the committed data is written to disk and the transaction log is truncated. In other words, a checkpoint is a point in time where the changes made to the database are permanently saved to disk. There are four types of checkpoints in SQL Server: Automatic Checkpoint : This is the default type of checkpoint in SQL Server, and it is triggered automatically by the server when certain conditions are met. These conditions include the size of the log file and the number of transactions. The frequency of automatic checkpoints can be configured in the database properties. Indirect Checkpoint : This type of checkpoint is similar to automatic checkpoint, but it is triggered by the checkpoint background task instead of by a user or application. Indirect checkpoint is designed to reduce the overhead of writing to the transaction log by spreading the checkpoint acti...

Isolation Level and its types in SQL Server

Isolation refers to the degree to which one transaction must be isolated from others. In SQL Server, there are four isolation levels, each providing a different degree of isolation. Here are the isolation levels and their examples: Read Uncommitted : This isolation level allows transactions to read uncommitted data, which can result in dirty reads. In other words, a transaction can read data that has been modified but not yet committed by another transaction. This level is not recommended for most applications. Read Committed : This isolation level guarantees that a transaction can only read committed data. A transaction will wait until another transaction has committed the data before it reads it. However, it is still possible to encounter non-repeatable reads and phantom reads. Repeatable Read : This isolation level guarantees that a transaction will always see the same data when it reads it, even if the data has been modified by another transaction. However, it is still possible to ...

Managing Virtual Log Files - SQL Server 2022

SQL Server's transaction log files are divided into smaller segments called Virtual Log Files (VLFs). Managing VLFs is an essential aspect of SQL Server administration. Here are some best practices for managing VLFs in SQL Server 2022: Monitor VLF fragmentation : Fragmentation of VLFs can occur due to multiple factors, including frequent log backups, auto-growth, and instant file initialization. Fragmented VLFs can cause slow transaction log backups and recovery time. You can use the DBCC LOGINFO command to check the VLF status. Control autogrowth settings : Automatic file growth can cause VLF fragmentation. Set appropriate values for autogrowth to avoid frequent VLF creations. It's recommended to set the growth rate to a fixed amount rather than a percentage. Regularly backup transaction log : Regular transaction log backups help prevent VLF fragmentation and maintain the transaction log size. A full backup doesn't truncate the transaction log, so it's necessary to tak...

Different Database States in SQL Server

In SQL Server, there are several database states that can help you understand the health and status of a database. Here are some of the different database states in SQL Server: Online : This is the normal state of a database when it's available and ready for use. When a database is online, users can connect to it, run queries and perform transactions. Offline : This state indicates that a database is not available for use. When a database is offline, it can't be accessed or modified. You can take a database offline using the SQL Server Management Studio or T-SQL scripts. Restoring : This state indicates that a database is currently undergoing a restore operation. When a database is being restored, it's not available for use until the restore process is complete. Recovering : This state indicates that a database is currently recovering from a failure, such as a crash or unexpected shutdown. During the recovery process, SQL Server is bringing the database to a consistent stat...

SQL Server Transaction Log Architecture

The SQL Server transaction log is a fundamental component of the database architecture that records all the modifications to the database. The transaction log ensures that the database can be restored to a consistent state after a system failure or user error. The transaction log is composed of a sequence of log records, each of which describes a single modification to the database. Each log record contains a Log Sequence Number (LSN) that uniquely identifies the record and its position in the log sequence. The transaction log is divided into Virtual Log Files (VLFs), which are fixed-size contiguous blocks of disk space that contain the log records. The size of the VLFs depends on the initial size of the log file and the autogrowth settings. One of the enhancements to the SQL Server transaction log is the Accelerated Database Recovery (ADR) feature, introduced in SQL Server 2019. ADR uses a more efficient and faster recovery mechanism that eliminates the need to roll back uncommitted ...

SQL Server Agent Jobs

SQL Server Agent Jobs are automated tasks that can be scheduled to run at specified intervals, such as daily, weekly, or monthly. They can be used to perform a variety of operations, such as database backups, data transfers, and maintenance tasks. Via GUI -  To create an SQL Server Agent Job using the GUI, follow these steps: Open SQL Server Management Studio (SSMS) and connect to the SQL Server instance. Expand the SQL Server Agent node and right-click on Jobs. Select New Job from the context menu to open the New Job window. In the General tab, enter a name and description for the job. In the Steps tab, add one or more steps to the job. Each step defines a specific task to be performed. In the Schedules tab, define the schedule for the job. You can choose from a variety of options, such as daily, weekly, or monthly. In the Notifications tab, configure the job to send an email notification when it completes or fails. Here's an example of an SQL Server Agent Job that performs a da...

Maintenance Plans - SQL Server

Maintenance Plans are a feature in SQL Server that allows you to automate common maintenance tasks, such as backups, index maintenance, and database integrity checks. By creating Maintenance Plans, you can save time and ensure that critical tasks are performed on a regular basis. Here's how to create and use Maintenance Plans in SQL Server: Create a new Maintenance Plan : To create a new Maintenance Plan, open SQL Server Management Studio and go to the "Management" node. Right-click on "Maintenance Plans" and select "New Maintenance Plan". This will open the Maintenance Plan Designer, which allows you to create and configure your plan. Add Maintenance Tasks : Once you've created a new Maintenance Plan, you can add maintenance tasks to it. This includes tasks such as backing up databases, rebuilding indexes, updating statistics, and checking database integrity. To add a task, drag it from the "Toolbox" pane and drop it onto the "Desig...

Database Mail - SQL Server

Database Mail is a feature in SQL Server that allows you to send email messages from the database engine. This can be useful for sending alerts and notifications, as well as reports and other information to users. Here's how to set up and use Database Mail in SQL Server: Enable Database Mail : Before you can use Database Mail, you need to enable it in SQL Server. This can be done using SQL Server Management Studio or by running a T-SQL script. To enable Database Mail, go to the "Management" node in SSMS, right-click on "Database Mail" and select "Configure Database Mail". Configure SMTP Server : To send email messages, you need to configure an SMTP server. This can be done in the "Configure Database Mail" wizard or by running a T-SQL script. You'll need to enter the server name, port number, and login credentials for the SMTP server. Create a Profile : In SQL Server, a profile is a collection of settings that define how email messages sho...

Synonyms - SQL Server

In SQL Server, a synonym is an alternative name for an object in the database. Synonyms are often used to simplify database schema management, improve query readability, or create a level of abstraction between the application and the database. Here are some of the key features and benefits of synonyms in SQL Server : Simplify database schema management : Synonyms allow you to create a logical name for an object that can be used instead of its physical name. This can simplify database schema management and make it easier to maintain the database over time. Improve query readability : Synonyms can make queries easier to read and understand, especially when working with complex database schemas that have long and complex object names. Create a level of abstraction : Synonyms can create a level of abstraction between the application and the database, making it easier to change the database schema without impacting the application code. Cross-database access : Synonyms can be used to acces...

Linked Server - SQL Server

A linked server is a SQL Server feature that enables you to connect to other database servers or data sources from within a SQL Server instance. Once you have created a linked server, you can execute distributed queries and transactions against the remote data source as if it were a local table in your database.  Here are the steps to create a linked server: Open SQL Server Management Studio and connect to the SQL Server instance where you want to create the linked server. In Object Explorer, expand the "Server Objects" node, right-click on the "Linked Servers" node, and select "New Linked Server". In the "New Linked Server" dialog box, enter a name for the linked server and select the data source type, such as SQL Server or Oracle. Enter the connection properties for the remote data source, such as the server name, database name, and authentication method. Configure the security options for the linked server, such as the login mappings and perm...

Execution Plan and its types - SQL Server

In SQL Server, an execution plan is a graphical representation of the query execution process that shows how the SQL Server query optimizer will execute a particular query. The execution plan can help database administrators and developers to understand how a query is being executed and to identify any performance issues. There are several types of execution plans in SQL Server, including: Estimated Execution Plan : An estimated execution plan is generated by the query optimizer without actually executing the query. It provides an estimate of the cost of the query execution and can help to identify potential performance issues before running the query. When generating an estimated execution plan, the query optimizer analyzes the query and creates a plan that is based on statistics about the data in the database. The estimated execution plan shows the operators that will be used to execute the query, the order in which they will be executed, and the estimated number of rows that will be...

SQL Server Profiler

SQL Server Profiler is a powerful tool for monitoring and analyzing SQL Server activity. Here are some additional details about its features and some recommendations for using it effectively: Event Capture : SQL Server Profiler can capture a wide variety of events related to SQL Server activity, including T-SQL statements, stored procedure calls, and database backups. However, capturing too many events can impact the performance of the SQL Server instance, so it's important to be selective about which events are captured. Recommendation : Start by capturing a small set of events that are relevant to the issue at hand. If necessary, add more events to the trace session as needed. Trace Filters : SQL Server Profiler allows users to filter events based on a variety of criteria, such as application name, database name, and user name. This can help to reduce the amount of data captured in the trace and focus on the events that are most relevant to the analysis. Recommendation : Use tra...

DBCC in SQL Server

Image
The Transact-SQL programming language provides DBCC statements that act as Database Console Commands for SQL Server. Database Console Command statements are grouped into the following categories. Maintenance : These commands perform maintenance tasks on a database, index, or filegroup. For example, the DBCC SHRINKFILE command can be used to reduce the size of a data file, while the DBCC INDEXDEFRAG command can be used to defragment an index. Miscellaneous : These commands perform miscellaneous tasks such as enabling trace flags or removing a DLL from memory. For example, the DBCC TRACEON command can be used to enable a specific trace flag, while the DBCC FREESYSTEMCACHE command can be used to clear the system cache. Informational : These commands gather and display various types of information. For example, the DBCC SQLPERF command can be used to display performance-related information for the SQL Server instance, while the DBCC SHOWCONTIG command can be used to display fragmentation i...

DMVs and DMFs in SQL Server

 Dynamic Management Views (DMVs) and Dynamic Management Functions (DMFs) are two important features in SQL Server that provide insight into the internal workings of the database engine. They are used to monitor the performance, health, and activity of the database, and provide valuable information that can be used to troubleshoot issues and optimize performance. Dynamic Management Views (DMVs) DMVs are special views that provide real-time information about the current state of a SQL Server instance. They are pre-built views that expose various aspects of the database engine, such as performance, activity, and health. DMVs can be queried just like any other view and they return a result set with information about the system. Some of the common uses of DMVs are: Monitoring performance: DMVs can be used to monitor the performance of the database and identify any performance bottlenecks. For example, the sys.dm_exec_requests DMV provides information about the currently executing requ...

Schema in SQL Server

A schema in SQL Server is a container for organizing and grouping database objects such as tables, views, stored procedures, and functions. Schemas provide a way to logically group objects together and control access to the objects within a schema. Each SQL Server database can have multiple schemas, and each schema can have multiple objects within it. By using schemas, you can improve the organization and management of your database objects, making it easier to understand the structure of your database and manage access to the objects within it. Here's an example of how you might create a schema in SQL Server : CREATE SCHEMA HumanResources This creates a new schema named HumanResources. You can then create tables and other objects within this schema: CREATE TABLE HumanResources.Employees (     EmployeeID INT PRIMARY KEY,     FirstName NVARCHAR(50),     LastName NVARCHAR(50),     HireDate DATE ) GO Now, you have a table named Employees within the H...

SQL Server Management Studio in Dark Theme.

Image
In SQL Server Management Studio 2016, Microsoft introduced a visual setting option to choose between the Blue and Light color theme. In SSMS 2016, SSMS 2017 and the latest SSMS 18, the user can switch between the Blue or Light theme by going to Tools | Options | Environment | General | Color theme : To achieve the same, we have to follow the below steps -  1. Search for ssms.pkgundef file under SSMS binaries. Below table for reference. SSMS Version Ssms.pkgundef File Location 16 C:\Program Files (x86)\Microsoft SQL Server\130\Tools\Binn\ManagementStudio 17 C:\Program Files (x86)\Microsoft SQL Server\140\Tools\Binn\ManagementStudio 18 C:\Program Files (x86)\Microsoft SQL Server Management Studio 18\Common7\IDE 2. Open the file  ssms.pkgundef  3. Scroll until you get to '// Remove Dark theme' 4. Add '//' to the beginning of the '[$RootKey$\Themes\{1ded0138-47ce-435e-84ef-9ec1f439b749}]' line to comment it out and save it. 5. Now open the SSMS and change the color ...