European Windows 2012 Hosting BLOG

BLOG about Windows 2012 Hosting and SQL 2012 Hosting - Dedicated to European Windows Hosting Customer

SQL Server Hosting - HostForLIFE :: SQL Server Data Types: Performance and Memory Efficiency

clock February 29, 2024 07:32 by author Peter

Choosing the right data types in SQL Server is critical for improving speed and properly managing memory resources. Developers can strike a balance between performance and memory utilization by taking data size, precision requirements, and indexing demands into account. In this post, we'll look at why it's important to choose the correct data types, as well as how caching and performance metrics can help with this decision.

Understanding Data Types

  • SQL Server offers a wide range of data types, each designed for specific data storage needs
  • Common numeric data types include int, decimal, and float, while character data types include varchar, nvarchar, and char
  • Understanding the characteristics and limitations of each data type is essential for making informed decisions

Performance Considerations:

  • Choosing data types with suitable storage sizes can have a substantial impact on query performance and execution durations
  • Narrower data types require less memory and disk space, which leads to faster data retrieval and lower storage costs
  • Avoiding unnecessary data type conversions and implicit conversions can help minimize performance bottlenecks and optimize query execution strategies

Memory Management and Caching

  • SQL Server uses memory caching to increase query performance by keeping frequently requested data in memory.
  • Data types with smaller storage capacities are cache-friendly because they enable for more data to be cached in memory.
  • Using data compression techniques and memory-optimized tables can help improve cache performance and reduce memory load.

Performance Metrics

  • Monitoring performance metrics such as CPU usage, memory consumption, and disk I/O is essential for identifying bottlenecks and optimizing data types.
  • Tools like SQL Server Profiler and Performance Monitor provide valuable insights into query performance and resource utilization.
  • Analyzing query execution plans and index usage statistics helps identify opportunities for optimizing data types and improving overall system performance.

Best Practices

  • Choose data types based on the size and precision needs of your data, aiming for the smallest storage capacity while maintaining accuracy.
  • Regularly examine and optimize data types to respond to changing workload patterns and performance requirements.
  • Test and benchmark various data formats in a controlled environment to determine their impact on performance and memory use.

Use Cases for Data Types

  • Integer vs. Decimal: Use int for whole numbers and decimal for precise numeric values, such as monetary amounts.
  • Varchar vs. Nvarchar: Use varchar for single-byte character data and nvarchar for Unicode character data supporting multiple languages.
  • Date vs. DateTime: Use date for date values only and datetime for date and time values.
  • Float vs. Decimal: Use a float for approximate numeric data and decimal for exact numeric values.
  • Char vs. Varchar: Use char for fixed-length character data and varchar for variable-length character data.
  • Text vs. Varchar(Max): Use varchar(max) for large variable-length character data and prefer it over text for new development.
  • Bit vs. Tinyint: Use bit for boolean values and tinyint for small integer values.

Conclusion
Selecting the appropriate data types in SQL Server is an important part of database design and optimization. Optimal query performance and resource utilization can be achieved by taking into account parameters like as throughput, memory usage, and cache effectiveness. Organizations may maintain a high-performing and scalable database infrastructure by continuously monitoring performance metrics and following best practices.

HostForLIFE.eu SQL Server 2022 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

 



SQL Server Hosting - HostForLIFE :: Tips to Launch Your SQL Mission

clock February 21, 2024 08:48 by author Peter

SQL (Structured Query Language) is the foundation of database management, allowing seamless interaction with databases to extract, manipulate, and analyze data.  As businesses around the world increase their reliance on data-driven insights,  SQL skills are proving to be an essential skill  across a variety of industries and roles.

Navigating Your SQL Journey

  • Basic Understanding: Start your SQL journey by learning fundamental concepts such as database architecture, SQL syntax, and basic query techniques. Use online resources like SQLZoo and Codecademy to deepen your understanding.
  • Practical Exercises: Get head-first into practical exercises and real-world scenarios to improve your SQL skills.Use platforms like HackerRank to conquer coding challenges and hone your problem-solving skills.
  • Interactive Learning Platforms: Explore interactive learning platforms like DataCamp and Coursera that offer structured SQL courses hand-picked by industry experts. Deepen your understanding of complex SQL concepts with guided tutorials and hands-on projects.
  • Take advantage of project-based learning: Improve your SQL skills by completing hands-on projects that reflect real-world scenarios. Build databases, design schemas, and run complex queries to analyze datasets and derive actionable insights.
  • Community Participation: Harness the power of community participation by participating in  online forums, SQL user groups, and virtual meetups.
  • Collaborate with colleagues, seek mentors, and share knowledge to foster continuous growth and learning.

Conclusion
When you embark on your mission to master SQL, you begin an exciting journey filled with endless possibilities and innovative learning experiences. By applying the strategies and tips described in this guide, you will have the tools and knowledge needed to navigate complex SQL environments and realize the  potential of data-driven decision-making.  You can attach it. Remember to be curious, persistent, and open-minded when starting your SQL mission. Your journey to mastering SQL has just begun.

HostForLIFE.eu SQL Server 2022 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.



SQL Server Hosting - HostForLIFE :: What Distinguishes UNION from UNION All (SQL Server)?

clock February 13, 2024 06:18 by author Peter

While UNION ALL combines them without removing duplicates, yielding faster results but keeping all rows, including duplicates, UNION merges and filters out duplicates from different SELECT queries.

Now let's look at the example.

I have started by making two tables, Employee and Employee_One.

CREATE TABLE Employee
(
 employeeId INT IDENTITY(1,1) PRIMARY KEY,
 employeeName VARCHAR(50),
 City VARCHAR(100)
)

The Employee table has records as follows.

CREATE TABLE Employee_One
(
 employeeId INT IDENTITY(1,1) PRIMARY KEY,
 employeeName VARCHAR(50),
 City VARCHAR(100)
)


The Employee_One table has records as follows.

Let's explore how the UNION operation works.

SELECT City
FROM Employee
UNION
SELECT City FROM Employee_One

Employee table records

Employee_One table records

After using UNION between these two tables, we will get results as follows (removing duplicates).

In conclusion, the UNION function in SQL Server automatically eliminates duplicate rows while combining the output of several SELECT queries to create a single, cohesive result set. Let's examine the operation of UNION ALL.

SELECT City

FROM Employee

UNION ALL

SELECT City

Employee_One

Employee table records

Employee_One table records

Employee_One table records

After using UNION ALL between these two tables, we will get results as follows (including all records - without removing duplicate records).
UNION ALL

In summary
In SQL Server, the UNION ALL method is used to aggregate the output of several SELECT queries without removing duplicate rows. Because duplicate elimination processing is not present in UNION, UNION ALL offers faster performance than UNION and contains all records from the combined queries, making it a good option when maintaining duplicate entries is required.

I hope this post has given you useful knowledge on using UNION and UNION ALL in SQL Server. Best wishes for the future.

HostForLIFE.eu SQL Server 2022 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.


 



SQL Server Hosting - HostForLIFE :: Select 1 from Table (SQL Server)

clock February 6, 2024 06:51 by author Peter

One easy method to see if the given MySQL table has any rows is to run "SELECT 1 FROM TABLE". Rather than extracting any information from the table, it provides a result set that has a single column with the value 1 for each row that meets the requirements in the WHERE clause (if any).

Now let's look at an example.

First Step
I am going to make an Employee table.
CREATE TABLE Employee
(
employeeId INT IDENTITY(1,1) PRIMARY KEY,
employeeName VARCHAR(50)
)

Then Inserting Some values in that Employee table.
INSERT INTO Employee (employeeName)
VALUES('Johnson'),('Richard'), ('Willam'),('John')


After inserting the value, the result will be as follows:

Step 2
Execute the following Query without the WHERE Clause.
SELECT 1 FROM Employee

Output Message: (4 rows affected)

Result



Now Exceute with WHERE Clause.
SELECT 1 FROM Employee WHERE employeeName LIKE 'John%'

Output Message: (2 rows affected)

Result

I hope this blog has helped you to better grasp how to use SQL Server's SELECT 1 From the table function. Wishing you luck.

HostForLIFE.eu SQL Server 2022 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

 



SQL Server Hosting - HostForLIFE :: Run MS SQL Server on Docker

clock January 25, 2024 07:03 by author Peter

I've made the decision to investigate and experiment with the docker. I therefore considered learning and imparting knowledge to others while I was doing it. Thus, I installed Docker on Windows 11 and used it to run the MS SQL server in this article.

Requirements

A laptop with at least 8 GB of RAM
Set up the docker
MS SQL Server Management Studio
After successfully installing the docker you need to sign into the Docker Hub. https://hub.docker.com/
Before you move to the next step, you need to learn some basics about Docker & the norms and nuances used in it.

What is Docker?
"Docker is an open platform for developing, shipping, and running applications," according to the Docker documentation. Docker allows you to rapidly release software by separating your apps from your infrastructure. You can use Docker to manage your infrastructure in the same manner that you do your apps. You may cut down on the amount of time it takes between writing code and having it run in production by utilizing Docker's shipping, testing, and deployment processes."

We can run the applications without caring about the underlying environment thanks to Docker. Since we can use that in the Docker application, we'll include all dependencies and necessary files in the container.

You've been curious about what a container is
Code can be executed in an isolated environment using a container. In other words, the container operates in the context where Docker Desktop is available, without any knowledge of the underlying operating system or files.

Docker Hub
It's a registry for Docker images hosted in the cloud. Users may share, search, and control Docker images with it. For developers wishing to create and launch apps using Docker, Docker Hub is a well-liked option.

Ok, done with our theory. Let's dive into the hands-on.

How to Run MS SQL Server on Docker

We need to find the MSSQL Server image that runs on the Ubuntu. https://hub.docker.com/_/microsoft-mssql-server

As I previously stated, the MSSQL Server is operating on Ubuntu, but my base environment is Windows 11. The photograph is available at the aforementioned URL. The command on the page to the command prompt must be used.

docker pull mcr.microsoft.com/mssql/server:2022-latest

You'll face the error when the Docker Deamon is not running.

Otherwise, it'll look like this.

Use the command, to show the images available
docker images

You can also see the same image on the Docker Desktop too.

Now, you need to install the MSSQL Image on the Docker using the below command
docker run -e "ACCEPT_EULA=Y" -e "MSSQL_SA_PASSWORD=<StrongPassword>" -p 1433:1433 --name sql1 --hostname sql1 -d  mcr.microsoft.com/mssql/server:2022-latest

You need to set the ACCEPT_EULA variable to Y to accept the end user license agreement and the SA_PASSWORD variable to a strong password for the system administrator account. After the successful login, you can able to see the container running in the Docker Desktop

You must launch the MS SQL Server Management Studio and fill in the fields displayed in the screenshot in order to access the SQL Server.


Both the password and the username, SA, must be entered. Once your authentication has been successful, you can query the system databases.

That's all I have for now; in the next post, I'll demonstrate how to link this database to the.NET applications. Please let me know if you have any problems completing the aforementioned tasks.

HostForLIFE.eu SQL Server 2022 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.


 

 



SQL Server Hosting - HostForLIFE :: Determine the Source of SQL Server Issues

clock January 12, 2024 07:54 by author Peter

Tracking down problems in SQL Server entails diagnosing and resolving issues at their core. These are some general actions that you can take.
Examine the error logs.

SQL Server keeps error logs, which are a useful source of information concerning problems. Look for any error messages in the Windows Event Viewer and the SQL Server Error Log.

Open SQL Server Management Studio (SSMS).

  • Link to the instance of SQL Server.
  • In the Object Explorer, expand "Management".
  • Select "View SQL Server Log" with a right-click on "SQL Server Logs."
  • Check for any warnings or error messages.

Event Viewer for Windows

  • Check the Windows Event Viewer for system and application logs.
  • Keep an eye out for any occurrences connected to database or SQL Server problems.

Make use of SQL Server Management Studio (SSMS)
To check for defects or performance problems, use SSMS to connect to the SQL Server instance and run queries. Look for any error warnings in the output.

  • Query Execution Plans: Use the "Execution Plan" feature in SSMS to analyze the execution plan of a query. This can help identify performance bottlenecks and suggest improvements.
  • Profiler Traces: SQL Server Profiler allows you to capture and analyze events as they occur in real-time. Tracing can help identify slow queries or other issues.

Dynamic Management Views (DMVs) and Dynamic Management Functions (DMFs)
A collection of DMVs and DMFs offered by SQL Server provide information about resource utilization, server performance, and other metrics. Sys.dm_exec_sessions, sys.dm_exec_requests, and sys.dm_os_wait_stats are a few examples.

Check Disk Space
Transaction failures or problems with performance can result from insufficient disk space. Make sure the drives holding SQL Server's data, log files, and backups have adequate room.

Review SQL Server Configuration
Check that the setup parameters for the server and database are in line with industry best practices. Keep an eye on memory, parallelism, and other performance-related configuration parameters.

Indexing

Index omissions or poor design might affect query performance. To find missing indexes, examine execution plans or use the Database Engine Tuning Advisor.

Monitor Blocking and Deadlocks
Use tools like SQL Server Profiler, Extended Events, or queries against system views (sys.dm_tran_locks, sys.dm_os_waiting_tasks) to discover and fix blocking and deadlock issues.

Review Application Code
There are instances when the application code may be the problem. Make that the SQL queries running are optimized by reviewing them. Aim for parameterization and steer clear of pointless database round trips.

Security Auditing
Ensure that security policies are correctly implemented and that there are no unauthorized accesses or security vulnerabilities.

Regular Maintenance
Carry out routine database maintenance, including statistics updates, index rebuilds, and consistency checks.

Keep in mind that the precise steps you take to identify problems may change based on the type of situation you are dealing with. It frequently involves looking into logs, examining query results, and figuring out how well the system is functioning as a whole.

HostForLIFE.eu SQL Server 2022 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

 



SQL Server Hosting - HostForLIFE :: Enhancing SQL Query Performance: CTE vs. Temporary Tables

clock December 18, 2023 06:05 by author Peter

Improving the effectiveness of queries is crucial for database optimization. Common Table Expressions (CTE) and temporary tables are two alternative ways that Microsoft SQL Server can improve query performance. But the question remains: which tactic works better in terms of efficiency and speed?

Frequently Used Table Terms (CTE)

Creating temporary result sets inside of a query is made easy and clear with the help of CTEs. By dividing intricate reasoning into smaller, easier-to-understand components, they improve query readability. CTEs can be referenced more than once and are defined within the query scope, which minimizes redundancy and enhances maintainability.

This is an example CTE query:
WITH CTE_Sales AS (
    SELECT ProductID, SUM(Quantity) AS TotalSales
    FROM Sales
    GROUP BY ProductID
)
SELECT P.ProductName, S.TotalSales
FROM Products P
JOIN CTE_Sales S ON P.ProductID = S.ProductID;


In this example, CTE_Sales calculates the total sales per product, which is later joined with the Products table.

Temporary Tables
Conversely, temporary tables are made physically inside the tempdb database. They hold temporary outcomes and continue until the session is over unless they are specifically removed. Although creating temporary tables requires more resource allocation and I/O cost, there are occasions where doing so improves speed, particularly for larger datasets or more complicated procedures.

Think about the following case with temporary tables:
CREATE TABLE #TempSales (
    ProductID INT,
    TotalSales INT
);

INSERT INTO #TempSales (ProductID, TotalSales)
SELECT ProductID, SUM(Quantity) AS TotalSales
FROM Sales
GROUP BY ProductID;

SELECT P.ProductName, TS.TotalSales
FROM Products P
JOIN #TempSales TS ON P.ProductID = TS.ProductID;

DROP TABLE #TempSales;


Here, #TempSales is created to hold the total sales per product before being joined with the Products table.

Comparing Speeds
Variations exist in the performance of CTEs and temporary tables due to variables such as query complexity, indexing, and dataset size. Because CTEs are in-memory and have minimal I/O cost, they often provide equivalent or occasionally higher performance in circumstances involving smaller datasets or simpler processes.

However, temporary tables may perform better than CTEs for larger datasets or more intricate tasks requiring several steps. Indexing can help temporary tables by enabling more efficient joins and quicker data retrieval.

In summary
Depending on a number of variables, one must decide whether to optimize query time using temporary tables or CTEs. Temporary tables excel at managing larger datasets and complex procedures, particularly when indexing and multi-step computations are involved. CTEs improve readability and are useful for simpler tasks.

In the end, experimenting, profiling, and taking into account the particular context of the query and database structure are frequently necessary for query performance optimization. Producing effective SQL queries in Microsoft SQL Server requires striking a balance between readability, maintainability, and efficiency.

Recall that there are two types of tools in the SQL optimization toolbox: temporary tables and CTEs. The best tool to use will depend on the particular needs of the task at hand.

HostForLIFE.eu SQL Server 2022 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.



SQL Server Hosting - HostForLIFE :: Most Common MS SQL Server SQL Queries

clock December 11, 2023 07:15 by author Peter

Overview
Microsoft SQL Server is a well-known and potent relational database solution in the field of database management. During their exploration of the complex world of SQL, developers and database administrators often find themselves returning to the same questions in both interviews and practical situations.

We'll explore the most commonly asked SQL questions for MS SQL Server in this blog, offering tips and code samples to help novices and experts alike.

Retrieving Data. The SELECT Statement
The foundation of any database interaction lies in retrieving data. The SELECT statement is your go-to tool for this task.
-- Retrieve all columns from a table
SELECT * FROM TableName;

-- Retrieve specific columns
SELECT Column1, Column2 FROM TableName;

-- Filter data with WHERE clause
SELECT * FROM TableName WHERE Condition;


Filtering and Sorting Data
Refining data based on conditions and sorting results is a common requirement.
-- Filtering with WHERE
SELECT * FROM TableName WHERE Column = 'Value';

-- Sorting with ORDER BY
SELECT * FROM TableName ORDER BY Column ASC/DESC;


Aggregating Data. GROUP BY and Aggregate Functions
Aggregating data provides valuable insights into summaries and statistics.
-- Grouping data with GROUP BY
SELECT Column, COUNT(*)
FROM TableName
GROUP BY Column;

-- Using Aggregate Functions
SELECT AVG(Column), SUM(Column), MAX(Column)
FROM TableName
WHERE Condition;


Joining Tables. INNER JOIN, LEFT JOIN
When data resides in multiple tables, joining becomes essential.
-- Inner Join
SELECT *
FROM Table1
INNER JOIN Table2 ON Table1.ID = Table2.ID;

-- Left Join
SELECT *
FROM Table1
LEFT JOIN Table2 ON Table1.ID = Table2.ID;


Subqueries. Nesting Queries for Precision
Subqueries enable embedding one query within another, offering precision and flexibility.
-- Using Subqueries
SELECT *
FROM TableName
WHERE Column IN (SELECT Column FROM AnotherTable WHERE Condition);


Modifying Data. UPDATE and DELETE Statements
Ensuring data accuracy involves updating and deleting records.
-- Update Statement
UPDATE TableName SET Column = 'NewValue' WHERE Condition;

-- Delete Statement
DELETE FROM TableName WHERE Condition;


Transaction Control. BEGIN, COMMIT, ROLLBACK
Transactions maintain data integrity by grouping operations.
-- Begin Transaction
BEGIN TRANSACTION;

-- Commit Transaction
COMMIT;

-- Rollback Transaction
ROLLBACK;


Working with Dates. Date Functions
Manipulating dates is a common task, and SQL Server provides robust date functions.
-- Get Current Date
SELECT GETDATE();

-- Extract Part of a Date
SELECT YEAR(DateColumn), MONTH(DateColumn), DAY(DateColumn);


Common Table Expressions (CTEs). Enhancing Readability
CTEs simplify complex queries and enhance code readability.
-- Using CTE
WITH MyCTE AS (
    SELECT Column FROM TableName WHERE Condition
)
SELECT * FROM MyCTE;


Window Functions. Analytical Insights
Window functions offer advanced analytical capabilities.
-- Using Window Function
SELECT Column, ROW_NUMBER() OVER (ORDER BY Column) AS RowNum
FROM TableName;


These SQL queries encapsulate the essence of database interactions and form the backbone of database-related interviews and projects. Mastering these queries empowers professionals to navigate diverse scenarios efficiently.
Conclusion

The world of SQL Server queries is vast, and continuous learning is key.

As you embark on your SQL journey, these fundamental queries will serve as the stepping stones to deeper insights and mastery. Happy querying!

HostForLIFE.eu SQL Server 2022 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.


 



SQL Server Hosting - HostForLIFE :: In SQL Server, How Can I obtain Every Job for an Agent?

clock December 6, 2023 06:59 by author Peter

How to Acquire Every SQL An essential part of Microsoft SQL Server is SQL Server Agent, which lets database administrators utilize jobs to automate a variety of processes like data processing, backup, and maintenance. You can arrange for these jobs to execute at predetermined times, which will simplify the management and upkeep of your SQL Server system. This post will demonstrate how to use SQL Server Management Studio (SSMS) to get a list of all SQL Server Agent jobs.

Finding Jobs for SQL Server Agents

To obtain a list of every SQL Server Agent job in SSMS, take the following actions:

Step 1: Establish a connection with SQL ServerWorks with Server Agents?
To access your SQL Server instance, open SQL Server Management Studio.

Step 2: Launch the SQL Server Agent
Open SSMS and select the "Object Explorer" window from the menu on the left. The "SQL Server Agent" node can be seen by expanding the server node. Click "SQL Server Agent" with a right-click, then choose "Jobs."

Step 3. View Job List
Once you've selected "Jobs," the right-hand pane will display a list of all the SQL Server Agent jobs configured on the SQL Server instance. The list includes the following columns:
    Job ID
    Job Name
    Owner
    Enabled (whether the job is currently enabled or not)
    Last Run Date
    Next Run Date
    Last Run Outcome

You can see an overview of the jobs, their statuses, and when they were last run, making it easier to manage your SQL Server Agent jobs.

Step 4: Job Specifics
To see additional information about a particular job, right-click on the job name and choose "Properties." This will cause a new window to open, displaying a plethora of job-related information such as the timetable, steps, and notifications.
Using Query, Retrieve SQL Server Agent Jobs

The msdb database contains information on SQL Server Agent jobs. SQL queries can be used to obtain job details, their steps, and other pertinent data. The two main tables that we will be utilizing are sysjobs and sysjobsteps. This is an extensive SQL query that retrieves different information on SQL Server Agent jobs.

SELECT
    [sJOB].[job_id] AS [JobID]
    , [sJOB].[name] AS [JobName],
    case when d.name is null then 'No Schedule' else d.name end Schedule,
isnull (case d.freq_type
when '1 ' then 'Once'
when '4' then 'Daily'
when '8' then 'Weekly'
when '16' then 'Monthly'
when '32' then 'Monthly relative'
when '64' then 'When SQL Server Agent starts' end, 'None') as Frequency,
     CASE
        WHEN [sJOBH].[run_date] IS NULL OR [sJOBH].[run_time] IS NULL THEN NULL
        ELSE CAST(
                CAST([sJOBH].[run_date] AS CHAR(8))
                + ' '
                + STUFF(
                    STUFF(RIGHT('000000' + CAST([sJOBH].[run_time] AS VARCHAR(6)),  6)
                        , 3, 0, ':')
                    , 6, 0, ':')
                AS DATETIME)
      END AS [LastRunDateTime]
    , CASE [sJOBH].[run_status]
        WHEN 0 THEN 'Failed'
        WHEN 1 THEN 'Succeeded'
        WHEN 2 THEN 'Retry'
        WHEN 3 THEN 'Canceled'
        WHEN 4 THEN 'Running' -- In Progress
      END AS [LastRunStatus]
    , STUFF(
            STUFF(RIGHT('000000' + CAST([sJOBH].[run_duration] AS VARCHAR(6)),  6)
                , 3, 0, ':')
            , 6, 0, ':')
        AS [LastRunDuration]
    , [sJOBH].[message] AS [LastRunStatusMessage]
    , CASE [sJOBSCH].[NextRunDate]
        WHEN 0 THEN NULL
        ELSE CAST(
                CAST([sJOBSCH].[NextRunDate] AS CHAR(8))
                + ' '
                + STUFF(
                    STUFF(RIGHT('000000' + CAST([sJOBSCH].[NextRunTime] AS VARCHAR(6)),  6)
                        , 3, 0, ':')
                    , 6, 0, ':')
                AS DATETIME)
      END AS [NextRunDateTime],
      isnull (convert (varchar,d.Date_Created), 'None') CreatedDate
FROM
    [msdb].[dbo].[sysjobs] AS [sJOB]

    LEFT JOIN (
                SELECT
                    [job_id]
                    , MIN([next_run_date]) AS [NextRunDate]
                    , MIN([next_run_time]) AS [NextRunTime]
                FROM [msdb].[dbo].[sysjobschedules]
                GROUP BY [job_id]
            ) AS [sJOBSCH]
        ON [sJOB].[job_id] = [sJOBSCH].[job_id]
    LEFT JOIN (
                SELECT
                    [job_id]
                    , [run_date]
                    , [run_time]
                    , [run_status]
                    , [run_duration]
                    , [message]
                    , ROW_NUMBER() OVER (
                                            PARTITION BY [job_id]
                                            ORDER BY [run_date] DESC, [run_time] DESC
                      ) AS RowNumber
                FROM [msdb].[dbo].[sysjobhistory]
                WHERE [step_id] = 0
            ) AS [sJOBH]
        ON [sJOB].[job_id] = [sJOBH].[job_id]
        AND [sJOBH].[RowNumber] = 1
        left outer join msdb.dbo.sysjobschedules e on e.job_id = [sJOB].job_id
        left outer join msdb.dbo.sysschedules d on e.schedule_id = d.schedule_id


The msdb.dbo.sysjobs table contains information about SQL Server Agent jobs.
The msdb.dbo.sysjobsteps table contains information about the steps within those jobs.
We use the inner join clause to link the two tables based on the job_id column.

In summary
Monitoring and controlling automated processes in a SQL Server environment requires retrieving information about SQL Server Agent jobs. With the SQL query that is provided, you may get comprehensive details on jobs and the steps that go along with them. Database administrators can maintain the functionality and health of their SQL Server instances by routinely accessing and evaluating this data. Furthermore, by utilizing this data, job-related problems can be resolved and work schedules can be optimized for increased productivity.

HostForLIFE.eu SQL Server 2022 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.



SQL Server Hosting - HostForLIFE :: What exactly is logical read in SQL?

clock December 1, 2023 07:04 by author Peter

SQL logical read
When the query engine needs to access data, it performs a logical read. It first verifies SQL Server's in-memory storage. If the relevant page is already present in SQL Server's memory, it is used. If the data page is not discovered in memory, a physical read is initiated, which results in the retrieval of the data page from the disk. A "cache hit" is a logical read without a following physical read.

For query resolution, the buffer cache, also known as the buffer pool, acts as SQL Server's primary working memory. The amount of RAM allocated to SQL Server has a direct impact on the size of the accessible buffer cache.

It is nearly impossible to provide particular recommendations without first reviewing the query, comprehending the table content, data structure, and indexing.

While a large number of logical readings is not necessarily harmful, an excessive number of logical reads is. For example, if a query returns only three rows of data but requires scanning through 200 million rows of data, the process becomes inefficient and can be improved by query optimization or the insertion of an appropriate index.

Example of a query

select *
from
(
  select *
  from Employees
  where empId = 9
)
where deptId = 1;

You can combine both criteria in a single step to improve the query and reduce logical reads. Rather of selecting all employees with empid 9 and then filtering for deptid 1, you may combine both requirements in the initial SELECT statement. This method seeks to reduce the size of the intermediate result set while increasing query efficiency.

Here's an example of how you might change the query:

SELECT *
FROM employees
WHERE empid = 9 AND deptid = 1;

When both conditions are combined in a single WHERE clause, the query engine is more likely to execute a more efficient execution plan, potentially resulting in fewer logical reads than in the two-step procedure. The efficiency of this optimization, however, is dependent on the specific database schema, indexes, and SQL Server's query optimizer.

HostForLIFE.eu SQL Server 2022 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in