European Windows 2012 Hosting BLOG

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

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