SQL Join code check and peer review [closed] - sql

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I am still fairly green when it comes to SQL joins. The below code works but I want to check that I am doing it the best way before I copy and paste errors into other work in the future.
The idea of the below code is to get the PropertyID and Name of a property from the first Table and using the PropertyID join them. In this case I am actually using every field in Table B (thus the *).
So more a peer review than anything.
SELECT TblA.propertyid AS PD,
TblA.propertyname AS PD,
TblB.*
FROM tbpropertydetails AS TblA
INNER JOIN tbpropertydetailssafeguarding AS TblB
ON TblA.propertyid = TblB.propertyid
WHERE TblA.regionid <> '0'
ORDER BY TblA.propertyid ASC
I am programming in VB.net but this is really standalone SQL.

Generally you want to be caution with inner joins because you can lose potential record sets.
An example would be records in TbPropertyDetails that do not have an entry (no matching PropertyId) in TbPropertyDetailsSafeguarding would vanish. There might not be a corresponding entry in the joining table because this information is entered at a later date.
Try using a LEFT JOIN first and then decide how you want to handle the null records i.e. those records in the primary table that had matching records in the joining table.

Related

Calculate number of exercises in each category in access 2016 [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have two tables such as: Category and Exercise. In the first of them I have field names such as: CategoryID and CategoryName. In the second table there are field names such as: ExerciseID Exercise and CategoryID. I have to calculate the number of exercises in each category. For the exercises with provided data I have:
addition, subtraction, multiplication, division, enhancemen,
running, jumping, pole vault, shot put, literature, grammar.
The query has to output me:
Maths = 5
English = 2
PE = 4
How would I be able to calculate this within query in ms-access?
You should have a key to join the tables.
In addition to ExerciseID and Exercise, have a CategoryKey column which you can join to the Category table through CategoryID. Then you'd just query SELECT COUNT(*) as count FROM Exercise WHERE CategoryKey = 1 where 1 is the CategoryID you want to count. You can also do more complex joins in the future if you have new requirements.
Otherwise, you'll have to write a giant goofy sql switch statement, which I don't have much experience with, because it's usually not something you need to use if your table is structured correctly.

SQL Select Sub Query [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I have the following database tables
User List
------ ------
userId (PK) listId (PK)
fullName description
addedById (FK with userId in User table)
modifiedById (FK with userId in User table)
I need to pull out all data from the List table, but instead of showing the IDs for addedById and modifiedById, I need to pull the fullName from the User table.
This query works, and gives me the data I need. However, I'm not sure if there is a better way of constructing this query? I'm not keen on having multiple sub select queries within my main select query, mainly because of performance issues.
select t1.[description],
t1.addedById,
t1.modifiedById,
(select fullName from dbo.User where userId = t1.addedById) as [AddedByUser],
(select fullName from dbo.User where userId = t1.modifiedById) as [ModifiedByUser]
from dbo.List t1
I'd really appreciate if anyone could suggest improvements to the query, or advise to keep as is.
Thanks.
A more standard SQL method would be:
SELECT t1.description,
t1.addedById,
t1.modifiedById,
add.fullName AS [AddedByUser],
mod.fullName AS [ModifiedByUser]
FROM dbo.List t1
LEFT JOIN dbo.User add
ON add.userId = t1.addedById
LEFT JOIN dbo.User mod
ON mod.userID = t1.modifiedById
However, I suspect this will perform identically to your query and probably has an identical execution plan. The only real advantage to this method is that it's easier to expand. For example, if you wanted to add new columns from the User table this would be easier.
As #Gordon notes, performance should be fine if there's an index on the fields you're joining with.
Is that double join with same table bothering you? It's not slow, its preferred way of doing it instead making the linked subquery.
I am assuming you got indexes on PK and both FK.
Only thing you can minimize is to lessen the number of joined rows. You can do that
by either using the left inner join or filtering in the end with where clause stating both keys you use in join must be not null
I can write both examples for you but this should be self explanatory.
Other mayor thing you can do is to PRESELECT values from users. For example if you have a shit ton of users, and you know only few of them can be in either role. And you can filter which ones by some column in Users you haven't listed, even better if that column has an index.
Then you can maybe profit from pre-selecting only those users and then joining to selection result. Either by temp table if both can be pre-selected or by making a select on spot instead joining to the entire table. Not sure about numbers we are dealing with here for this to become relevant..

Replace one column by values of the same column in anther table in SQL server [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have two tables, one big and one small. Both contain columns ID and EffectiveDate.
The bigger table has more other columns and of course more rows than the smaller table.
Under the condition that ID for both tables are the same, the EffectiveDate column is earlier in the small table than the big table. I want to replace the EffectiveDate in the big table by the value of the EffectiveDate column from the small table.
What should I do?
Seems like a very basic SQL query....
UPDATE bt
SET EffectiveDate = st.EffectiveDate
FROM dbo.BiggerTable bt
INNER JOIN dbo.SmallerTable st ON bt.ID = st.ID
-- maybe you also need this condition, if not *ALL* EffectiveDate values in the
-- smaller table are indeed before the values in the bigger table
WHERE st.EffectiveDate < bt.EffectiveDate

Sqlite: I need to update a data from one table to another [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have two tables in my sqlite database, with a column name as in both tables solution, solutionimage, id saying tableA and tableB. I want to, copy from tableB solution, solutionimage to tableA matching the id in both table respectively, how to do it?
I have google it and tried but i didnt get it.. Any one help me. Thanks a lot in advance.
Ideally you would want to join the table you are updating to the other table where you take the values from.
But I just read that JOINS in UPDATES are not allowed in SQLITE so subqueries are the way to go I suppose:
UPDATE tableB
SET
Solution = (SELECT Solution FROM tableA WHERE ID = tableB.ID),
SolutionImage = (SELECT Solution FROM tableA WHERE ID = tableB.ID);
See this fiddle for example output.

Search with result priority based on different condtions [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I have a auto-complete search box that I am working on for a client. The database is in SQL Server and there is a big set of data.
I've been able to do a standard LIKE query to the database which is not that much of a problem, but the client has come up with some requirements.
Let's say the search keyword is "London Airport"
The results that show up must have certain precedence. Here are the precedence criteria:
The results with London and Airport as match must show at the top. e.g. London Airport, London Main Airport etc.
The results with London must follow, since it matches the city field.
Airport would then follow, as it is the catagory part.
The requirement is actually to include UK results first but I have already taken care of that.
Let's say the table is
Airport_name | country | city | geo_id and so on.
I've created a table function that splits the keyword into table rows of results and then I've done the like query
LIKE '% split_table.result %'
the trouble is even for the 1st criteria, the above approach is doing an OR query, showing results with London and Airport only... I want to do an AND query here and would appreciate it if I could use the split table function I've created.
I need some idea about how to set these priorities.
I'd really appropriate some help.
One plan of action is to build the separate result sets and union them together
select Id, Name
from
(
Select Id, Name, 1 as SearchRank from tables where (primary filter)
union
Select Id, Name, 2 as SearchRank from tables where (secondary filter)
union
Select Id, Name, 3 as SearchRank from tables where (tertiary filter)
) results
group by Id, Name
order by Min(SearchRank)
Hope this helps as you are using sql server
http://technet.microsoft.com/en-us/library/ms142559%28v=sql.105%29.aspx