r/SQLServer • u/punctuationuse • Jul 25 '25
Performance Best strategy for improving cursor paginated queries with Views
Hey,
Im using MSSQL, and need to execute a search on a single table.
Problem is, we have to search also in fields of related tables. (For example, execute a LIKE query on User table, and on the Posts table, etc; Find users whose Posts, Tags, Settings, have a certain search term) in a single trip.
I’m using Prisma ORM, and the performance was horrendous when searching on the related tables. To solve this I:
- Created a “FlatUsers” View which just joins all the searchable columns from all the relevant tables
- Implement a basic cursor-based pagination by the PKs and a timestamp.
Currently it seems to work fine on a few hundred thousands of records.
BUT,
My questions are:
- The View has many duplicates of the PKs, as I join various one-to-many and many-to-many tables, and any combination of DISTINCT gives me, usually, less unique records than asked. (For example, User has 100 tags - therefore, the View has 100 records with the same User PK. Running a Distinct query of size 100 gives me a single User PK). This isn’t a big problem, but perhaps there is a better approach. I’m not super proficient with SQL, so…
- I’m afraid the cursor-based implementation is too naive, and will become problematic in the future. Simply, this is just ordering by the PK, selecting the ones where the PK is larger than the cursor, and running a chained LIKE on selected fields. Any other suggestions?
- Is creating Views for searching is a common or correct approach? I figured the problem was the fact that we need to find unique User PKs while searching across multiple tables. So, I created a “flat” table to allow a flattened search. Yet View isn’t an actual table - and it does the JOINs every time I execute a query - so, how is it more performant? And are there any other strategies?
IMPORTANT CLARIFICATIONS:
- the pagination is necessary, as I need these queries in the context of infinite scroll in the client, which fetches X results in every scroll.
- By ‘Cursor’ I refer to the general concept of pagination not through indexes but with a sorted unique value.
Generally, optimizations and such are a new thing for me, and my interaction with SQL was through ORMs only - so, if I’m mistaken or missing something, please correct me.
Thank you all very much
2
u/SQLBek 1 Jul 25 '25
Short answers since I'm in the middle of something else:
Are these views on top of views or just one single view? The former is going to be a scalability nightmare. The latter is generally acceptable.
Cursors = bad. Why do you want to iterate records one by one?
One thing to keep in mind - SQL Server is a declarative programming language, not procedural. Thus the same paradigms that one might be used to in procedural languages do not translate well. Also, SQL Server excels at set-based solutions, not iterative solutions.
1
u/silentlegacyfalls Jul 25 '25
So you have some collection of n tables, each with their own set of fields you need to search for an arbitrary term, and they are some combination of one to one, one to many, AND many to many? And right now you're just left joining them together and processing them with a cursor of some arbitrary size, doing a LIKE <search criteria> on all the fields?
1
u/SirGreybush 1 Jul 25 '25
The simplest approach you did was the best, from a business POV. Short time to implement, a simple view, doesn't matter how slow it is, that's a worry-for-later.
My approach if I was working in the same company as you, would be to create a reporting database, that the data is always 1-day old, and some stored procs for maintaining it. This is where the BI notion comes up.
I'd keep your view as-is, but would put a cap with SELECT TOP 10000 for only 10k records at a time, and maybe a CTE or more nested just to increase performance a bit, no more than an hour's time.
In the reporting DB, your view would become an actual table with an index or two, the whole point of a reporting DB, flatten out the 2D (3D with time) to make queries easier, and being physical tables, very high performance.
The slow query time is mitigated by only fetching new or changed data in the last 24 hours to import from the Prod DB to the Reporting DB. This is done with Stored Procs inside the Reporting DB.
Then business analysts can use various tools like PowerBI, Excel, Crystal Reports, and not affect the Prod DB performance for the users using that application.
The advanced BI is to do the above in "layers", the lowest is Staging, where the new/changed data lives for a day. Then that goes into a raw layer (bronze), then extrapolated / new / transformed data columns goes into a business layer (silver).
The last layer is usually Kimball / Snowflake, dimensions and facts, that PowerBI loves. I won't get into this, just look at r/dataengineering sub for more info. Also it's a University-level course taught worldwide. BI Analysts & Architects are always in demand in medium-to-large companies. Use this current job as a learning experience, and learn the BI track, to better your career. A lot of courses / classes online.
I've been in IT, programming, DBA, BI, since the early 90's, and I've had to completely re-learn my skills every decade at a minimum. Except, SQL, 98% similar SQL today than even in 1992. We just have more window functions and security setups, how dates are handled.
I think that you could probably build a reporting DB, with the skills and comment responses you've shared here so far. I believe in you.
1
u/B1zmark 1 Jul 26 '25
While I understand the want to do this through a single, monolithic query - when dealing with search boxes you should consider adding in "Search for the name, X, Y, Z of a customer" to the text box description. Limiting the searched fields will MASSIVELY increase the performance of the search.
In cases where a user is searching for something and is on the phone to a customer, customer service for example, every second the operator is sitting waiting for a search result to come back costs the company money. The solution is training the operator to search on specific terms using specific fields - because that reduces search times and reduces call handling time.
I know we're nerds but remember the real world impact of the code you push - most of the time the "right" solution isn't the perfect piece of code; instead it's about creating a solution that is optimal for the user and the company.
1
u/jshine13371 6 Jul 27 '25
FWIW, a stored procedure would give you the most flexibility to implement, manage, and tune your solution.
As far as pagination goes, I try to avoid it in the database layer, and prefer pulling everything back for the client-side or API to manage the pagination in what's effectively a cached dataset. This then prevents the same data from re-appearing multiple times on future pages, or previously shown data from disappearing when paging back to a previous page, resulting in a much better user experience.