I have a table with a primary key constraint created like so:
CONSTRAINT [APP_NOTIFICATION_LOG_PK] PRIMARY KEY CLUSTERED
(
[ID] ASC
) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
I had some records in the table that I have now deleted.
I manually find the next ID to insert like so:
SELECT #maxid_log = max(ID) + 1 FROM APP_NOTIFICATION_LOG;
And then I try to insert the record:
INSERT INTO [dbo].[APP_NOTIFICATION_LOG]([ID],[COLOR],[ACTIVE],[FK_SYS_USERS_ID],[FK_APP_NOTIFICATIONS_ID], [MESSAGE],[WIN_USER_CREATOR], [FK_JOBR_RESOURCE_ID])
SELECT -- log notification created
#maxid_log,
anc.COLOR,
1,
anc.[FK_SYS_USERS_ID],
an.id,
'Notification cancelled!',
#creatorUserId,
#jobrResourceDbId
FROM [dbo].[APP_NOTIFICATIONS] an
INNER JOIN [dbo].[APP_NOTIFICATION_CONFIG] anc on anc.id = #configId
WHERE an.[FK_JOBR_RESOURCE_ID] = #jobrResourceDbId
At this stage get the error in the title. It also says that the value 5 is a dublicate. But running a select:
SELECT * FROM APP_NOTIFICATION_LOG WHERE ID = 5
...returns zero records.
What could be the problem here?
The Select is returning more than one record ?
Run it by itself and see how many rows are returned.
Your inner join returns more than just 1 result, so you try to insert several rows with same id.
Related
I am trying to add this index:
CREATE NONCLUSTERED INDEX [HE_MissingIndex]
ON [dbo].[HardwareEvents] ([PlaceId] ASC, [EventId] ASC, [UserTokenType])
INCLUDE ([Id], [EventTime], [UserToken], [Username], [UserId],
[VisitorId], [UserLastname])
WHERE (EventId = 16 AND UserTokenType = 5) OR EventId = 58
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
SORT_IN_TEMPDB = OFF, DROP_EXISTING = ON, ONLINE = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
Unfortunately, I am getting this error message:
Msg 156, Level 15, State 1, Line 16
Incorrect syntax near the keyword 'or'.
Which is kinda weird for me. I have consulted related MSDN page, an I don't see any constraint that fits here. Both columns in the filter are present in the index. The index is created without an OR in the expression. What am I missing here?
Filtered Indexes only allow AND and IN predicates, so your issue is in your WHERE clause -- you cannot use OR. You could get around this by creating two indexes:
CREATE NONCLUSTERED INDEX [HE_MissingIndex] ON [dbo].[HardwareEvents]
(
[PlaceId] ASC,
[EventId] ASC,
[UserTokenType] ASC
)
INCLUDE ( [Id],
[EventTime],
[UserToken],
[Username],
[UserId],
[VisitorId],
[UserLastname])
WHERE [EventId] = 16 and [UserTokenType] = 5
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = ON, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
CREATE NONCLUSTERED INDEX [HE_MissingIndex_2] ON [dbo].[HardwareEvents]
(
[PlaceId] ASC,
[EventId] ASC,
[UserTokenType] ASC
)
INCLUDE ( [Id],
[EventTime],
[UserToken],
[Username],
[UserId],
[VisitorId],
[UserLastname])
WHERE [EventId] = 58
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = ON, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
I have an update query:-
Update PM.Contractual_Allowances Set Provider_ID = 3 Where Tenant_ID = 1 and Carrier_ID = 203
For this above query I am getting execution plan as below :
I am trying to understand that why do I get the sort operator when I dont have an ORDER BY clause and what I can do to avoid it.
Below is the plan in text (aka 'Showplan_text'):
|--Sequence
|--Index Update(OBJECT:([Ntier_Master].[PM].[Contractual_Allowances].[IX_Contractual_Allowances_Provider_ID_Tenant_ID]), SET:([Contractual_Allowance_ID1043] = [Ntier_Master].[PM].[Contractual_Allowances].[Contractual_Allowance_ID],[Provider_ID1044] = [Ntier_Master].[PM].[Contractual_Allowances].[Provider_ID],[Tenant_ID1045] = [Ntier_Master].[PM].[Contractual_Allowances].[Tenant_ID]) WITH ORDERED PREFETCH ACTION:([Act1042]))
| |--Sort(ORDER BY:([Ntier_Master].[PM].[Contractual_Allowances].[Provider_ID] ASC, [Ntier_Master].[PM].[Contractual_Allowances].[Tenant_ID] ASC, [Ntier_Master].[PM].[Contractual_Allowances].[Contractual_Allowance_ID] ASC, [Act1042] ASC))
| |--Filter(WHERE:(NOT [Expr1038]))
| |--Table Spool
| |--Split
| |--Clustered Index Update(OBJECT:([Ntier_Master].[PM].[Contractual_Allowances].[PK_Contractual_Allowances_Contractual_Allowance_ID]), SET:([Ntier_Master].[PM].[Contractual_Allowances].[Provider_ID] = [Expr1033],[Ntier_Master].[PM].[Contractual_Allowances].[Contractual_Allowance_TS] = [Expr1003]))
| |--Compute Scalar(DEFINE:([Expr1038]=[Expr1038], [Expr1039]=[Expr1039]))
| |--Compute Scalar(DEFINE:([Expr1038]=CASE WHEN [Expr1007] THEN (1) ELSE (0) END, [Expr1039]=CASE WHEN [Expr1007] THEN (1) ELSE (0) END))
| |--Compute Scalar(DEFINE:([Expr1033]=(3)))
| |--Compute Scalar(DEFINE:([Expr1007]=CASE WHEN [Ntier_Master].[PM].[Contractual_Allowances].[Provider_ID] = (3) THEN (1) ELSE (0) END))
| |--Compute Scalar(DEFINE:([Expr1003]=gettimestamp((10))))
| |--Clustered Index Scan(OBJECT:([Ntier_Master].[PM].[Contractual_Allowances].[PK_Contractual_Allowances_Contractual_Allowance_ID]), WHERE:([Ntier_Master].[PM].[Contractual_Allowances].[Tenant_ID]=(1) AND [Ntier_Master].[PM].[Contractual_Allowances].[Carrier_ID]=(203)) ORDERED FORWARD)
|--Index Update(OBJECT:([Ntier_Master].[PM].[Contractual_Allowances].[IX_Contractual_Allowances_Carrier_ID_Location_ID_Department_ID_Tenant_ID]), SET:([Contractual_Allowance_ID1046] = [Ntier_Master].[PM].[Contractual_Allowances].[Contractual_Allowance_ID],[Modifiers1047] = [Ntier_Master].[PM].[Contractual_Allowances].[Modifiers],[Carrier_ID1048] = [Ntier_Master].[PM].[Contractual_Allowances].[Carrier_ID],[Procedure_Code_ID1049] = [Ntier_Master].[PM].[Contractual_Allowances].[Procedure_Code_ID],[Location_ID1050] = [Ntier_Master].[PM].[Contractual_Allowances].[Location_ID],[Provider_ID1051] = [Ntier_Master].[PM].[Contractual_Allowances].[Provider_ID],[Department_ID1052] = [Ntier_Master].[PM].[Contractual_Allowances].[Department_ID],[Tenant_ID1053] = [Ntier_Master].[PM].[Contractual_Allowances].[Tenant_ID]) WITH ORDERED PREFETCH ACTION:([Act1042]))
|--Sort(ORDER BY:([Ntier_Master].[PM].[Contractual_Allowances].[Carrier_ID] ASC, [Ntier_Master].[PM].[Contractual_Allowances].[Location_ID] ASC, [Ntier_Master].[PM].[Contractual_Allowances].[Department_ID] ASC, [Ntier_Master].[PM].[Contractual_Allowances].[Tenant_ID] ASC, [Ntier_Master].[PM].[Contractual_Allowances].[Contractual_Allowance_ID] ASC, [Act1042] ASC))
|--Filter(WHERE:(NOT [Expr1039]))
|--Table Spool
CREATE NONCLUSTERED INDEX IX_Contractual_Allowances_Location_ID_Tenant_ID ON PM.Contractual_Allowances ( Location_ID ASC , Tenant_ID ASC ) WITH ( PAD_INDEX = OFF ,FILLFACTOR = 100 ,SORT_IN_TEMPDB = OFF , IGNORE_DUP_KEY = OFF , STATISTICS_NORECOMPUTE = OFF , DROP_EXISTING = ON , ONLINE = OFF , ALLOW_ROW_LOCKS = ON , ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY ]
CREATE NONCLUSTERED INDEX IX_Contractual_Allowances_Provider_ID_Tenant_ID ON PM.Contractual_Allowances ( Provider_ID ASC , Tenant_ID ASC ) WITH ( PAD_INDEX = OFF ,FILLFACTOR = 100 ,SORT_IN_TEMPDB = OFF , IGNORE_DUP_KEY = OFF , STATISTICS_NORECOMPUTE = OFF , DROP_EXISTING = ON , ONLINE = OFF , ALLOW_ROW_LOCKS = ON , ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY ]
CREATE NONCLUSTERED INDEX IX_Contractual_Allowances_Carrier_ID_Current_Effective_Date_Tenant_ID ON PM.Contractual_Allowances ( Carrier_ID ASC , Current_Effective_Date ASC , Tenant_ID ASC ) WITH ( PAD_INDEX = OFF ,FILLFACTOR = 100 ,SORT_IN_TEMPDB = OFF , IGNORE_DUP_KEY = OFF , STATISTICS_NORECOMPUTE = OFF , DROP_EXISTING = ON , ONLINE = OFF , ALLOW_ROW_LOCKS = ON , ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY ]
CREATE NONCLUSTERED INDEX IX_Contractual_Allowances_Carrier_ID_Location_ID_Department_ID_Tenant_ID ON PM.Contractual_Allowances ( Carrier_ID ASC , Location_ID ASC , Department_ID ASC , Tenant_ID ASC ) INCLUDE ( Modifiers , Procedure_Code_ID , Provider_ID ) WITH ( PAD_INDEX = OFF ,FILLFACTOR = 100 ,SORT_IN_TEMPDB = OFF , IGNORE_DUP_KEY = OFF , STATISTICS_NORECOMPUTE = OFF , DROP_EXISTING = ON , ONLINE = OFF , ALLOW_ROW_LOCKS = ON , ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY ]
CREATE NONCLUSTERED INDEX IX_Contractual_Allowances_Procedure_Code_ID_Tenant_ID ON PM.Contractual_Allowances ( Procedure_Code_ID ASC , Tenant_ID ASC ) WITH ( PAD_INDEX = OFF ,FILLFACTOR = 100 ,SORT_IN_TEMPDB = OFF , IGNORE_DUP_KEY = OFF , STATISTICS_NORECOMPUTE = OFF , DROP_EXISTING = ON , ONLINE = OFF , ALLOW_ROW_LOCKS = ON , ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY ]
ORDER BY clauses are not the only thing that cause a sort. GROUP BY, DISTINCT, window ranking functions (e.g. ROW_NUMBER, RANK), window aggregate functions (e.g. SUM() OVER (PARTITION BY ...), window frame functions (e.g. LAG and LEAD) are among many things that cause a sort.
When we add indexes we're pre-sorting data so that it does not need to be sorted when queried. Sorts in the exectution plan mean that (1) there was not an index available to handle the sort or (2) the was an index that could handle the sort but the optimizer chose not to use it. Consider the following sample data:
if object_id('tempdb..#sometable') is not null drop table #sometable;
create table #sometable (col1 int, col2 int);
insert #sometable values(1,10),(1,20),(2,15),(2,50),(3,10);
Next, run these queries with "Include Actual Execution Plan" turned on.
select col1, max(col2)
from #sometable
group by col1;
select distinct col1
from #sometable;
select col1, col2, avg(col2) over (partition by col1)
from #sometable;
select col1, col2, avg(col2) over (partition by col1 order by (select null))
from #sometable;
Note the execution plans:
You can get more info about what was sorted by holding the mouse over the sort operator:
Here it's it needs to sort col1 so let's add this index, run the queries and examine the execution plan:
--alter table #sometable
create clustered index uq_sometable on #sometable(col1);
Now the new execution plans:
As you can see, the sorts are all gone. There's so much more to this topic but hopefully this helps you understand how you can get sorts without an ORDER BY and how to get rid of them.
I would like to select data from two columns, both of similar length(#fetch) but at a certain offset in the same table.
However off the bat I am running into syntax errors.I would prefer a join solution for this. Thanks.
SELECT c.[Close],h.[High]
FROM
(
SELECT [Close],[CityID],[Time]
FROM [dataSQL].[dbo].[temperature]
WHERE [Time]<#time
ORDER BY [Time] DESC
OFFSET 0 ROWS
FETCH NEXT (#fetch) ROWS ONLY
) AS c
JOIN
(
SELECT [High],[CityID],[Time]
FROM [dataSQL].[dbo].[temperature]
WHERE [Time]<#time
ORDER BY [Time] DESC
OFFSET (#offset) ROWS
FETCH NEXT (#fetch) ROWS ONLY
) AS h
ON c.[CityID]=h.[CityID] AND c.[Time]=h.[Time]
WHERE c.[CityID]=#name AND h.[CityID]=#name;
EDIT:
This is now returning more than expected results with repetitions in both columns
EDIT:
This now returns columns that are in same row without offset because I required primary keys to match! There has to be an offset and the problem is this table contains data for more than two cities so you cannot use ROW_NUMBER()!
Here is my table schema:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Temperature](
[Time] [datetime] NOT NULL,
[CityID] [tinyint] NOT NULL,
[High] [real] NULL,
[Close] [real] NULL,
CONSTRAINT [pk_time_cityid] PRIMARY KEY CLUSTERED
(
[Time] ASC,
[CityID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Temperature] WITH CHECK ADD CONSTRAINT [FK_Temperature_Cities] FOREIGN KEY([CityID])
REFERENCES [dbo].[Cities] ([CityID])
GO
ALTER TABLE [dbo].[Temperature] CHECK CONSTRAINT [FK_Temperature_Cities]
GO
Keep in mind you can edit your question to correct your query.
In addition to OFFSET 0 ROWS and FETCH NEXT (...) ROWS ONLY issues, you need to use SELECT [CityID],[Close] and SELECT [CityID],[High] in your subqueries respectively. The only fields from a subquery that are available outside the subquery are those you explicitly specify. That includes JOIN conditions.
Regarding your comment that you're getting the number of rows you expect squared, you've probably got an implicit cross join that's creating a Cartesian product. You need to join your tables using the fields in the primary key of dbo.temperature. Try adding some sample data to your question and possibly the table schema.
How can I get the cartesian product of two columns in one table?
I have table
A 1
A 2
B 3
B 4
and I want a new table
A 1
A 2
A 3
A 4
B 1
B 2
B 3
B 4
fiddle demo
your table
try this using joins
select distinct b.let,a.id from [dbo].[cartesian] a join [dbo].[cartesian] b on a.id<>b.id
will result like this
Create this table :
CREATE TABLE [dbo].[Table_1]
(
[A] [int] NOT NULL ,
[B] [nvarchar](50) NULL ,
CONSTRAINT [PK_Table_1] PRIMARY KEY CLUSTERED ( [A] ASC )
WITH ( PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY]
)
ON [PRIMARY]
Fill table like this :
INSERT INTO [dbo].[Table_1]
VALUES ( 1, 'A' )
INSERT INTO [dbo].[Table_1]
VALUES ( 2, 'A' )
INSERT INTO [dbo].[Table_1]
VALUES ( 3, 'B' )
INSERT INTO [dbo].[Table_1]
VALUES ( 4, 'C' )
SELECT *
FROM [dbo].[Table_1]
Use this query
SELECT DISTINCT
T1.B ,
T2.A
FROM dbo.Table_1 AS T1 ,
dbo.Table_1 AS T2
ORDER BY T1.B
To clarify loup's answer (in more detail that allowable in a comment), any join with no relevant criteria specified will naturally produce a Cartesian product (which is why a glib answer to your question might be "all too easily"-- mistakenly doing t1 INNER JOIN t2 ON t1.Key = t1.Key will produce the same result).
However, SQL Server does offer an explicit option to make your intentions known. The CROSS JOIN is essentially what you're looking for. But like INNER JOIN devolving to a Cartesian product without a useful join condition, CROSS JOIN devolves to a simple inner join if you go out of your way to add join criteria in the WHERE clause.
If this is a one-off operation, it probably doesn't matter which you use. But if you want to make it clear for posterity, consider CROSS JOIN instead.
INSERT INTO contacts_lists (contact_id, list_id)
SELECT contact_id, 110689 AS list_id
FROM plain_contacts
WHERE TRUE
AND is_print = TRUE
AND ( ( TRUE
AND country_id IN (231,39)
AND company_type_id IN (2,8,12,5,6,4,3,9,10,13,11,1,7)
AND is_broadcast = TRUE )
OR ( TRUE
AND country_id IN (15,59,73,74,81,108,155,165,204,210,211,230)
AND company_type_id IN (2,8,12,5,6,4,3,9,10,13,11,1,7)
AND is_broadcast = TRUE )
OR ( TRUE
AND country_id IN (230)
AND company_type_id IN (2,8,12,5,6,4,3,9,10,13,11,1,7)
AND is_broadcast = TRUE ))
AND (NOT EXISTS (
SELECT title_id
FROM company_types_lists_titles
WHERE company_types_list_id = 92080)
OR title_id IN (
SELECT title_id
FROM company_types_lists_titles
WHERE company_types_list_id = 92080))
AND company_type_id = 2
AND country_id IN (
SELECT country_id
FROM countries_lists
WHERE list_id = 110689)
AND ((state_id IS NULL
OR country_id NOT IN (231,39)
OR state_id IN (
SELECT state_id
FROM lists_states
WHERE list_id = 110689))
OR zone_ids && ARRAY(
SELECT zone_id
FROM lists_zones
WHERE list_id = 110689)
)
AND (NOT EXISTS (
SELECT award_id
FROM company_types_lists_top_awards
WHERE company_types_list_id = 92080)
OR top_award_ids && ARRAY(
SELECT award_id
FROM company_types_lists_top_awards
WHERE company_types_list_id = 92080))
I have using postgresql which selects 30000 rows from various tables which takes lessthan a second to select data from various tables. But after selecting data which take more and more time to insert in another table. how to reduce the time insert. This is the query i have. In this the select query give nearly 30000 thousand records.
take more and more time to insert
That usually means you're missing an index.
Edit: now that you've posted the query... Definitely missing one or more indexes to speed up lookups during the insert. And you probably want to rewrite that huge select statement so as to reduce nesting.
If no other people (threads) are meanwhile working with the target table, you could drop the indexes for the table, insert the data, and recreate the indexes later.
This may lead to a speed up, and might be considered, if your data is reliable, and you can guarantee, that you won't violate unique-restrictions.