Over the years I've read and experienced where joining more then 5 tables can lead to performance problems. This number can vary based upon the amount of data in each table, if and how indexes are used and the complexity of the query, but 5 has always been a good rule of thumb. Unfortunately I do not know what rule to apply in regards to joing views.
A developer has experienced timeout problems periodically when opening a view in EM or when running the code which makes-up the view. I decided to look at the view and noticed it references tables and views, which reference more views, which in turn reference other views. In all the initial view references 5 tables and 8 views directly and indirectly, with some of the views containing function calls. What are your thoughts on how many views and tables are too many when it comes to joins and query performance.
Ok, What I want to achieve is plain stuff, I want to join 2 views on a common key.It all works well with the SQL2000 Query Analyzer, but not trough ADO.NET or should I say my webapplication.With that I mean that my query return rows when executed from SQL2000 Query Analyzer, But not when used in my application or Executed from the Visual Studio Server Explorer.I have struggled with this one for several hours, I cant get this one right.So lets bring in the one who actually know what his doing View1: 1 select 2 cast((PS.RabattProsent/100.00)*PS.Pris AS decimal(11,2)) AS Rabatt 3 ,cast((PS.MVAProsent/100.00)*PS.Pris AS decimal(11,2)) AS MVA 4 ,cast(PS.Antall * ((PS.Pris*(100-PS.RabattProsent))/100)*((PS.MvaProsent/100.00)+1) AS decimal(11,2)) AS Belop 5 ,PS.* 6 ,K.Kunde_ID 7 FROM 8 tbl_ProduktSalg AS PS 9 INNER JOIN 10 tbl_Ordre AS O 11 ON 12 O.Ordre_ID = PS.Ordre_ID 13 INNER JOIN 14 tbl_Kunde AS K 15 ON 16 K.Kunde_ID = O.Kunde_IDView2: 1 SELECT 2 PS.Ordre_ID 3 ,SUM(cast((PS.RabattProsent/100.00)*PS.Pris AS decimal(11,2))) AS TotalRabatt 4 ,SUM(cast(PS.Antall * ((PS.Pris*(100-PS.RabattProsent))/100)*((PS.MvaProsent/100.00)+1) AS decimal(11,2))) AS TotalBelop 5 ,SUM(PS.Pris) AS TotalPris 6 ,SUM(cast((PS.MVAProsent/100.00)*PS.Pris AS decimal(11,2))) AS TotalMVA 7 FROM 8 tbl_ProduktSalg AS PS 9 GROUP BY 10 PS.Ordre_ID MyQuery/SPRC: 1 create procedure %PROC% (@Kunde_ID int, @Ordre_ID int) 2 as 3 begin 4 SELECT 5 v_PSD.* 6 ,v_OTS.TotalRabatt 7 ,v_OTS.TotalBelop 8 ,v_OTS.TotalPris 9 ,v_OTS.TotalMVA 10 FROM 11 v_ProduktSalgDetaljer AS v_PSD 12 INNER JOIN 13 v_OrdreTotalSum AS v_OTS 14 ON 15 v_OTS.Ordre_ID = v_PSD.Ordre_ID 16 WHERE 17 v_PSD.Kunde_ID = @Kunde_ID 18 AND 19 v_PSD.Ordre_ID = @Ordre_ID 20 21 end 22
When working with databases containing myriad of huge tables, I am very much tempted to create categorized views on those tables in order to simplify and facilitate data query programming? Some developers I talk to say such views generally slow down query performance. Is this true? Thanks.
I have come across this problem with SQL server both on 2000 and 2005. I am stating an example here.
I have two partitioned tables and a view on top of both tables as below: create table [dbo].[Table_1] ( [TableID] INTEGER PRIMARY KEY NONCLUSTERED CHECK NOT FOR REPLICATION ([TableID] BETWEEN 1 AND 999), [AnyOtherColumn] int NOT NULL , ) ON [Primary] GO
create table [dbo].[Table_2] ( [TableID] INTEGER PRIMARY KEY NONCLUSTERED CHECK NOT FOR REPLICATION ([TableID] BETWEEN 1000 AND 1999), [AnyOtherColumn] int NOT NULL , ) ON [Primary] GO create view TableView as select * from Table_1 union all select * from Table_2 GO
Note the NOT FOR REPLICATION clause on the check constraint on the TableID column.
I then ran the query execution plan for the following query on both SQL server 2000 and 2005. select * from TableView where TableID = 10
On both the versions the execution plan shows and Index seek on both the tables in the view. This means that my partitioning is not working. If I remove the primary key constraint from the TableID column, the same query on the view shows a table scan on all the underlying tables. This is even worse.
Next, create the same tables and views again, now without the NOT FOR REPLICATION clause on the check constraint as show below: create table [dbo].[Table_1] ( [TableID] INTEGER PRIMARY KEY NONCLUSTERED CHECK ([TableID] BETWEEN 1 AND 999), [AnyOtherColumn] int NOT NULL , ) ON [Primary] GO
create table [dbo].[Table_2] ( [TableID] INTEGER PRIMARY KEY NONCLUSTERED CHECK ([TableID] BETWEEN 1000 AND 1999), [AnyOtherColumn] int NOT NULL , ) ON [Primary] GO
create view TableView as select * from Table_1 union all select * from Table_2 GO
Now run the query execution plan for the same query again.
select * from TableView where TableID = 10
This time you would see that it does an index scan only on the first parititon table. This time it proves that the partitioning works.
I would like to know why does the NOT FOR REPLICATION clause in the check constraint make such a huge difference?
Hi, I am new to sql and I am trying to join 2 views using MySQL Query Browser. Here is my query and the issues I am having.
SELECT book_month, region_book, product_group as base_prod_group, cnt as base_cnt FROM collections.v_nonpay_trend_base a join collections.v_nonpay_trend_npdata b on (a.book_month=b.disc_check_in_month and a.region_book=b.region and a.base_prod_group=b.product_group)
Error - "Column 'product_group' in field list is ambiguous" and "Column 'cnt' in field list is ambiguous"
Both views have columns named 'product_group' and 'cnt'
Can someone please let me know what I am doing wrong?
create view myidtitlenew as SELECT c1.messageid_, c1.title_, c1.list_, c1.created_ FROM outmail_ c1 inner join (Select max(messageid_) as messageid_, max(title_) as title_ FROM outmail_ c1 where list_ = 'copd' GROUP BY substring([title_],1,charindex(' ',[title_])-1) ) c2
ON c1.messageid_ = c2.messageid_ go
create view mymembersum as select distinct list_, membertype_ , count(*) as cnt from Members_ where list_='copd' group by membertype_,list_ go
I have 2 views that I can join to give me the recordset I want. Both views are currently filtered on a particular column (ie 'WHERE colName = myValue')
The problem is that I want to use this from a web page with user input in which the user would specify myValue.
Is there any alternative to having two views? Can I combine them into one SQL statement? Access allowed me to do it by specifying an alias for a select statement, then joining this to another. I'm not sure if that makes sense, but I guess what I want to do it specify one view then another, then join them - all in the same statement!
Something like this:
Code:
SELECT view1.*, view2.* FROM ((SELECT tbl1.*,tbl2.*,tbl3.* FROM tbl1 JOIN tbl2 ON tbl1.id = tbl2.tbl1_id JOIN tbl3 ON tbl2.id = tbl3.tbl2_id AND tbl3.id = myValue) AS view1) ((SELECT tbl4.* FROM tbl4 WHERE tbl4.id = myValue) AS view2) RIGHT JOIN view1 ON view2....
Hi guys,I detected a strange behaviour when doing an inner join of two views.There is table_Objects, table_Contracts and view_Objects, View_Contracts.Table_Objects: ID, PriceView_Objects: Select * from Table_Objects Where Price > 10Table_Contracts: ID, YearView_Contracts: Select c.ID, c.YearFrom Table_Contracts c Join View_Objects o on c.id=o.idQuiete simple so far, but it doesn't work. Imagine Object with id 3 that is shown in View_Objects and Table_Contracts but not shown in View_Contracts. How is that possible?EDIT: Sometimes its shown, sometimes notThx for your reply!
I am new to programming trying hard to learn. I made a code for Views in mssql for the 2 tables below:I am wondering if I could make it 3, 4 or more tables at the same time. How can incorporate in the following codes I made.
Create View vwEmployeeInfoByGender as Select FirstName, MiddleName, FamilyName, Gender, BirthDate, MaritalStatus from tblEmployeeInfo join tblGender on tblEmployeeInfo.GenderID = tblGender.GenderID
I have two databses SIS and SIS_Pro. Users tables should be used in both of them because I have some relations between this table with other table in SIS and SIS_Pro. Users in SIS only have one column and it is the UserId which is the primary Key in both of them, but in SIS_Pro Users table have Firstname Lastname and... now. In my program I need some informatin from SIS and some from SIS_Pro so I create a view which is joining of forexample exam in SIS and Users in SIS_Parnian, becuase I don't have the firstname and lastname in a Users table which is in SIS_Pro databse.Does it reduce the performance?is it better to copy datas which are in Users in SIS to Users in SIS_Pro( I mean all columns firstname, lastname ,,.....)
I'm currently using a system where the number of column in any given table is so great that the columns are often split into additonal tables. I know it's a wierd design but there you go. So I have to deal with tables looking like: MathResult, MathResult_2, MathResult_3, etcEach table is basically the same entity, i.e. it has the same number of rows and each row has the same key value as its peer tables. My question is that should I create a view to bring the tables together, given that a View doesn't seem to have any sort of row-size restriction? Normally I shy away from Views because I've always found them to bring performance down. Any thoughts?
I want to use VIEWS to filter records using a stored procedure to call the VIEW. Will I get a performance boost from using a VIEW, or should I just use the SQL statement that I used to create the VIEW, in my SP and forget about calling a VIEW at all?
I have a query which retrieves data from 4-5 tables. To restrict the acess directly to the tables, views have been created on all these tables. These views are just select * from the tables. Two of these 5 tables have 700 Million and 8 Million rows respectively. And all the tables are having indexes. My issue here is that my query on views take three times more then the duration it takes to retrive data directly from tables. e.g. To retrieve 1 Miliion rows, it takes just 7-10 minutes on tables but on views it takes more than 30 minutes. When I check the query plan for both the options, I can see that indexes are being picked up but still the views are very slow.
Creating indexes on views is not feasible option for me as it requires DDL changes and so much testing efforts.
I'm have a table which is filled daily by a procedure. This procedure executes for around 2 hours. Now i also want to create a clustered index view on this table.
Now during the time data is being inserted in this table, would the performance of server get hit.? Since it think it would continiously be updating this view during this duration.
Is there a way i can temporarily disconnect the view?
OK so I have this EAV system on a server that is old enough for kindergarten. Insanely enough, this company that makes more money than any of your gods can not buy me a new box.
Before you say "redesign", I need funding allocated for that. See my first statement.
Anywho, I have this page that touches the dreaded Value table and does a clustered index seek on it. Can't search faster than that, right? Well I am getting some funding for "performance tuning". I am wondering if maybe incorporating some clustered index views involving the value table and producing a smaller clustered index for it to seek may alleviate some of this. Any thoughts?
Dear All, i've tried with indexed views, but because the view is referenceing another view, i was unable to create a clustered index on that view. so please let me know how can i improve the performance of the view.
thank you very much
Vinod Even you learn 1%, Learn it with 100% confidence.
I posted this same question couple of times in the news groups but no answers. I have a 2 tables and i am doing a union query using a view. each has 250 rows. The query takes 20 seconds to return the results. no joins or anything. the create view simply looks like this:
create view myview as select id, name from table1 union select id,name from table2
Where as if i write a stored procedure like below, it returns the rows in 4 seconds. create table #mytable ( id int, name varchar(30)) insert into #mytable (id, name) select id, name from table1 insert into #mytable (id, name) select id, name from table2 select id,name from #mytable.
I prefer doing in the view since both returns the same result. I tried running dbcc, update statistics. but no luck. Can anyone please help me in this issue.
I wonder if anyone has any hard fact based pro or contra, especially onperformance, about having views as opposed to tables when the object isbeing accessed for read only by multiple sessions/users/spids. I amparticularly concerned about the multiple instantiations of the view.Relevant thoughts on this are much appreciated.Thanks,Caveman
The code below is from a nested view, which I've read should be avoided. I've also noticed GETDATE() is used, which I believe causes GETDATE() to be executed for every record selected (correct me if I'm wrong). I'm also guessing a JOIN containing a UNION against a SELECT statement is not a good idea. What other problems do you notice?
SELECT trans.Entry_Code, trans.D_C, trans.ADP_Security_# , trans.TRID, trans.Batch_Code, trans.Last_Money, null as Shares, Settle_date as Process_Date, null as Closing_Price, trans.Dwnld_Date, trans.Acnt, null as Mktval, cast(Null as varchar(20)) as Cusip_#, ACT.dbo.account.account_key AS account_key FROM (SELECT * FROM ADPDBBOOK.dbo.YTD05B WHERE (DATEDIFF(mm, Process_Date, GETDATE()) <= 15) UNION SELECT * FROM ADPDBBOOK.dbo.YTD06B) trans INNER JOIN ACT_DATA.dbo.account ON ACT_DATA.dbo.account.account_key = RIGHT(trans.Acnt, 5) INNER JOIN tbl_Accounts_TransactionalData ON trans.Acnt = tbl_Accounts_TransactionalData.Acnt
Hello Everyone,I have a very complex performance issue with our production database.Here's the scenario. We have a production webserver server and adevelopment web server. Both are running SQL Server 2000.I encounted various performance issues with the production server with aparticular query. It would take approximately 22 seconds to return 100rows, thats about 0.22 seconds per row. Note: I ran the query in singleuser mode. So I tested the query on the Development server by taking abackup (.dmp) of the database and moving it onto the dev server. I ranthe same query and found that it ran in less than a second.I took a look at the query execution plan and I found that they we'rethe exact same in both cases.Then I took a look at the various index's, and again I found nodifferences in the table indices.If both databases are identical, I'm assumeing that the issue is relatedto some external hardware issue like: disk space, memory etc. Or couldit be OS software related issues, like service packs, SQL Serverconfiguations etc.Here's what I've done to rule out some obvious hardware issues on theprod server:1. Moved all extraneous files to a secondary harddrive to free up spaceon the primary harddrive. There is 55gb's of free space on the disk.2. Applied SQL Server SP4 service packs3. Defragmented the primary harddrive4. Applied all Windows Server 2003 updatesHere is the prod servers system specs:2x Intel Xeon 2.67GHZTotal Physical Memory 2GB, Available Physical Memory 815MBWindows Server 2003 SE /w SP1Here is the dev serers system specs:2x Intel Xeon 2.80GHz2GB DDR2-SDRAMWindows Server 2003 SE /w SP1I'm not sure what else to do, the query performance is an order ofmagnitude difference and I can't explain it. To me its is a hardware oroperating system related issue.Any Ideas would help me greatly!Thanks,Brian T*** Sent via Developersdex http://www.developersdex.com ***
I know how to join 2 tables, but I have a third I need to insert. For some reason, this doesn't work:
Code:
$rows = ff_select( "select ". "u.email as email, ". "c.user_id as user_id, ". "u.name as name, ". "r.age as age ". "from #__comprofiler as c ". "left join #__users as u on c.user_id = u.id ". "left join #__rnr_contest as r on c.user_id = r.userid ". "where (r.age != chicken) and (r.age != nystrip) and (r.age != regrets) and (u.block = 0) and (c.cb_contactmethod LIKE '%Email%') and (u.usertype != 'Super Administrator') and (u.email != 'please@change.com') and (u.username != 'guest') and (u.username != 'piedmont') ". "order by email"
anyone see why? It tells me that "chicken" is not a column which is weird because I don't think it's listed as a column in my query... is it?
First off sorry for my complete lack of experience with SQL, but I've just started a new position which involved learning SQL. I'm currently looking for a course but in the mean time I just have to try and fumble by doing basic things.
I'm trying to write my first basic select / join statement, and I just can't seem to get it working.
Any help would really be appreciated. It's T-SQL we use btw.
Thanks :)
USE MLSDHeat GO
select * from dbo.CallLog where callstatus between 'open'and 'pending' right outer join dbo.Asgnmnt on callid = callid order by callid
--the above returns error Msg 156, Level 15, State 1, Line 4 Incorrect syntax near the keyword 'right'.
CREATE FUNCTION dbo.fn_copdmailinglist(@list_ varchar(60)) RETURNS @copdmailinglist TABLE ( list_ varchar(60) , title_ varchar(255) , desc_ varchar(255), message_id int , txt varchar(255) , cnt int , cnt_txt varchar(255) )
--Returns a result set that lists all the copds AS BEGIN WITH ListManager.dbo.[List Copd](list_ , title_ , message_id , txt , cnt , cnt_txt ) AS (select @list_ , gmc.name_, osc.message_id , txt , cnt , cnt_txt from ListManager.dbo.[Open statisticscopd]('') osc left outer join ListManager.dbo.get_mailingidcopd_('') gmc on gmc.name_ = osc.title_ where list_ = @list_ )
-- copy the required columns to the result of the function INSERT @copdmailinglist SELECT list_ , title_ , message_id , txt , cnt , cnt_txt FROM ListManager.dbo.[List Copd] RETURN END GO
i m getting error that Incorrect syntax near the keyword 'WITH'.
Select LOCGeneralHave.LSCH, LOCSubClassHave.LSCH from LOCGeneralHave ,LOCSubClassHave Where (LOCGeneralHave.LCNT <> '0' andLOCSubClassHave.LCNT = '0')This query seems to be ignoring the 'and' part of the clause.Basically I want select from table1, table2 where LCNT in table1 is not0 andLCNT in table2 is 0.I have verified the LCNT's numbersThis query returns 2 columns with 1700 rowsIt needs to only find a few rows.What am I missing, any ideas, thanks for any help.
Two tables:T1 (c1 int, TestVal numeric(18,2), ResultFactor numeric(18,2))--c1 isthe primary key.T2 (x1 int, FromVal numeric(18,2), ToVal numeric(18,2), Factornumeric(18,2))--x1 is the primary key. T2 contains non-overlappingvalues. So for eg., a few rows in T2 may look like.1, 51, 51.999, 512, 52, 52.999, 52........32, 82, 82.999, 82........T2 is basically a lookup table. There is no relationship between thetwo tables T1 and T2. However, if the TestVal from T1 falls in therange between FromVal and ToVal in T2, then I want to updateResultFactor in T1 with the corresponding value of Factor from the T2table.------Example for illustration only---------------Even though tables cannot be joined using keys, the above problem is avery common one in our everyday life. For example T1 could beemployees PayRaise table, c1=EmployeeID, with "TestVal" representingtest scores (from 1 to 100). T2 representing lookup of the ranges,with "Factor" representing percent raise to be given to the employee.If TestVal is 65 (employee scored 65% in a test), and a row in T2(FromVal=60, ToVal=70, Factor=12), then I would like to update 12 intable T1 from T2 using sql;. Basically T2 (like a global table)applies to all the employees, so EmpID cannot serve as a key in T2.---------------------------------------------------------Could anyone suggest how I would solve MY PROBLEM using sql? I wouldlike to avoid cursors and loops.Reply appreciated.Thanks
Sorry for the akward title, not sure how to say this. I have a Person table and a addresses table. Each person may have many address records as shown below:
Addresses --------------- addressID | AutoNum personID | int (FK) address1 | varchar city | varchar state | varchar isPrimary | bit ...etc
What I'm trying to do is select all from Person and the city and state of each person's primary address. A little voice keeps saying subquery...but I can't figure it out. So far I have the SQL below, but if there is no address or no address where isPrimary = 1, it fails to return the person record. I need the person record regardless of if they have a primary address. Does that make sense?
Doesn't return all Person records:
SELECT Person.*, Address.City, Address.State FROM Person LEFT OUTER JOIN Address ON Person.PersonID = Address.PersonID WHERE (Address.isPrimary= 1) ORDER BY Person.lName, Person.fName
I am having the following situation - there is a view that aggregates and computes some values and a table that I need the details from so I join them filtering on the primary key of the table. The execution plan shows that the view is executed without any filtering so it returns 140 000 rows which are later filtered by the join operation a hash table match. This hash table match takes 47% of the query cost. I tried selecting the same view but directly giving a where clause without the join €“ it gave a completely different execution plan. Using the second method is in at least 4 folds faster and is going only through Index Seeks and nested loops. So I tried modifying the query with third version. It gave almost the same execution plan as the version 1 with the join operation. It seams that by giving the where clause directly the execution plan chosen by the query optimizer is completely different €“ it filters the view and the results from it and returns it at the same time, in contrast to the first version where the view is executed and return and later filtered. Is it possible to change the query some how so that it filters the view before been joined to the table.
Any suggestions will be appreciated greatly Stoil Pankov
"vHCItemLimitUsed" - this is the view "tHCContractInsured" - this is the table "ixHCContractInsuredID" - is the primary key of the table
Here is a simple representation of the effect:
Version 1: select * from dbo.vHCItemLimitUsed inner join tHCContractInsured on vHCItemLimitUsed.ixHCContractInsuredID = tHCContractInsured.ixHCContractInsuredID where tHCContractInsured.ixHCContractInsuredID in (9012,9013,9014,9015)
Version 2: select * from vHCItemLimitUsed where ixHCContractInsuredID in (9012,9013,9014,9015)
Version 3: select * from dbo.vHCItemLimitUsed where ixHCContractInsuredID in (select ixHCContractInsuredID from tHCContractInsured where ixHCContractInsuredID in (9012,9013,9014,9015))
In database DB1, I have table DB1.dbo.Suppliers1. This table has an ID column of type INT named SUPPL1_ID
In database DB2, I have table DB2.dbo.Suppliers2. This table has an ID column of type INT named SUPPL2_ID I would like to update DB2.dbo.Suppliers2 based on values from DB1.dbo.Suppliers1 joining on SUPPL1_ID = SUPPL2_ID.
How can I do this in SSIS?
Assumptions:
linked servers are not an option, as I want the SSIS package to be portable and not dependent on server environments. TIA.
I am learning the Optimizer from the book "Querying Microsoft SQL Server 2012" for certificate exam 70-461. I really cannot understand how it explains the number of possible ways to execute a query joining three tables. the pseudo-query is:
SELECT A.col5, SUM(C.col6) AS col6sum FROM TableA AS A INNER JOIN TableB AS B ON A.col1 = B.col1 INNER JOIN TableC AS C ON B.col2 = c.col2 WHERE A.col3 = constant 1 AND B.col4 = constant2 GROUP BY A.col5;
The book says:"Start with the FROM part. Which tables should SQL Server join first, TableA and TableB or TableB and TableC? And in each join, which of the two tables joined should be the left and which one the right table? The number of all possibilities is six, if the two joins are evaluated linearly, one after another."
Q1: How could it be six possibilities? From my understanding, lets say, if the SQL Server has to join A and B first, and then join C, in this case I can think of 4 possibilities, which are:
1. When A Join B, Left: A, Right: B. Â Â When Join C, Left: result of A join B, Right: C
2. When A Join B, nbsp;  When Join C, nbsp;When A Join B, nbsp;  When Join C, nbsp;When A Join B, nbsp;   When Join C, "line-height:13.5px;">
Q2:Â The section following the previous question says there are 4 different types of join.."This already gives four options for each join. So far, there are 6 x 4 = 24 different options for only the FROM part of this query."
How can it be 6 x 4? My understanding is 4 is only for 1 join, but in our case, there are 2 joins, so it should be 6 x 4 x 4.