SQL Archives - Tech Insights https://reactconf.org/category/advanced-sql-conditionally-updating-update-command/ Unveiling Tomorrow's Tech Today, Where Innovation Meets Insight Thu, 28 Sep 2023 06:10:52 +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 SQL Archives - Tech Insights https://reactconf.org/category/advanced-sql-conditionally-updating-update-command/ 32 32 230003556 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
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
How to Update, Insert and Delete data through Views in SQL Server https://reactconf.org/how-to-update-insert-delete-data-through-views-in-sql-server/ https://reactconf.org/how-to-update-insert-delete-data-through-views-in-sql-server/#respond Mon, 27 Mar 2023 01:37:02 +0000 http://www.sqlneed.com/?p=306 Most frequent question in SQL Server interviews is How to Update, Insert and Delete data through Views in SQL Server. To update, insert and delete data in a table through …

The post How to Update, Insert and Delete data through Views in SQL Server appeared first on Tech Insights.

]]>
Most frequent question in SQL Server interviews is How to Update, Insert and Delete data through Views in SQL Server.

To update, insert and delete data in a table through views in SQL Server, you need to understand the following.
Important
⦁ View – it is a virtual table that is created by joining one or more tables. it does not contain any physical data but provides a logical representation of the underlying data.
⦁ Views can be used to update, insert and delete data in the tables.

Update Views
⦁ View must contain only one table.
⦁ View must not use any subqueries.
⦁ It should not be use DISTINCT Keyword.
⦁ View must not use TOP keyword.
⦁ Can only update columns that belong to a single base table.

CREATE View EmployeeV AS SELECT * FROM Employee

SELECT * FROM EmployeeV 

UPDATE EmployeeV SET hire_date = '2015-12-15' WHERE emp_id ='L-B31947F'

Insert Views
⦁ cannot insert a row if the view references more than one base table.
⦁ view cannot contain any aggregate function, GROUP BY or HAVING clauses.
⦁ view cannot contain any subqueries.

INSERT INTO EmployeeV(emp_id,fname,lname,job_id,pub_id) VALUES('SA1250543','JOHN','Fleming',12,0877) 

Delete
⦁ You cannot delete a row if the view references more than one table.
⦁ It must contain all the columns from the underlying table that are part of the primary key or a unique constraint.

DELETE FROM EmployeeV WHERE emp_id = 'SA1250543'

The post How to Update, Insert and Delete data through Views in SQL Server appeared first on Tech Insights.

]]>
https://reactconf.org/how-to-update-insert-delete-data-through-views-in-sql-server/feed/ 0 2262
How to Search Text using Contains Command in SQL Server https://reactconf.org/contains-command-in-sql-server/ https://reactconf.org/contains-command-in-sql-server/#respond Sat, 25 Mar 2023 03:39:26 +0000 http://www.sqlneed.com/?p=286 For searching a specific word or phrase within a full-text index in SQL Server, use the CONTAINS predicate. In this tutorial, we will learn How to Search Text using SQL …

The post How to Search Text using Contains Command in SQL Server appeared first on Tech Insights.

]]>
For searching a specific word or phrase within a full-text index in SQL Server, use the CONTAINS predicate.

In this tutorial, we will learn How to Search Text using SQL Contains Command in SQL Server.

  • CONTAINS  is the predicate in a WHERE clause that performs a full-text search
  • CONTAINS  – searches for a word or phrase using fuzzy logic

Also check the previous article Find 2nd, 3rd and Nth Highest Salary in SQL SERVER

NEAR: Finds words that are close to one another.

AND: Identifies documents with both search phrases in them.

OR:  Finds records that have either search term in them.

NOT:: Finds documents that do not contain the search term.

Find Text using SQL Contains Command

USE AdventureWorks2019;    
SELECT Name, ListPrice FROM Production.Product  WHERE ListPrice = 539.99  
   AND CONTAINS(Name, 'Mountain');  
  
 Contains Command in SQL Server

In this example, product denotes the name of the table you want to search, Name denotes the name of the column you want to search, and ‘search term’ denotes the term you want to look for.

SELECT Name, Color   
FROM Production.Product  
WHERE CONTAINS((Name, Color), 'Red');
Contains Command in SQL Server

The post How to Search Text using Contains Command in SQL Server appeared first on Tech Insights.

]]>
https://reactconf.org/contains-command-in-sql-server/feed/ 0 286
How to Find the Highest Salary in SQL SERVER https://reactconf.org/find-2nd-3rd-and-highest-salary-in-sql-server/ https://reactconf.org/find-2nd-3rd-and-highest-salary-in-sql-server/#respond Fri, 17 Mar 2023 11:16:51 +0000 http://www.sqlneed.com/?p=264 In this Tutorial, we will discuss, Multiple ways to Find 2nd, 3rd, and Nth Highest Salary in SQL. When it comes to SQL Server interviews, one of the most important …

The post How to Find the Highest Salary in SQL SERVER appeared first on Tech Insights.

]]>
In this Tutorial, we will discuss, Multiple ways to Find 2nd, 3rd, and Nth Highest Salary in SQL. When it comes to SQL Server interviews, one of the most important questions is whether or not the candidate can write complex SQL queries.  

Three ways to find the Nth Highest Salary in SQL

  • Using Correlate subquery
  • By using ROW_Number()
  • TOP Keyword
  • DENSE_RANK()

First, we need to create an Employee_salary  table. The employee table has three columns, Id , Employeename, salary.

CREATE TABLE [dbo].[Employee_salary](
    [id] [int] IDENTITY(1,1) NOT NULL,
	[Employeename] [varchar](10) NULL,
	[salary] [float] NULL
	)

Insert Employee data in the Employee table

INSERT INTO Employee_salary(Employeename,salary)VALUES('Ken','35000')
INSERT INTO Employee_salary(Employeename,salary)VALUES('Wanida','60000')
INSERT INTO Employee_salary(Employeename,salary)VALUES('Michael','55000')
INSERT INTO Employee_salary(Employeename,salary)VALUES('Sariya','62000')

Retrieve the Employee Data

SELECT * FROM Employee_salary

Second Highest Salary in SQL

In the employee salary, we want to find out the second highest salary.

SELECT TOP 1 * FROM 
(SELECT TOP 2 salary FROM Employee_salary ORDER BY salary DESC)
AS innerq ORDER BY salary 

Also, check the Previous Article How to Find Top N records using SQL

 2nd, 3rd and Nth Highest Salary in SQL SERVER

First Highest Salary in SQL

In the employee salary, we want to find out the First highest salary.

SELECT TOP 1 * FROM 
(SELECT TOP 1 salary FROM Employee_salary ORDER BY salary DESC)
AS innerq ORDER BY salary 

Third highest Salary in SQL

In the employee salary, we want to find out the Third highest salary

SELECT TOP 1 * FROM 
(SELECT TOP 3 salary FROM Employee_salary ORDER BY salary DESC)
AS innerq ORDER BY salary 

Find the Nth Highest Salary Using DENSE_RANK

The DENSE_RANK function returns the rank of each row within a result set partition, with no gaps in the ranking values. The ranking in the DESNE_RANK() function is integer values starting from 1.

SELECT * FROM
(SELECT Employeename,Salary,DENSE_RANK()
over(ORDER BY salary desc) As nested_query FROM Employee_salary)
AS nth_nestedquery
WHERE nested_query=3

 

Find the Nth Highest Salary Using ROW_NUMBER

The ROW_NUMBER function is a window function that assigns a sequence integer to each row within the partition of a result set. Starting at 1 for the first row in each partition.

SELECT Employeename,Salary,ROW_NUMBER()
over(ORDER BY salary desc) As NTH_nested_query FROM Employee_salary

SELECT * FROM(
SELECT Employeename,Salary,ROW_NUMBER()
over(ORDER BY salary desc) As NTH_nested_query FROM Employee_salary)
as NESTED_QUERY WHERE NTH_nested_query=3

The post How to Find the Highest Salary in SQL SERVER appeared first on Tech Insights.

]]>
https://reactconf.org/find-2nd-3rd-and-highest-salary-in-sql-server/feed/ 0 2256