'Is it better to have a single insert or several updates For Fill in Data in a Table in SQL Server?
I have a table in which the IDs of all customers (About 10 million) along with information about their interests are recorded, for example, interest in books, movies, music, etc.and the structure of the table is as follows:
InteresTable:
| CustomerId | InterestedInbook | InterestedInMovies | InterestedInMusic |
|---|---|---|---|
| 1 | 1 | 0 | 1 |
| 1 | 0 | 0 | 1 |
| 1 | 1 | 1 | 1 |
If Customer Interes In Book Then the value Of The InterestedInBook would be 1.
For each of these interests, there is a separate table in which the number of interested customers is kept.
Now I want to fill in this table. Is it better to Left join the customer table with other tables using the query below the main table And insert at once?
INSERT INTO InteresTable (CustomerId, InterestedInbook, InterestedInMovie, InterestedInMusic)
SELECT
A.CustomerId,
CASE
WHEN B.CustomerNumber IS NOT NULL THEN 1 ELSE 0
END AS InterestedInbook,
CASE
WHEN B.CustomerNumber IS NOT NULL THEN 1 ELSE 0
END AS InterestedInMovie,
CASE
WHEN B.CustomerNumber IS NOT NULL THEN 1 ELSE 0
END AS InterestedInMusic
FROM
Customer A
LEFT JOIN
BookInt B ON A.CustomerNumber = B.CustomerNumber
LEFT JOIN
MovieInt C ON A.CustomerNumber = C.CustomerNumber
LEFT JOIN
MusicInt D ON A.CustomerNumber = D.CustomerNumber
Or is it better to read the customer ID from the main table once and then fill in the column values several times using the update Like Below:
INSERT INTO InteresTable (CustomerId)
SELECT A.CustomerId
FROM Customer A
-----
UPDATE a
SET InterestedInbook = 1
FROM InteresTable A
JOIN BookInt B ON a.CustomerNumber = B.CustomerNumber
---
UPDATE a
SET InterestedInMovies = 1
FROM InteresTable A
JOIN MovieInt B ON a.CustomerNumber = B.CustomerNumber
---
UPDATE a
SET InterestedInMusic = 1
FROM InteresTable A
JOIN MusicInt B ON a.CustomerNumber = B.CustomerNumber
Solution 1:[1]
Though requirement is not 100% clear to me.
Second option is very neat and tidy and easy to debug. No of Sql statement never matter for performance.
Suppose a person has more than one interest then First option will fail ??
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | KumarHarsh |
