Northwind Database Sql Queries

-->

  1. Northwind Database For Sql Server
  2. Northwind Database Sql Queries Examples
  3. Northwind Database Sql

This walkthrough provides a fundamental end-to-end LINQ to SQL scenario with minimal complexities. You will create an entity class that models the Customers table in the sample Northwind database. You will then create a simple query to list customers who are located in London.

This walkthrough is code-oriented by design to help show LINQ to SQL concepts. Normally speaking, you would use the Object Relational Designer to create your object model.

Note

Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For more information, see Personalizing the IDE.

This walkthrough was written by using Visual C# Development Settings.

Northwind Database is a sample database that is shipped along with Microsoft Access application. Basically, the database is about a company named 'Northwind Traders'.The database captures all the sales transactions that occurs between the company i.e. Northwind traders and its customers as well as the purchase transactions between Northwind and its suppliers. MySQL Northwind Queries - Part 2 This is part 2 of the tutorial series - converting the popular Microsoft Access Northwind database queries to MySQL queries. These queries are originated from Access Northwind Traders application. Some of them are relatively complex aggregated queries with sub-queries.

Prerequisites

  • This walkthrough uses a dedicated folder ('c:linqtest5') to hold files. Create this folder before you begin the walkthrough.

  • This walkthrough requires the Northwind sample database. If you do not have this database on your development computer, you can download it from the Microsoft download site. For instructions, see Downloading Sample Databases. After you have downloaded the database, copy the file to the c:linqtest5 folder.

Overview

Database

This walkthrough consists of six main tasks:

  • Creating a LINQ to SQL solution in Visual Studio.

  • Mapping a class to a database table.

  • Designating properties on the class to represent database columns.

  • Specifying the connection to the Northwind database.

  • Creating a simple query to run against the database.

  • Executing the query and observing the results.

Creating a LINQ to SQL Solution

In this first task, you create a Visual Studio solution that contains the necessary references to build and run a LINQ to SQL project.

To create a LINQ to SQL solution

  1. On the Visual Studio File menu, point to New, and then click Project.

  2. In the Project types pane of the New Project dialog box, click Visual C#.

  3. In the Templates pane, click Console Application.

  4. In the Name box, type LinqConsoleApp.

  5. In the Location box, verify where you want to store your project files.

  6. Click OK.

Adding LINQ References and Directives

This walkthrough uses assemblies that might not be installed by default in your project. If System.Data.Linq is not listed as a reference in your project (expand the References node in Solution Explorer), add it, as explained in the following steps.

To add System.Data.Linq

  1. In Solution Explorer, right-click References, and then click Add Reference.

  2. In the Add Reference dialog box, click .NET, click the System.Data.Linq assembly, and then click OK.

    The assembly is added to the project.

  3. Add the following directives at the top of Program.cs:

Mapping a Class to a Database Table

In this step, you create a class and map it to a database table. Such a class is termed an entity class. Note that the mapping is accomplished by just adding the TableAttribute attribute. The Name property specifies the name of the table in the database.

To create an entity class and map it to a database table

  • Type or paste the following code into Program.cs immediately above the Program class declaration:

Designating Properties on the Class to Represent Database Columns

In this step, you accomplish several tasks.

  • You use the ColumnAttribute attribute to designate CustomerID and City properties on the entity class as representing columns in the database table.

  • You designate the CustomerID property as representing a primary key column in the database.

  • You designate _CustomerID and _City fields for private storage. LINQ to SQL can then store and retrieve values directly, instead of using public accessors that might include business logic.

To represent characteristics of two database columns

Northwind Database Sql Queries
  • Type or paste the following code into Program.cs inside the curly braces for the Customer class.

Specifying the Connection to the Northwind Database

In this step you use a DataContext object to establish a connection between your code-based data structures and the database itself. The DataContext is the main channel through which you retrieve objects from the database and submit changes.

You also declare a Table<Customer> to act as the logical, typed table for your queries against the Customers table in the database. You will create and execute these queries in later steps.

To specify the database connection

  • Type or paste the following code into the Main method.

    Note that the northwnd.mdf file is assumed to be in the linqtest5 folder. For more information, see the Prerequisites section earlier in this walkthrough.

Creating a Simple Query

In this step, you create a query to find which customers in the database Customers table are located in London. The query code in this step just describes the query. It does not execute it. This approach is known as deferred execution. For more information, see Introduction to LINQ Queries (C#).

You will also produce a log output to show the SQL commands that LINQ to SQL generates. This logging feature (which uses Log) is helpful in debugging, and in determining that the commands being sent to the database accurately represent your query.

To create a simple query

  • Type or paste the following code into the Main method after the Table<Customer> declaration.

Executing the Query

In this step, you actually execute the query. The query expressions you created in the previous steps are not evaluated until the results are needed. When you begin the foreach iteration, a SQL command is executed against the database and objects are materialized.

To execute the query

  1. Type or paste the following code at the end of the Main method (after the query description).

  2. Press F5 to debug the application.

    Note

    If your application generates a run-time error, see the Troubleshooting section of Learning by Walkthroughs.

    The query results in the console window should appear as follows:

    ID=AROUT, City=London

    ID=BSBEV, City=London

    ID=CONSH, City=London

    ID=EASTC, City=London

    ID=NORTS, City=London

    ID=SEVES, City=London

  3. Press Enter in the console window to close the application.

Next Steps

The Walkthrough: Querying Across Relationships (C#) topic continues where this walkthrough ends. The Query Across Relationships walkthrough demonstrates how LINQ to SQL can query across tables, similar to joins in a relational database.

If you want to do the Query Across Relationships walkthrough, make sure to save the solution for the walkthrough you have just completed, which is a prerequisite.

See also

Subqueries

Subqueries can be characterized in two main ways. One is by the expected number of values (either scalar or multivalued), and another is by the subquery’s dependency on the outer query (either self-contained or correlated). Both scalar and multivalued subqueries can be either self-contained or correlated.

Self-Contained Subqueries

A self-contained subquery is a subquery that can be run independently of the outer query. Self-contained subqueries are very convenient to debug, of course, compared to correlated subqueries.

Scalar subqueries can appear anywhere in the query where an expression resulting in a scalar value is expected, while multivalued subqueries can appear anywhere in the query where a collection of multiple values is expected.

A scalar subquery is valid when it returns a single value, and also when it returns no valuesin which case, the value of the subquery is NULL. However, if a scalar subquery returns more than one value, a run-time error will occur.

………………

Logically, a self-contained subquery can be evaluated just once for the whole outer query. Physically, the optimizer can consider many different ways to achieve the same thing, so you shouldn’t think in such strict terms.

…………………

Correlated Subqueries

Correlated subqueries are subqueries that have references to columns from the outer query. Logically, the subquery is evaluated once for each row of the outer query. Again, physically, it’s a much more dynamic process and will vary from case to case. There isn’t just one physical way to process a correlated subquery.

Northwind Database For Sql Server

………………….

Let’s start with the basic request to return the orders with the maximum OrderDate for each employee. Here you can get multiple rows for each employee because an employee can have multiple orders with the same order date.

You might be tempted to use this solution, which includes a self-contained subquery similar to the one used to return orders on the last actual order date of the month:

SELECT OrderID, CustomerID, EmployeeID, OrderDate, RequiredDate
FROM dbo.Orders
WHERE OrderDate IN
(SELECT MAX(OrderDate) FROM dbo.Orders
GROUP BY EmployeeID);

Northwind Database Sql Queries Examples

However, this solution is incorrect. The result set will include the correct orders (the ones with the maximum OrderDate for each employee). But you will also get any order for employee A with an OrderDate that happens to be the maximum for employee B, even though it’s not also the maximum for employee A. This wasn’t an issue with the previous problem, as an order date in month A can’t be equal to the maximum order date of a different month B.

In our case, the subquery must be correlated to the outer query, matching the inner EmployeeID to the one in the outer row:

Northwind Database Sql

SELECT OrderID, CustomerID, EmployeeID, OrderDate, RequiredDate
FROM dbo.Orders AS O1
WHERE OrderDate =
(SELECT MAX(OrderDate)
FROM dbo.Orders AS O2
WHERE O2.EmployeeID = O1.EmployeeID);

Comments are closed.