Ahmed S, Author at Tech Insights https://reactconf.org/author/ahmed-s/ Unveiling Tomorrow's Tech Today, Where Innovation Meets Insight Tue, 19 Dec 2023 05:34:58 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.1 https://i0.wp.com/reactconf.org/wp-content/uploads/2023/11/cropped-reactconf.png?fit=32%2C32&ssl=1 Ahmed S, Author at Tech Insights https://reactconf.org/author/ahmed-s/ 32 32 230003556 How to Get the size of all Tables in a Database https://reactconf.org/sql-server-get-size-of-all-tables-in-a-database/ https://reactconf.org/sql-server-get-size-of-all-tables-in-a-database/#respond Tue, 19 Dec 2023 05:34:58 +0000 http://www.sqlneed.com/?p=534 In this guide, we will learn How to Get the size of all Tables in a Database using SQL Server. There are multiple ways, let’s take a look at them …

The post How to Get the size of all Tables in a Database appeared first on Tech Insights.

]]>
In this guide, we will learn How to Get the size of all Tables in a Database using SQL Server. There are multiple ways, let’s take a look at them one by one.

#Solution-1: SQL Query

The query joins information from the system catalog views such as “sys.tables”, “sys.indexes”, ”sys.partitions”, and “sys.allocation_units” to calculate the size of each table in KB(kilobytes) and as well as MB(megabytes).

It provides a detailed overview of all tables in the specified database, including the table name row count, total size, used size, and unused side. The results are ordered by total size in descending order, so you can easily identify the largest tables.

SELECT 
    t.name AS TableName,
    s.name AS SchemaName,
    p.rows,
    SUM(a.total_pages) * 8 AS TotalSpaceInKB, 
    CAST(ROUND(((SUM(a.total_pages) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS TotalSpaceInMB,
    SUM(a.used_pages) * 8 AS UsedSpaceKB, 
    CAST(ROUND(((SUM(a.used_pages) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS UsedSpaceInMB, 
    (SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceInKB,
    CAST(ROUND(((SUM(a.total_pages) - SUM(a.used_pages)) * 8) / 1024.00, 2) AS NUMERIC(36, 2)) AS UnusedSpaceInMB
FROM 
    sys.tables t
INNER JOIN      
    sys.indexes i ON t.object_id = i.object_id
INNER JOIN 
    sys.partitions p ON i.object_id = p.object_id AND i.index_id = p.index_id
INNER JOIN 
    sys.allocation_units a ON p.partition_id = a.container_id
LEFT OUTER JOIN 
    sys.schemas s ON t.schema_id = s.schema_id
WHERE 
    t.name NOT LIKE 'dt%' 
    AND t.is_ms_shipped = 0
    AND i.object_id > 255 
GROUP BY 
    t.name, s.name, p.rows
ORDER BY 
    TotalSpaceInMB DESC, t.name;

Results:

How to Get size of all Tables in a Database

#Solution-2:CTE Query

with CTE as (  
  SELECT  
  t.name as TableName,  
  SUM (s.used_page_count) as used_pages_count,  
  SUM (CASE  
              WHEN (i.index_id < 2) THEN (in_row_data_page_count + lob_used_page_count + row_overflow_used_page_count)  
              ELSE lob_used_page_count + row_overflow_used_page_count  
          END) as pages  
  FROM sys.dm_db_partition_stats  AS s   
  JOIN sys.tables AS t ON s.object_id = t.object_id  
  JOIN sys.indexes AS i ON i.[object_id] = t.[object_id] AND s.index_id = i.index_id  
  GROUP BY t.name  
  )  
  ,cte2 as(select  
      cte.TableName,   
      (cte.pages * 8.) as TableSizeInKB,   
      ((CASE WHEN cte.used_pages_count > cte.pages   
                  THEN cte.used_pages_count - cte.pages  
                  ELSE 0   
            END) * 8.) as IndexSizeInKB  
  from CTE  
 )  
 select TableName,TableSizeInKB,IndexSizeInKB,  
 case when (TableSizeInKB+IndexSizeInKB)>1024*1024   
 then cast((TableSizeInKB+IndexSizeInKB)/1024*1024 as varchar)+'GB'  
 when (TableSizeInKB+IndexSizeInKB)>1024   
 then cast((TableSizeInKB+IndexSizeInKB)/1024 as varchar)+'MB'  
 else cast((TableSizeInKB+IndexSizeInKB) as varchar)+'KB' end [TableSizeIn+IndexSizeIn]  
 from CTE2  
 order by 2 desc

Result:

How to Get size of all Tables in a Database

#Solution-3:T-SQL |Stored Procedure

-- Using T-SQL
DECLARE @table_name sysname 
DECLARE table_list_cursor 
CURSOR FOR SELECT TABLE_NAME from INFORMATION_SCHEMA.TABLES 
where TABLE_TYPE='BASE TABLE' 
IF EXISTS ( SELECT * FROM    tempdb.INFORMATION_SCHEMA.COLUMNS WHERE    table_name = '##TABLE_RES')
BEGIN    
DROP TABLE ##TABLE_RES END CREATE TABLE ##TABLE_RES( Name nvarchar(255), 
Rows int, reserved varchar(18), Data varchar(18), index_size varchar(18),
Unused varchar(18)) OPEN table_list_cursor 
FETCH NEXT FROM table_list_cursor INTO @table_name 
INSERT INTO ##TABLE_RES exec sp_spaceused @table_name
WHILE @@FETCH_STATUS = 0 
BEGIN    FETCH NEXT FROM table_list_cursor INTO @table_name
INSERT INTO ##TABLE_RES exec sp_spaceused @table_name 
END CLOSE table_list_cursor 
DEALLOCATE table_list_cursor 
SELECT * from ##TABLE_RES order by rows desc
How to Get size of all Tables in a Database

#Solution-4: To Get the size of all tables in the SQL Server Database

In SQL Server, it is an easier way to get the size of all tables in the database is to use the Standard Report feature available in SQL Server Management Studio.

  • Open the SSMS (SQL Server Management Studio)
  • Now, Right Click on the Selected Database.
  • Select Reports
  • Next, Select Standard Reports
  • Then Click on Disk Usage by Table
How to Get size of all Tables in a Database using SQL Server

Output:

See Also:

The post How to Get the size of all Tables in a Database appeared first on Tech Insights.

]]>
https://reactconf.org/sql-server-get-size-of-all-tables-in-a-database/feed/ 0 534
How to Find All Identity Columns in the Database https://reactconf.org/find-all-identity-columns-in-the-database/ https://reactconf.org/find-all-identity-columns-in-the-database/#respond Sat, 04 Nov 2023 09:16:06 +0000 http://www.sqlneed.com/?p=573 In this article, we will learn How to Find all Identity Columns in the Database. You can typically query the system catalog or information schema, to find identity columns in …

The post How to Find All Identity Columns in the Database appeared first on Tech Insights.

]]>
In this article, we will learn How to Find all Identity Columns in the Database. You can typically query the system catalog or information schema, to find identity columns in different database management systems.

Here’s a Query to find all identity columns in a database.

Using SQL Server to Find All Identity Columns in the Database

SELECT 
	OBJECT_SCHEMA_NAME(tables.object_id, db_id())
	AS SchemaName,
	tables.name As TableName,
	columns.name as ColumnName
FROM sys.tables tables 
	JOIN sys.columns columns 
ON tables.object_id=columns.object_id
WHERE columns.is_identity=1

This query retrieves the table and column names of identity columns in a Database.

Find All identity columns in the database

Another way to find all identity columns in the Database. It contains details of all identity columns in a database along with their seed value, increment value, and other information. The below query for the same is given.

SELECT 
	OBJECT_SCHEMA_NAME(tables.object_id, db_id())
	AS SchemaName,
	tables.name As TableName,
	identity_columns.name as ColumnName,
	identity_columns.seed_value,
	identity_columns.increment_value,
	identity_columns.last_value
FROM sys.tables tables 
	JOIN sys.identity_columns identity_columns 
ON tables.object_id=identity_columns.object_id
Find All Identity Columns in the Database

Read Also:

The post How to Find All Identity Columns in the Database appeared first on Tech Insights.

]]>
https://reactconf.org/find-all-identity-columns-in-the-database/feed/ 0 573
Replace Null with Empty String in SQL Using Coalesce | ISNULL function https://reactconf.org/replace-null-with-empty-string-in-sql-using-coalesce-isnull-function/ https://reactconf.org/replace-null-with-empty-string-in-sql-using-coalesce-isnull-function/#respond Thu, 28 Sep 2023 06:10:52 +0000 http://www.sqlneed.com/?p=493 Replacing Null values with Empty strings or other custom values in SQL using ‘Coalesce()’ and ‘ISNULL()’ functions. In this article, we will learn How to Replace Null with Empty String …

The post Replace Null with Empty String in SQL Using Coalesce | ISNULL function appeared first on Tech Insights.

]]>
Replacing Null values with Empty strings or other custom values in SQL using ‘Coalesce()’ and ‘ISNULL()’ functions. In this article, we will learn How to Replace Null with Empty String in SQL Using Coalesce | ISNULL function.

Coalesce Function

The COALESCE() function can take multiple arguments and return the first non-null value from the list of arguments. For example:

Select coalesce(null,'Hight',null,'Low') as 'coalesce function' 

The above query returns the second value because it considers the second value as the first value that isn’t null.

Replace Null with Empty String Using Coalesce Function

-- Replace Null with Empty string
select Company,[First Name],[Last Name], coalesce([E-mail Address],'') as email from [dbo].[Customers]

-- Replace Null with custom value
select Company,[First Name],[Last Name], coalesce([E-mail Address],'Email address missing') as email from [dbo].[Customers]

Result:

Replace Null with Empty String in SQL Using Coalesce | ISNULL function

ISNULL Function

The ISNULL() function takes two arguments. It returns the not null value first. For example

Select ISNULL('Hight',null) as 'ISNULL function' 

Replace Null with Empty String Using ISNULL Function

select Company,[First Name],[Last Name], ISNULL([E-mail Address],'') as email from [dbo].[Customers]

Result

The post Replace Null with Empty String in SQL Using Coalesce | ISNULL function appeared first on Tech Insights.

]]>
https://reactconf.org/replace-null-with-empty-string-in-sql-using-coalesce-isnull-function/feed/ 0 2263
What are the benefits of using MS SQL Server? https://reactconf.org/what-are-the-benefits-of-using-ms-sql-server/ https://reactconf.org/what-are-the-benefits-of-using-ms-sql-server/#respond Fri, 02 Jun 2023 06:29:34 +0000 http://www.sqlneed.com/?p=452 Discover the numerous benefits of using MS SQL Server for efficient and secure data management. From data integrity and security to scalability, performance, and advanced features, MS SQL Server empowers …

The post What are the benefits of using MS SQL Server? appeared first on Tech Insights.

]]>
Discover the numerous benefits of using MS SQL Server for efficient and secure data management. From data integrity and security to scalability, performance, and advanced features, MS SQL Server empowers businesses of all sizes

What is MS SQL Server?

Data management is essential to organizations of all sizes in today’s digital landscape. Businesses rely on efficient and dependable database management systems to successfully store, process, and retrieve data. MS SQL Server, developed by Microsoft, is one such popular and capable database management system. In this post, we will look at the different advantages of utilizing MS SQL Server and why it is so popular among enterprises worldwide.

Before we go into the benefits, let’s first define MS SQL Server. MS SQL Server is a relational database management system (RDBMS) for storing, managing, and retrieving structured data. It provides a safe and scalable environment for programs to communicate with the database. MS SQL Server provides a solid working environment for developers and administrators thanks to its extensive set of capabilities and tools.

Data Integrity and Security

For any organization, data integrity and security are important. Constraints, triggers, and referential integrity are just a few of the strategies available in MS SQL Server to ensure data integrity. It also includes extensive security features such as authentication, authorization, and encryption to safeguard sensitive data from unauthorized access.

Scalability and Performance

   As a company grows, so do its data requirements. MS SQL Server excels at scalability, allowing businesses to handle enormous amounts of data efficiently. It provides vertical and horizontal growth, allowing organizations to meet their rising database needs. Furthermore, MS SQL Server’s query optimization algorithms and indexing options improve performance, resulting in faster data retrieval and processing.

Robustness and Reliability

   MS SQL Server is well-known for its dependability and resilience. It includes solutions for high availability and disaster recovery such as database mirroring, log shipping, and failover clustering. These features reduce downtime and guarantee that important company operations run smoothly.

Advanced-Data Management Features

   MS SQL Server provides a wide range of advanced data management tools. It supports sophisticated data types like geographic and XML data and gives robust tools for interacting with various data kinds. It also includes Before we go into the advantages, let’s first define MS SQL Server. MS SQL Server is a relational database management system (RDBMS) designed to store, manage, and retrieve structured data. It provides a secure and scalable framework for programs to interface with the underlying database. MS SQL Server provides a stable working environment for developers and administrators thanks to its extensive set of capabilities and tools. Partitioning, compression, and data deduplication are examples of features that optimize storage and increase overall database performance.

Compatibility and Integration

   MS SQL Server works smoothly with other Microsoft products and technologies, including the.NET framework, Azure services, and Microsoft Power BI. It also supports a variety of data access protocols, such as ODBC, OLE DB, and ADO.NET, allowing it to be used with a wide range of applications and computer languages.

Simplified Development and Administration

   MS SQL Server makes database development and administration easier. SQL Server Management Studio is a user-friendly graphical interface for managing databases, establishing security, and composing queries. It also supports strong programming languages such as T-SQL, which allows developers to create robust and efficient database applications.

Analytics and Business Intelligence

   MS SQL Server provides robust business information and analytics features. SQL Server Analysis Services (SSAS) for multidimensional analysis and SQL Server Reporting Services (SSRS) are included.

SSRS) to generate interactive reports. It also connects with Microsoft Power BI, allowing organizations to better visualize and analyze data.

Business Intelligence and Analytics

   MS SQL Server offers cost-effective database management solutions. It provides a variety of licensing choices, including free versions for smaller applications and cost-effective options for enterprise-level installations. Furthermore, robust documentation, online resources, and a huge user community lower the cost of training and support.

Real-World Examples of Benefits of Using MS SQL Server

Let’s look at some real-world examples to better grasp the benefits of MS SQL Server:

E-commerce Platform

   MS SQL Server is used for data storage and processing on an e-commerce platform with thousands of daily transactions. The platform takes advantage of MS SQL Server’s scalability and performance, ensuring quick and reliable retrieval of product information and order processing.

Healthcare System

   Using MS SQL Server, a healthcare system controls patient records, appointments, and medical history. The system’s data integrity features ensure that patient information stays correct and safe, while its robustness ensures that essential medical data is accessible at all times.

Financial services

SQL Server is used by financial services organizations to store customer data, account data, and transaction data. This information can be used to manage risk, track performance, and ensure compliance with rules.

Manufacturing

SQL Server is used by manufacturers to store product data, inventory data, and production data. This information can be used to increase efficiency, reduce costs, and satisfy client demand.

Related Post How to Reset Identity Columns in SQL Server

Conclusion

Finally, MS SQL Server provides various benefits of using MS SQL Server that make it a popular choice for enterprises looking for a dependable and efficient database management system. MS SQL Server enables organizations to manage their data successfully by assuring data integrity and security, as well as providing scalability, performance, and advanced data management tools. Its appeal is boosted by its seamless integration, easier development and administration, business intelligence capabilities, and low cost.

The post What are the benefits of using MS SQL Server? appeared first on Tech Insights.

]]>
https://reactconf.org/what-are-the-benefits-of-using-ms-sql-server/feed/ 0 452
How to Reset Identity Columns in SQL Server https://reactconf.org/how-to-reset-identity-columns-for-improved-performance-in-sql-server/ https://reactconf.org/how-to-reset-identity-columns-for-improved-performance-in-sql-server/#respond Wed, 26 Apr 2023 11:16:01 +0000 http://www.sqlneed.com/?p=432 The identity column in SQL Server makes it simple to generate unique values for table columns automatically. However, you may need to reset the identity column settings in SQL Server …

The post How to Reset Identity Columns in SQL Server appeared first on Tech Insights.

]]>
The identity column in SQL Server makes it simple to generate unique values for table columns automatically. However, you may need to reset the identity column settings in SQL Server on occasion. This may be necessary if you wish to reseed the identity column or start the identity column values at a specified number. In this post, we’ll go over How to Reset Identity Columns in SQL Server.

Understanding Identity Columns in SQL Server Before we proceed to reset identity column values, let us first define identity columns in SQL Server. When a new record is added to a SQL Server table, the identity field is automatically populated with a unique integer value. To assure row uniqueness, the identification column is frequently utilized as the table’s primary key.

Install Required Software

  • Microsoft® SQL Server® 2019 Express from here

Reseeding an Identity Column

Reseeding an identity column implies changing the value of the identity column to a certain integer. Reseeding an identity column is handy when you want to start the values of the identity column at a specified number or when you want to reset the values of the identity column after deleting rows from the database.

The DBCC CHECKIDENT command can be used to reseed an identity column in SQL Server. The command’s syntax is as follows:

DBCC CHECKIDENT ('TableName', RESEED, New_Value)

DBCC CHECKIDENT ('Customers', RESEED, 201)
 
How to Reset Identity Columns for Improved Performance in SQL Server

‘Customers’ is the name of the table whose identification column you wish to reseed in this case. ‘NewValue’ is the value to which the identity column should be reset. For instance, if you want to reset the identification column of the ‘Customers’ database to 201, execute the following command:

Also, Check the Previous Article Top 15 SQL Server Management Studio Keyboard Shortcuts and Tips

Automatically Resetting Identity Column Values

If you want to automatically reset the identity column values, construct a stored procedure that utilizes the DBCC CHECKIDENT command to reseed the identity column. The stored procedure can then be scheduled to run at a given time or interval using SQL Server Agent.

Conclusion
We explored how to reset identity column values in SQL Server in this article. We discussed how to reseed an identity column, insert rows with specified identity column values, and automatically reset identity column values. You may quickly reset identity column values in SQL Server by following these instructions.

The post How to Reset Identity Columns in SQL Server appeared first on Tech Insights.

]]>
https://reactconf.org/how-to-reset-identity-columns-for-improved-performance-in-sql-server/feed/ 0 432
Top 15 SQL Server Management Studio Keyboard Shortcuts and Tips https://reactconf.org/top-15-sql-server-management-studio-keyboard-shortcuts-and-tips/ https://reactconf.org/top-15-sql-server-management-studio-keyboard-shortcuts-and-tips/#respond Wed, 26 Apr 2023 03:45:43 +0000 http://www.sqlneed.com/?p=418 Are you weary of navigating SQL Server Management Studio’s (SSMS) menus and choices? You may save a lot of time and effort by using keyboard shortcuts. We’ll go over the …

The post Top 15 SQL Server Management Studio Keyboard Shortcuts and Tips appeared first on Tech Insights.

]]>
Are you weary of navigating SQL Server Management Studio’s (SSMS) menus and choices? You may save a lot of time and effort by using keyboard shortcuts. We’ll go over the Top 15 SQL Server Management Studio Keyboard Shortcuts and Tips in this article to increase your productivity.

An effective tool for administering SQL Server databases is called SQL Server Management Studio (SSMS). Users can communicate with SQL Server via its graphical user interface (GUI) without having to write any code. However, navigating SSMS with the mouse can be cumbersome and ineffective. Tasks can be completed more quickly and conveniently by using keyboard shortcuts.

 SQL Server Management Studio (SSMS) – what is it?

Users can administer SQL Server databases using the free Microsoft application SQL Server Management Studio (SSMS). For activities like building databases, tables, and stored procedures as well as running queries and managing users, it offers a user-friendly interface.

Why should you utilize keyboard shortcuts?

Keyboard shortcuts enable users to complete activities quickly and efficiently by avoiding the need to travel through menus and options. This saves time and effort, which is especially beneficial for recurring jobs. Keyboard shortcuts also lessen the possibility of errors by requiring less mouse movement and clicking.

More Related Post Calculate Date & Time in SQL Server

Top 15 SSMS Keyboard Shortcuts and Tips

Keyboard shortcuts for opening windows

  • Ctrl+T – Opens a new query window.
  • Ctrl+Shift+N – Opens a new solution.
  • Ctrl+Shift+O – Opens a file.

Keyboard shortcuts for managing tabs

  • Ctrl+Tab – Switches between open tabs.
  • Ctrl+F4 – Closes the current tab.
  • Ctrl+Shift+T – Reopens the last closed tab.

Keyboard shortcuts for executing queries

  • F5 – Executes the query.
  • Ctrl+Shift+M – Executes the query and includes the actual execution plan.
  • Ctrl+R – Toggles the display of the query results pane.

Keyboard shortcuts for formatting code

  • Ctrl+K, Ctrl+F – Formats the entire document.
  • Ctrl+K, Ctrl+D – Formats the current selection.
  • Ctrl+K, Ctrl+C – Comments on the current selection.
  • Ctrl+K, Ctrl+U – Uncomments the current selection.

Keyboard shortcuts for debugging

  • F11 – Toggles a breakpoint on the current line.
  • F5 – Starts debugging.
  • Shift+F5 – Stops debugging.
  • F10 – Steps over the current line.
  • F11 – Steps into the current line.

Keyboard shortcuts for searching and replacing

  • Ctrl+F – Opens the Find dialog.
  • Ctrl+Shift+F – Opens the Find and Replace dialog.
  • F3 – Finds the next occurrence of the current search term.
  • Shift+F3 – Finds the previous occurrence of the current search term.

Keyboard shortcuts for commenting and uncommenting code

  • Ctrl+K, Ctrl+C – Comments on the current selection.
  • Ctrl+K, Ctrl+U – Uncomments the current selection.

Keyboard shortcuts for displaying the execution plan

  • Ctrl+M – Toggles the display of the actual execution plan.

Keyboard shortcuts for managing connections

  • Ctrl+Alt+C – Connects to a database.
  • Ctrl+Alt+D – Disconnects from a database.

Keyboard shortcuts for managing objects

  • F7 – Opens the Object Explorer.
  • F8 – Toggles the display of the Object Explorer Details.

Keyboard shortcuts for managing indexes

  • Alt+F1 – Displays the index details.

Keyboard shortcuts for managing databases

  • Ctrl+D – Opens the Database Properties dialog.
  • Ctrl+Alt+G – Generates a script for a database.

Keyboard shortcuts for managing tables

  • Alt+F1 – Displays the table details.

Keyboard shortcuts for managing views

  • Alt+F1 – Displays the view details.

Keyboard shortcuts for managing stored procedures

  • Ctrl+Shift+M – Executes a stored procedure.
  • Alt+F1 – Displays the stored procedure details.

Conclusion

SSMS keyboard shortcuts can boost your productivity by allowing you to complete activities more quickly and efficiently. We covered the top 15 SSMS keyboard shortcuts and tips in this article, including keyboard shortcuts for opening windows, managing tabs, executing queries, formatting code, debugging, searching and replacing, commenting and uncommenting code, displaying the execution plan, and managing connections, objects, indexes, databases, tables, views, and stored procedures.

The post Top 15 SQL Server Management Studio Keyboard Shortcuts and Tips appeared first on Tech Insights.

]]>
https://reactconf.org/top-15-sql-server-management-studio-keyboard-shortcuts-and-tips/feed/ 0 418
How to Calculate Date & Time in SQL Server https://reactconf.org/how-to-calculate-date-time-in-sql-server/ https://reactconf.org/how-to-calculate-date-time-in-sql-server/#respond Thu, 20 Apr 2023 02:16:58 +0000 http://www.sqlneed.com/?p=380 In this article, we will learn How to Calculate Date & Time in SQL Server, and giving you the information and abilities you need to master it and utilize it …

The post How to Calculate Date & Time in SQL Server appeared first on Tech Insights.

]]>
In this article, we will learn How to Calculate Date & Time in SQL Server, and giving you the information and abilities you need to master it and utilize it to the most extent possible.

The DATEDIFF function of SQL Server, a popular relational database management system, is among its most helpful features. This function computes the difference between two dates and can be applied in several ways to do intricate calculations and produce helpful results.

Introduction

The built-in SQL Server function known as DATEDIFF returns the difference between two dates in a given date part. It can be employed to determine how many days, weeks, months, or years between two dates. This function is especially helpful in business applications when it is important to figure out how many days there are between two dates, such as how many days there are between the date of the order and the date of delivery.

Syntax of DATEDIFF Function

DATEDIFF(datepart, startdate, enddate)

DATEDIFF Function Parameters

Three parameters are required for the DATEDIFF function:

DatepartThis is the date portion that is used to calculate the difference. The values year, quarter, month, day of the year, day, week, hour, minute, second, millisecond, microsecond, and nanosecond are all possible.
StartdateThis is the starting date.
EnddateThis is the ending date.

Datepart

The section of the date that is used to determine the difference between the two dates is specified by the datepart parameter. The DATEDIFF function supports a number of date components, and each one has a unique formula for determining the difference.

  • Year : calculates the number of years that have passed between the two dates.
  • Quarter : calculates the number of quarters that have passed between the two dates.
  • Month : calculates the number of months that have passed between the two dates.
  • dayofyear: Based on a 365-day year, determines the number of days that separate the two dates.
  • day: Determines how many days there are between the two dates.
  • calculates the number of weeks that have passed between the two dates.
  • calculates the time difference between the two dates in hours.
  • calculates the time difference between the two dates in minutes.
  • calculates the time difference between the two dates in seconds.
  • calculates the time difference between the two dates in milliseconds.
  • microsecond: Determines the number of microseconds that between the two dates.
  • nanosecond: Determines the number of nanoseconds that separate the two dates.

Using DATEDIFF

Let’s explore some of the date parts that can be utilized with the DATEDIFF function in more detail.

Caculating the Year

SELECT DATEDIFF(Year, '2001-03-01', GETDATE())  as Year
How to Calculate Date in SQL Server

Caculating the Month

SELECT DATEDIFF(MONTH, '2001-03-01', GETDATE())  as Months

Caculating the Days

SELECT DATEDIFF(DAY, '2001-03-01', GETDATE())  as Days

Caculating the Hours

SELECT DATEDIFF(HOUR, '2023-04-19 01:34:02', GETDATE())  as Hours

Caculating the Minutes

SELECT DATEDIFF(MINUTE, '2023-04-19 01:34:02', GETDATE())  as Minutes

Caculating the Seconds

SELECT DATEDIFF(SECOND, '2023-04-19 01:34:02', GETDATE())  as Seconds

Common DATEDIFF Errors

It’s crucial to be aware of certain typical mistakes that can happen while using the DATEDIFF function. The erroneous date portion being used is a frequent mistake. An error message will appear if you enter an invalid date portion. Make sure you are using a correct date part to fix this error.

Putting the startdate and enddate parameters in the wrong order is another frequent mistake. You will obtain a negative number if you reverse these parameters’ order. Make sure the startdate and enddate parameters are used in the right order to fix this issue.

Conclusion

The DATEDIFF function in SQL Server is a potent tool that can be used in a variety of ways to determine the difference between two dates. You can perform intricate calculations and provide useful reports by becoming an expert with this function. You may use the DATEDIFF function to its fullest extent and advance your knowledge of SQL programming with the knowledge and abilities you acquire from this tutorial.

The post How to Calculate Date & Time in SQL Server appeared first on Tech Insights.

]]>
https://reactconf.org/how-to-calculate-date-time-in-sql-server/feed/ 0 380
How to Find and Remove Duplicate records in a table in SQL https://reactconf.org/3-ways-find-and-remove-duplicate-records-in-a-table-in-sql/ https://reactconf.org/3-ways-find-and-remove-duplicate-records-in-a-table-in-sql/#respond Wed, 12 Apr 2023 02:37:22 +0000 http://www.sqlneed.com/?p=349 In this article, we will learn How to Find and Remove Duplicate records in a table in SQL. We will explore some of the most effective method for finding and …

The post How to Find and Remove Duplicate records in a table in SQL appeared first on Tech Insights.

]]>
In this article, we will learn How to Find and Remove Duplicate records in a table in SQL. We will explore some of the most effective method for finding and removing duplicate records in SQL, including using GROUP BY Clause, INNER JOIN, EXIST CLAUSE and ROW_NUMBER Function.

We need to create sample table

 CREATE TABLE [dbo].[Customers](
	[id] [int] NOT NULL,
	[firstName] [nvarchar](max) NOT NULL,
	[lastName] [nvarchar](max) NOT NULL,
	[job] [nvarchar](max) NOT NULL,
	[amount] [real] NOT NULL,
	[tdate] [datetime2](7) NOT NULL,
	[email] [varchar](25) NULL
	)

Then Insert the Sample record

 INSERT [dbo].[Customers] ([id], [firstName], [lastName], [job], [amount], [tdate], [email]) VALUES (1, N'Astle', N'Vicky', N'Software Engineer', 50000, CAST(N'2021-01-29T00:00:00.0000000' AS DateTime2), N'astle@example.com')
INSERT [dbo].[Customers] ([id], [firstName], [lastName], [job], [amount], [tdate], [email]) VALUES (2, N'John', N'Vicky', N'software engineer', 55000, CAST(N'2022-12-03T00:00:00.0000000' AS DateTime2), N'John@example.com')
INSERT [dbo].[Customers] ([id], [firstName], [lastName], [job], [amount], [tdate], [email]) VALUES (3, N'Fleming', N'Stuart', N'software engineer', 55000, CAST(N'2022-12-29T00:00:00.0000000' AS DateTime2), N'astle@example.com')
INSERT [dbo].[Customers] ([id], [firstName], [lastName], [job], [amount], [tdate], [email]) VALUES (4, N'Philip', N'John', N'Manager', 650000, CAST(N'2022-12-29T00:00:00.0000000' AS DateTime2), N'ricky@example.com')
INSERT [dbo].[Customers] ([id], [firstName], [lastName], [job], [amount], [tdate], [email]) VALUES (5, N'Ricky', N'Fleming', N'DBA Administrator', 78000, CAST(N'2022-12-29T00:00:00.0000000' AS DateTime2), N'ricky@example.com')
INSERT [dbo].[Customers] ([id], [firstName], [lastName], [job], [amount], [tdate], [email]) VALUES (6, N'mack', N'Mack', N'Manager', 56000, CAST(N'2022-12-20T00:00:00.0000000' AS DateTime2), N'nack@exampl.com')
INSERT [dbo].[Customers] ([id], [firstName], [lastName], [job], [amount], [tdate], [email]) VALUES (7, N'steva', N'margh', N'Team Lead', 456000, CAST(N'2022-12-23T00:00:00.0000000' AS DateTime2), N'steva@example.com')

Here are few SQL methods for finding and removing duplicate records in a table using SQL

GROUP BY and HAVING CLAUSE

Suppose we have a table customer with columns id, firstname, email etc. 

Suppose we have a table customer with columns id, firstname, email etc.  To find and remove duplicate records based on the “email”  column, you can use the following SQL query

SELECT EMAIL,COUNT(*)
FROM Customers GROUP BY EMAIL
HAVING COUNT(*)>1

This query will group the rows in the “Customers” table by the “email” column, and the return the email and count of each group that has more than on row. To delete the duplicate records , you can use the following SQL query

Find and remove duplicate record
DELETE FROM Customers WHERE id NOT IN(SELECT MAX(id) FROM Customers GROUP BY EMAIL)

This query will delete all records in the customers table that have a duplicate email, except for the one with highest id value

EXISTS CLAUSE

Suppose we have a table customer with columns id, firstname, email etc  To find and remove duplicate records based on the “firstname”  column, you can use the following SQL query

SELECT c.id,c.firstName
FROM Customers c WHERE EXISTS (
SELECT * FROM Customers cust
WHERE c.firstName=cust.firstName
AND c.id > cust.id
)
Find and remove duplicate record

This query will select all rows in the customers table where there exists another row with the same firstname and a lower id value. To delete the duplicate records , you can use the following SQL query

DELETE c FROM Customers c,Customers cust
WHERE c.firstName=cust.firstName
AND c.id > cust.id

This query will delete all records in the customers table that have a duplicate firstname, except for the one with lowest id value

Document

ROW_NUMBER Function

In this query , I’m using the same example as in the above one, but this time I’m using the ROW_NUMBER Function to find the duplicate data

SELECT id, email , ROW_NUMBER() OVER (
     PARTITION BY email ORDER BY id
	 ) AS row_dup
	 FROM Customers

The query return the id, email and row number for each row from the email column. To remove duplicate rows, modify the query as follows

WITH CT AS(
SELECT id, email , ROW_NUMBER() OVER (
     PARTITION BY email ORDER BY id
	 ) AS row_dup
	 FROM Customers
	 )
	 DELETE FROM CT WHERE row_dup>1

This query will use a common table expression (CTE) to assign row numbers to each records in the customers table based on the email column, then delete any rows with a row number greater than 1

The post How to Find and Remove Duplicate records in a table in SQL appeared first on Tech Insights.

]]>
https://reactconf.org/3-ways-find-and-remove-duplicate-records-in-a-table-in-sql/feed/ 0 349
How to Find and remove Numbers from string in a column using SQL Server https://reactconf.org/remove-numbers-from-string-column-using-sql-server/ https://reactconf.org/remove-numbers-from-string-column-using-sql-server/#respond Fri, 31 Mar 2023 04:18:53 +0000 http://www.sqlneed.com/?p=335 In this Tutorial, We will learn How to Find and remove Numbers from string in a column using SQL Server. Remove numeric character from a string in SQL SERVER using …

The post How to Find and remove Numbers from string in a column using SQL Server appeared first on Tech Insights.

]]>
In this Tutorial, We will learn How to Find and remove Numbers from string in a column using SQL Server. Remove numeric character from a string in SQL SERVER using the PATINDEX function along with the REPLACE function.

First we need to create Table 

CREATE TABLE [dbo].[EmployeeV](
	ID int NOT NULL,
	[FirstName] Varchar(200) NOT NULL,
	[MiddleName] Varchar(200) NOT NULL,
	[LastName] Varchar(200) NOT NULL,	
	[JobTitle] Varchar(200) NOT NULL,
	[Department] Varchar(200) NOT NULL,	
	[Gender] [nchar](1) NULL
)

Then Insert data into EmployeeV Table

INSERT [dbo].[EmployeeV] ([ID], [FirstName], [MiddleName], [LastName], [JobTitle], [Department], [Gender]) VALUES (1, N'Ken12', N'J', N'Sánchez', N'Chief Executive Officer', N'Executive', N'M')
INSERT [dbo].[EmployeeV] ([ID], [FirstName], [MiddleName], [LastName], [JobTitle], [Department], [Gender]) VALUES (2, N'Te3r31ri', N'Lee', N'Duffy', N'Vice President of Engineering', N'Engineering', N'F')
INSERT [dbo].[EmployeeV] ([ID], [FirstName], [MiddleName], [LastName], [JobTitle], [Department], [Gender]) VALUES (3, N'Ro23be4447rto', NULL, N'Tamburello', N'Engineering Manager', N'Engineering', N'M')
INSERT [dbo].[EmployeeV] ([ID], [FirstName], [MiddleName], [LastName], [JobTitle], [Department], [Gender]) VALUES (4, N'Rob4', NULL, N'Walters', N'Senior Tool Designer', N'Tool Design', N'M')
INSERT [dbo].[EmployeeV] ([ID], [FirstName], [MiddleName], [LastName], [JobTitle], [Department], [Gender]) VALUES (5, N'Gail5', N'A', N'Erickson', N'Design Engineer', N'Engineering', N'M')
INSERT [dbo].[EmployeeV] ([ID], [FirstName], [MiddleName], [LastName], [JobTitle], [Department], [Gender]) VALUES (6, N'Jossef666', N'H', N'Goldberg', N'Design Engineer', N'Engineering', N'M')
INSERT [dbo].[EmployeeV] ([ID], [FirstName], [MiddleName], [LastName], [JobTitle], [Department], [Gender]) VALUES (7, N'45454Dylan', N'A', N'Miller', N'Research and Development Manager', N'Research and Development', N'M')
INSERT [dbo].[EmployeeV] ([ID], [FirstName], [MiddleName], [LastName], [JobTitle], [Department], [Gender]) VALUES (8, N'Diane55', N'L', N'Margheim', N'Research and Development Engineer', N'Research and Development', N'F')
INSERT [dbo].[EmployeeV] ([ID], [FirstName], [MiddleName], [LastName], [JobTitle], [Department], [Gender]) VALUES (9, N'Gigi554', N'N', N'Matthew', N'Research and Development Engineer', N'Research and Development', N'F')
INSERT [dbo].[EmployeeV] ([ID], [FirstName], [MiddleName], [LastName], [JobTitle], [Department], [Gender]) VALUES (10, N'Mi4chae43l', NULL, N'Raheem', N'Research and Development Manager', N'Research and Development', N'M')

Remove numeric character in a string

DECLARE @FirstName  varchar(100)
SET @FirstName = 'Wel123come234'
WHILE PATINDEX('%[0-9]%', @FirstName)>0
	SET @FirstName = REPLACE(@FirstName, SUBSTRING(@FirstName, PATINDEX('%[0-9]%', @FirstName),1),'')
SELECT @FirstName

Also Check Previous Article How to Count Male and Female Without Case Statement

  • PATINDEX Function- It finds any numeric characters in the string. It returns the starting position of the first occurrence of a pattern in a specified expression.
  • PATINDEX function return a value greater than o it means that a numeric character was found in the string.
  • REPLACE Function – It replace that character with an empty string.
  • SUBSTRING Function – It is used to extract the numeric character that was found using the stating position returned by PAINDEX.

Remove numeric character in a string using Function

CREATE Function RemoveNumericCharacterinstring(@inputstr VARCHAR(100))
Returns VARCHAR(max)
AS
BEGIN

 
WHILE PATINDEX('%[0-9]%', @inputstr)>0
	SET @inputstr = REPLACE(@inputstr, SUBSTRING(@inputstr, PATINDEX('%[0-9]%', @inputstr),1),'')

	return @inputstr;	

END

Test SQL Function

SELECT [dbo].[RemoveNumericCharacterinstring]('Welco234me')

The post How to Find and remove Numbers from string in a column using SQL Server appeared first on Tech Insights.

]]>
https://reactconf.org/remove-numbers-from-string-column-using-sql-server/feed/ 0 335
How to count male and female without case statement in SQL https://reactconf.org/how-to-count-male-and-female-case-statement-in-sql/ https://reactconf.org/how-to-count-male-and-female-case-statement-in-sql/#respond Fri, 31 Mar 2023 01:47:12 +0000 http://www.sqlneed.com/?p=325 In this Tutorial, We will learn How to Count Male and Female Without Case Statement in SQL Server. Counting male and female in SQL Without using a Case statement by …

The post How to count male and female without case statement in SQL appeared first on Tech Insights.

]]>
In this Tutorial, We will learn How to Count Male and Female Without Case Statement in SQL Server. Counting male and female in SQL Without using a Case statement by using the SUM function with a conditional expression.

First we need to create Table 

CREATE TABLE [dbo].[EmployeeV](
	ID int NOT NULL,
	[FirstName] Varchar(200) NOT NULL,
	[MiddleName] Varchar(200) NOT NULL,
	[LastName] Varchar(200) NOT NULL,	
	[JobTitle] Varchar(200) NOT NULL,
	[Department] Varchar(200) NOT NULL,	
	[Gender] [nchar](1) NULL
)

Then Insert data into EmployeeV Table

INSERT [dbo].[EmployeeV] ([ID], [FirstName], [MiddleName], [LastName], [JobTitle], [Department], [Gender]) VALUES (1, N'Ken', N'J', N'Sánchez', N'Chief Executive Officer', N'Executive', N'M')
INSERT [dbo].[EmployeeV] ([ID], [FirstName], [MiddleName], [LastName], [JobTitle], [Department], [Gender]) VALUES (2, N'Terri', N'Lee', N'Duffy', N'Vice President of Engineering', N'Engineering', N'F')
INSERT [dbo].[EmployeeV] ([ID], [FirstName], [MiddleName], [LastName], [JobTitle], [Department], [Gender]) VALUES (3, N'Roberto', NULL, N'Tamburello', N'Engineering Manager', N'Engineering', N'M')
INSERT [dbo].[EmployeeV] ([ID], [FirstName], [MiddleName], [LastName], [JobTitle], [Department], [Gender]) VALUES (4, N'Rob', NULL, N'Walters', N'Senior Tool Designer', N'Tool Design', N'M')
INSERT [dbo].[EmployeeV] ([ID], [FirstName], [MiddleName], [LastName], [JobTitle], [Department], [Gender]) VALUES (5, N'Gail', N'A', N'Erickson', N'Design Engineer', N'Engineering', N'M')
INSERT [dbo].[EmployeeV] ([ID], [FirstName], [MiddleName], [LastName], [JobTitle], [Department], [Gender]) VALUES (6, N'Jossef', N'H', N'Goldberg', N'Design Engineer', N'Engineering', N'M')
INSERT [dbo].[EmployeeV] ([ID], [FirstName], [MiddleName], [LastName], [JobTitle], [Department], [Gender]) VALUES (7, N'Dylan', N'A', N'Miller', N'Research and Development Manager', N'Research and Development', N'M')
INSERT [dbo].[EmployeeV] ([ID], [FirstName], [MiddleName], [LastName], [JobTitle], [Department], [Gender]) VALUES (8, N'Diane', N'L', N'Margheim', N'Research and Development Engineer', N'Research and Development', N'F')
INSERT [dbo].[EmployeeV] ([ID], [FirstName], [MiddleName], [LastName], [JobTitle], [Department], [Gender]) VALUES (9, N'Gigi', N'N', N'Matthew', N'Research and Development Engineer', N'Research and Development', N'F')
INSERT [dbo].[EmployeeV] ([ID], [FirstName], [MiddleName], [LastName], [JobTitle], [Department], [Gender]) VALUES (10, N'Michael', NULL, N'Raheem', N'Research and Development Manager', N'Research and Development', N'M')
INSERT [dbo].[EmployeeV] ([ID], [FirstName], [MiddleName], [LastName], [JobTitle], [Department], [Gender]) VALUES (11, N'Ovidiu', N'V', N'Cracium', N'Senior Tool Designer', N'Tool Design', N'M')
INSERT [dbo].[EmployeeV] ([ID], [FirstName], [MiddleName], [LastName], [JobTitle], [Department], [Gender]) VALUES (12, N'Thierry', N'B', N'D''Hers', N'Tool Designer', N'Tool Design', N'F')
INSERT [dbo].[EmployeeV] ([ID], [FirstName], [MiddleName], [LastName], [JobTitle], [Department], [Gender]) VALUES (13, N'Janice', N'M', N'Galvin', N'Tool Designer', N'Tool Design', N'F')
INSERT [dbo].[EmployeeV] ([ID], [FirstName], [MiddleName], [LastName], [JobTitle], [Department], [Gender]) VALUES (14, N'Michael', N'I', N'Sullivan', N'Senior Design Engineer', N'Engineering', N'M')
INSERT [dbo].[EmployeeV] ([ID], [FirstName], [MiddleName], [LastName], [JobTitle], [Department], [Gender]) VALUES (15, N'Sharon', N'B', N'Salavaria', N'Design Engineer', N'Engineering', N'M')
INSERT [dbo].[EmployeeV] ([ID], [FirstName], [MiddleName], [LastName], [JobTitle], [Department], [Gender]) VALUES (16, N'David', N'M', N'Bradley', N'Marketing Manager', N'Marketing', N'M')
INSERT [dbo].[EmployeeV] ([ID], [FirstName], [MiddleName], [LastName], [JobTitle], [Department], [Gender]) VALUES (17, N'Kevin', N'F', N'Brown', N'Marketing Assistant', N'Marketing', N'M')
INSERT [dbo].[EmployeeV] ([ID], [FirstName], [MiddleName], [LastName], [JobTitle], [Department], [Gender]) VALUES (18, N'John', N'L', N'Wood', N'Marketing Specialist', N'Marketing', N'M')
INSERT [dbo].[EmployeeV] ([ID], [FirstName], [MiddleName], [LastName], [JobTitle], [Department], [Gender]) VALUES (19, N'Mary', N'A', N'Dempsey', N'Marketing Assistant', N'Marketing', N'F')
INSERT [dbo].[EmployeeV] ([ID], [FirstName], [MiddleName], [LastName], [JobTitle], [Department], [Gender]) VALUES (20, N'Wanida', N'M', N'Benshoof', N'Marketing Assistant', N'Marketing', N'F')
INSERT [dbo].[EmployeeV] ([ID], [FirstName], [MiddleName], [LastName], [JobTitle], [Department], [Gender]) VALUES (21, N'Terry', N'J', N'Eminhizer', N'Marketing Specialist', N'Marketing', N'F')
INSERT [dbo].[EmployeeV] ([ID], [FirstName], [MiddleName], [LastName], [JobTitle], [Department], [Gender]) VALUES (22, N'Sariya', N'E', N'Harnpadoungsataya', N'Marketing Specialist', N'Marketing', N'F')
INSERT [dbo].[EmployeeV] ([ID], [FirstName], [MiddleName], [LastName], [JobTitle], [Department], [Gender]) VALUES (23, N'Mary', N'E', N'Gibson', N'Marketing Specialist', N'Marketing', N'F')
	

Now Execute the Count the Male and Female query. This query will return the number of male and female separately in two different columns. Here’s an example

SELECT
    
    SUM(IIF(GENDER = 'M', 1, 0)) AS Male,
    SUM(IIF(GENDER = 'F', 1, 0)) AS Female
FROM
    EmployeeV

count male and female without case statement in SQL

Now Execute the Count the Male and Female query. This query will return the number of male and female in each department separately in two different columns. Here’s an example

SELECT
    Department,
    SUM(IIF(GENDER = 'M', 1, 0)) AS Male,
    SUM(IIF(GENDER = 'F', 1, 0)) AS Female
FROM
    EmployeeV

	group by Department
Count Male and Female SQL Server

Step by Step Explanation of the SQL Query

  • SELECT – SELECT statement to retrieve the male and female count from table.
  • SUM Function – Count the Males and Females. The SUM function takes an expression that evaluates to 1 if the condition is True and 0 if the condition is False.
  • IIF Function – return a value if a condition is TRUE or another value if a condition is False.

The post How to count male and female without case statement in SQL appeared first on Tech Insights.

]]>
https://reactconf.org/how-to-count-male-and-female-case-statement-in-sql/feed/ 0 325