Why is my WHERE clause not return the CustomerIDs that are also in the Orders table? - sql

My SQL statements are not returning any results. I am using the table that are on the www.w3schools.com web site. I want to have all of the customer IDS in my Customers table match all of the CustomerIDS in the Orders table. The SQL statement works that it goes through the table and checks every CustomerID to every Orders.CustomersID and when it finds a match doesn't it return that record.
Question: Why does the SQL not return the row when both customerIDS are equal because there are values that will return true?
SQL Statement:
SELECT * FROM Customers WHERE Customers.CustomersID = Orders.CustomersID;
One last thought: What is the best free SQL database that can be downloaded without a lot of hassle for home use?

Try this:
SELECT Customers.*
FROM Customers
JOIN Orders ON Customers.CustomerID = Orders.CustomerID;

If you just want customers that have orders then use:
SELECT *
FROM Customers
WHERE CustomerID IN
(SELECT CustomerID FROM Orders)
If you use a JOIN you may get multiple records per customer (if the customer has multiple orders). You can solve that with DISTINCT but IMHO a IN clause is cleaner (and likely faster)

You need a query like this: SELECT *
FROM Customers c
INNER JOIN Orders o on c.CustomerID = o.CustomerID;
w3schools is a very bad resource.
Selecting the best database is a bad question for stackoverflow. But the answer is PostgreSQL. (And lots of other DBMSs would fit the bill for you as well.)

Related

SQL-92 Selecting with the dot operator

Before it is marked as a duplicate, I am not asking If I have to specify it fully, I am why it does not matter if it is specified. Hope that clears that up. Now to the question.
I'm new to SQL so I'm not sure if there is some technical term for this.
Say I have a database with tables: Orders and Customers.
Orders has categories: OrderID, CustomerID, and OrderDate
Customers has categories: CustomerID, CustomerName, ContactName, and Country
I then have a SQL Query:
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;
So I am selecting Orders.OrderID, Customers.CustomerName, and Orders.OrderDate FROM Orders table. If it is from the Orders table, why specify Orders. before the OrderID and OrderDate in select ? This is an example from a website, and does not explain this. I am not sure if it has to do with join (which is in the example) so that's why I also put it there and in the tags.
-Thanks
Sometimes the column name is found in both tables and your DBMS will throw an error that the column is ambiguous. It's usually a good idea to explicitly declare which table you want the item to come from.
Using an alias often make the code easier to read and write:
SELECT ord.OrderID, cus.CustomerName, ord.OrderDate
FROM Orders ord
INNER JOIN Customers cus ON ord.CustomerID=cus.CustomerID;
These table names are pretty short, but you can see how useful aliases can be when the table names become longer and more complicated.
One benefit to explicitly declaring the table is that you can tell at a glance what table the data is coming from. Once you have data coming from many sources, through joins or not, it can be difficult to tell exactly which table a field is coming from, if you do not show the table in the select statements.

Writing a query that can be used to find which orders shipped to a different country from the customer

So I am currently in a Database 2 class at my University. We are using the Northwinds db. I haven't used SQL in a few years so I am a little rusty.
I changed a few of the pieces in the Orders table so that instead of 'Germany' it was 'Tahiti'. Now I need to write a query to find which orders shipped where.
I know that I will need to use an Join but I am not exactly sure how. I have gone to W3Schools and looked at the Joins SQL page but still haven't found the correct answer I am looking for.
This is what I have currently (which I am also not sure if it is correct):
SELECT Customers.Country
FROM Customer
WHERE Customer.Country = 'Germany'
INNER JOIN
SELECT Orders.ShipCountry
FROM Orders
WHERE Orders.ShipCountry = 'Tahiti'
So if anyone could give me help I would really appreciate it.
EDIT
So this is the actual question I was given which I think is also kind of poorly worded.
"Suspicious e-commerce transactions include orders placed by a customer in one country that are shipped to another country. In fact there are no such orders in the Northwind db, so create a few by modifying some of the "Germany" shipcountry entries in the orders table to "Tahiti". Then write a query which finds orders shipped to a different country from the customer. Hint: in order to do this, you will need to join the Customers and Orders table."
Is this what you are looking for:
SELECT *
FROM Customer AS C
INNER JOIN
Orders AS O
ON C.CustomerID = O.CustomerID
WHERE C.Country = 'Germany' AND O.ShipCountry = 'Tahiti';
The above query is based on the Schema as defined in CodePlex
i hope that this can help you
SELECT Orders.*
FROM Orders -- table name, also can use alias
inner join Customer -- table name, also can use alias
on Orders.ShipCountry = Customer.Country -- you must declare what is the field to use by join
where Customer.Country in ('Germany','Tahiti')

Translate SQL query to absolute beginner (me)

I am trying to understand the JOIN command from w3schools tutorial and there is an example.
Can you please "translate" it to me what exactly it does? I already know what do the dots do, but INNER JOIN, ON and so on messed me up?
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers
ON Orders.CustomerID=Customers.CustomerID;
And does it creates a new table in my SQL database or it just creates (lets call it..) "virtual" table which I can use it in the moment
The dot notation here signifies the column of a table.
Table.Column
So the SELECT is retrieving the columns specified from each table.
JOIN matches the tables based on the condition that appears after ON
this queries joins customers to orders based the condition of having the same CustomerID.
For more on joins check out http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html
Perhaps the first thing to understand is the "dot notation." When you see a value like Orders.CustomerID SQL will read that to mean the CustomerID column within the Orders table.
The INNER JOIN is looking for an exact match for the records you specify with the ON clause...
So, in this example, SQL will first find all the records in the Orders table which have a CustomerID that matches the CustomerID found in the Customers table.
Then, it will look to the SELECT clause and show you the OrderID (from the Orders table), the CustomerName (from the Customers table) and the OrderDate from the Orders table.
If you're using SQL Server Management Studio (SSMS) or some other similar tool, it should display your results - kindof like a virtual table... but it doesn't actually create a table.
Hope that helps,
Russell
There are INNER AND OUTER JOINS. I think this post sums up those differences well.
What is the difference between "INNER JOIN" and "OUTER JOIN"?
As far as the concept itself you are 'joining' the tables by finding things in common between them based on a shared value in each. If you have ever done a vlookup with Microsoft Excel then you are familiar with this concept. In the query you've posted you are selecting values from both the Orders and Customers table. You can tell which table you are selecting values from by the prefix Orders. or Customers. You can then tell which column by the value following the dot i.e. OrderID, CustomerName, OrderDate.
The way the query knows to pull a conjoined field is if the CustomerID field matches.
So step by step
You are selecting
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
From the table Orders
FROM Orders
You wish to pull corresponding values from Customers. There are numerous join methods and logic that goes with each but you have chosen INNER JOIN explained in the link above.
INNER JOIN Customers
The criteria for joining is CustomerID
ON Orders.CustomerID=Customers.CustomerID;
To use an approximate Excel Vlookup analogy
The Lookup_value is CustomerID
The Table array is ORDERS
The range lookup is the type of join you are performing
SELECT statement returns data, it doesn't create any table not even virtual table whatsoever (if you see any table after executing SELECT statement, thats just a way the returned data presented). Create and modify table done using DDL (Data Definition Language) statements when SELECT is one of DML (Data Manipulation Language) [reference].
Join statement explained very well here, from basic use to more advance with illustration.

SQL, Select from table A and use result ID to loop though table B?

I have a windows server running MS-SQL 2008.
I have a customer table that I need to select the id's of all customers that are Active, On Hold, or Suspended.
get all customers that are Y= current active customer H=on hold S=Suspended
select id from customer where active = 'Y';
the above statement worked fine for selecting the ID's of the affected customers.
I need to use these results to loop though the following command in order to find out what rates all the affected customers have.
get all rates for a customer
select rgid from custrate where custid = [loop though changing this id with results from first statement];
the id from the customer table coincides with the custid from the custrate table.
So in the end I need a list of all affected customer id's and what rgid's(rate group(s)) they have.
SQL isn't about loops in general and instead you should think in terms of joins.
select customer.id, custrate.rgid, customer.active
from customer
inner join custrate
on customer.id = custrate.custid
where active in ('Y', 'H', 'S")
order by customer.active, customer.id
would be a starting point to think about. However, that is just a wild guess as the schema was not specified nor the relations between the tables.

Select based on the number of appearances of an id in another table

I have a table B with cids and cities. I also have a table C that has these cids with extra information. I want to list all the cids in table C that are associated with ALL appearances of a given city in Table B.
My current solution relies on counting the number of times the given city appears in Table B and selecting only the cids that appear that many times. I don't know all the SQL syntax yet, but is there a way to select for this kind of pattern?
My current solution:
SELECT Agents.aid
FROM Agents, Customers, Orders
WHERE (Customers.city='Duluth')
AND (Agents.aid = Orders.aid)
AND (Customers.cid = Orders.cid)
GROUP BY Agents.aid
HAVING count(Agents.aid) > 1
It only works because I know right now with the HAVING statement.
Thanks for the help. I wasn't sure how to google this problem, since it's pretty specific.
EDIT: I'm pinpointing my problem a bit. I need to know how to determine if EVERY row in a table has a certain value for a field. Declaring a variable and counting the rows in a sub-selection and filtering out my results by IDs that appear that many times works, but It's really ugly.
There HAS to be a way to do this without explicitly count()ing rows. I hope.
Not an answer to your question, but a general improvement.
I'd recommend using JOIN syntax to join your tables together.
This would change your query to be:
SELECT Agents.aid
FROM Agents
INNER JOIN Orders
ON Agents.aid = Orders.aid
INNER JOIN Customers
ON Customers.cid = Orders.cid
WHERE Customers.city='Duluth'
GROUP BY Agents.aid
HAVING count(Agents.aid) > 1
What variant of SQL are you using?
To start with, you can (and should) use JOIN instead of doing it in the WHERE clause, e.g.,
select Agents.aid
from Agents
join Orders on Agents.aid = Orders.aid
join Customers on Customers.cid = Orders.cid
where Customers.city = 'Duluth'
group by Agents.aid
having count(Agents.aid) > 1
After that, I'm afraid I might be a little lost. Using the table names in your example query, what (in English, not pseudocode) are you trying to retrieve? For example, I think your sample query is retrieving the PK for all Agents that have been involved in at least 2 Orders involving Customers in Duluth.
Also, some table definitions for Agents, Orders, and Customers might help (then again, they might be irrelevant).
I'm not sure if I understood you problem, but I think the following query is what you want:
SELECT *
FROM customers b
INNER JOIN orders c USING (cid)
WHERE b.city = 'Duluth'
AND NOT EXISTS (SELECT 1
FROM customers b2
WHERE b2.city = b.city
AND b2.cid <> cid);
Probably you will need some indexes on these columns.