Building queries in sql server. Access queries

Queries in Access are the primary tool for retrieving, updating, and manipulating data in database tables. Access, in accordance with the concept of relational databases, uses Structured Query Language (SQL) to execute queries. Any query in Access is implemented using SQL statements.

The main type of query is a select query. The result of this query is a new table that exists before the query is closed. The records are formed by combining the records of the tables on which the query is built. The way to combine table records is specified when defining their relationship in the data schema or when creating a query. The selection conditions formulated in the query allow you to filter the records that make up the result of joining tables.

Access can create several types of queries:

  • fetch request- selects data from a single table or query, or multiple related tables and other queries. The result is a table that exists before the query is closed. Formation of records of the result table is carried out in accordance with the specified selection conditions and when using several tables by combining their records;
  • query to create a table- selects data from interconnected tables and other queries, but, unlike a select query, saves the result in a new permanent table;
  • update, add, delete requests- are action requests, as a result of which the data in the tables is changed.

Queries in Access in design mode contain a data schema that displays the tables used, and a query form, which constructs the structure of the query table and the conditions for selecting records (Figure 4.1).

Using a query, you can perform the following types of data processing:

  • include in the query table user-selected table fields;
  • make calculations in each of the received records;
  • select records that meet the selection criteria;
  • create a new virtual table based on the union of records of related tables;
  • group records that have the same values ​​in one or several fields, simultaneously perform statistical functions on other fields of the group and include one record for each group in the result;
  • create a new database table using data from existing tables;
  • update the fields in the selected subset of records;
  • delete the selected subset of records from the database table;
  • add the selected subset of records to another table.

Queries in Access serve as sources of records for other queries, forms, reports. Using a query, you can collect complete information for the formation of a certain document of the subject area from several tables, then use it to create a form - an electronic representation of this document. If a form or a report is created by the wizard based on several interconnected tables, then a query is automatically generated for them as a record source.
To consolidate, watch the video tutorial.

Requests are written without escaping quotes, since MySQL, MS SQL and PostGree they are different.

SQL query: getting specified (required) fields from a table

SELECT id, country_title, count_people FROM table_name

We get a list of records: ALL countries and their population. The names of the required fields are separated by commas.

SELECT * FROM table_name

* denotes all fields. That is, there will be impressions EVERYTHING data fields.

SQL query: output records from a table excluding duplicates

SELECT DISTINCT country_title FROM table_name

We get a list of records: the countries where our users are located. There can be many users from one country. In this case, this is your request.

SQL query: displaying records from a table according to a specified condition

SELECT id, country_title, city_title FROM table_name WHERE count_people> 100000000

We get a list of records: countries where the number of people is more than 100,000,000.

SQL query: displaying records from a table with ordering

SELECT id, city_title FROM table_name ORDER BY city_title

We get a list of records: cities in alphabetical order. At the beginning of A, at the end of I.

SELECT id, city_title FROM table_name ORDER BY city_title DESC

We get a list of records: cities in reverse ( DESC) ok. At the beginning I, at the end A.

SQL query: counting the number of records

SELECT COUNT (*) FROM table_name

We get the number (number) of records in the table. In this case, there is NO list of records.

SQL query: output the required range of records

SELECT * FROM table_name LIMIT 2, 3

We get 2 (second) and 3 (third) records from the table. The request is useful when creating navigation on WEB pages.

SQL queries with conditions

Output of records from a table according to a given condition using logical operators.

SQL query: AND construction

SELECT id, city_title FROM table_name WHERE country = "Russia" AND oil = 1

We get a list of records: cities from Russia AND have access to oil. When the operator is used AND, then both conditions must match.

SQL query: OR construct

SELECT id, city_title FROM table_name WHERE country = "Russia" OR country = "USA"

We get a list of records: all cities from Russia OR USA. When the operator is used OR, then at least one condition must match.

SQL query: AND NOT construct

SELECT id, user_login FROM table_name WHERE country = "Russia" AND NOT count_comments<7

We get a list of records: all users from Russia AND who made NOT LESS 7 comments.

SQL query: IN (B) construct

SELECT id, user_login FROM table_name WHERE country IN ("Russia", "Bulgaria", "China")

We get a list of records: all users who live in ( IN) (Russia, or Bulgaria, or China)

SQL query: NOT IN construction

SELECT id, user_login FROM table_name WHERE country NOT IN ("Russia", "China")

We get a list of records: all users who do not live in ( NOT IN) (Russia or China).

SQL query: IS NULL construct (empty or NOT empty values)

SELECT id, user_login FROM table_name WHERE status IS NULL

We get a list of records: all users where status is not defined. NULL is a separate topic and is therefore checked separately.

SELECT id, user_login FROM table_name WHERE state IS NOT NULL

We get a list of records: all users where status is defined (NOT ZERO).

SQL query: LIKE construct

SELECT id, user_login FROM table_name WHERE surname LIKE "Ivan%"

We get a list of records: users whose last name begins with the combination "Ivan". The% sign means ANY number of ANY characters. To find the% sign, you need to use the escaping "Ivan \%".

SQL query: BETWEEN construct

SELECT id, user_login FROM table_name WHERE salary BETWEEN 25000 AND 50000

We get a list of records: users who receive salaries from 25,000 to 50,000 inclusive.

There are a LOT of logical operators, so study the SQL server documentation in detail.

Complex SQL queries

SQL query: combining multiple queries

(SELECT id, user_login FROM table_name1) UNION (SELECT id, user_login FROM table_name2)

We get a list of records: users who are registered in the system, as well as those users who are registered on the forum separately. Multiple queries can be combined with the UNION operator. UNION acts like SELECT DISTINCT, that is, it discards duplicate values. To get absolutely all records, you need to use the UNION ALL operator.

SQL query: counting field values ​​MAX, MIN, SUM, AVG, COUNT

Output of one, the maximum value of the counter in the table:

SELECT MAX (counter) FROM table_name

Output of one, the minimum value of the counter in the table:

SELECT MIN (counter) FROM table_name

Displaying the sum of all counter values ​​in the table:

SELECT SUM (counter) FROM table_name

Displaying the average value of the counter in the table:

SELECT AVG (counter) FROM table_name

Displaying the number of counters in the table:

SELECT COUNT (counter) FROM table_name

Display of the number of counters in workshop No. 1, in the table:

SELECT COUNT (counter) FROM table_name WHERE office = "Shop # 1"

These are the most popular commands. It is recommended, where possible, to use SQL queries of this kind for calculating, since no programming environment can compare in data processing speed than the SQL server itself when processing its own data.

SQL query: grouping records

SELECT continent, SUM (country_area) FROM country GROUP BY continent

We get a list of records: with the name of the continent and with the sum of the areas of all their countries. That is, if there is a directory of countries where each country has its area recorded, then using the GROUP BY clause, you can find out the size of each continent (based on the grouping by continent).

SQL query: using multiple tables via alias

SELECT o.order_no, o.amount_paid, c.company FROM orders AS o, customer AS with WHERE o.custno = c.custno AND c.city = "Tyumen"

We get a list of records: orders from customers who live only in Tyumen.

In fact, with a properly designed database of this type, the query is the most frequent, therefore a special operator was introduced in MySQL, which works many times faster than the code written above.

SELECT o.order_no, o.amount_paid, z.company FROM orders AS o LEFT JOIN customer AS z ON (z.custno = o.custno)

Nested subqueries

SELECT * FROM table_name WHERE salary = (SELECT MAX (salary) FROM employee)

We get one record: information about the user with the maximum salary.

Attention! Nested subqueries are one of the bottlenecks in SQL servers. Together with their flexibility and power, they also significantly increase the load on the server. Which leads to a catastrophic slowdown in the work of other users. Cases of recursive calls with nested queries are very common. Therefore, I strongly recommend NOT to use nested queries, but to break them into smaller ones. Or use the above LEFT JOIN combination. In addition to this type of request, requests are an increased hotbed of security breaches. If you decide to use nested subqueries, then you need to design them very carefully and make the initial runs on copies of databases (test databases).

SQL queries changing data

SQL query: INSERT

Instructions INSERT allow you to insert records into a table. In simple words, create a line with data in the table.

Option number 1. The instruction is often used:

INSERT INTO table_name (id, user_login) VALUES (1, "ivanov"), (2, "petrov")

In the table " table_name"2 (two) users will be inserted at once.

Option number 2. It is more convenient to use the style:

INSERT table_name SET id = 1, user_login = "ivanov"; INSERT table_name SET id = 2, user_login = "petrov";

This has its advantages and disadvantages.

Main disadvantages:

  • Many small SQL queries run slightly slower than one large SQL query, but other queries will be queued for service. That is, if a large SQL query is executed for 30 minutes, then during all this time the rest of the queries will smoke bamboo and wait for their turn.
  • The request turns out to be more massive than the previous version.

Main advantages:

  • During small SQL queries, other SQL queries are not blocked.
  • Ease of reading.
  • Flexibility. In this option, you can not follow the structure, but add only the necessary data.
  • When forming archives in this way, you can easily copy one line and run it through the command line (console), thereby not restoring the whole ARCHIVE.
  • The writing style is similar to the UPDATE statement, which makes it easier to remember.

SQL query: UPDATE

UPDATE table_name SET user_login = "ivanov", user_surname = "Ivanov" WHERE id = 1

In the table " table_name"In the record with id = 1, the values ​​of the user_login and user_surname fields will be changed to the specified values.

SQL query: DELETE

DELETE FROM table_name WHERE id = 3

The record with id number 3 will be deleted in the table_name table.

  1. It is recommended to write all field names in small letters and, if necessary, separate them with a forced space "_" for compatibility with different programming languages ​​such as Delphi, Perl, Python and Ruby.
  2. Write SQL commands in CAPITAL letters for readability. Always remember that other people can read the code after you, and most likely you yourself after N amount of time.
  3. Name fields from the beginning of the noun, and then the action. For example: city_status, user_login, user_name.
  4. Try to avoid fallback words in different languages ​​that can cause problems in SQL, PHP or Perl, such as (name, count, link). For example: link can be used in MS SQL, but is reserved in MySQL.

This material is a short reference for everyday work and does not claim to be a super mega authoritative source, which is the primary source of SQL queries for a particular database.

Each of us regularly comes across and uses various databases. When we choose an email address, we are working with a database. Databases use search engines, banks to store customer data, etc.

But, despite the constant use of databases, even for many developers of software systems there are many "blank spots" due to different interpretations of the same terms. We will give a brief definition of basic database terms before looking at the SQL language. So.

Database - a file or set of files for storing ordered data structures and their relationships. Very often a control system is called a database - it is only a storage of information in a certain format and can work with various DBMS.

table - Imagine a folder that stores documents grouped by a certain criterion, for example, a list of orders for the last month. This is the table in the computer. A separate table has its own unique name.

Data type - the kind of information allowed to be stored in a separate column or row. These can be numbers or text in a specific format.

Column and row- we all worked with spreadsheets, which also have rows and columns. Any relational database works with tables in a similar way. Lines are sometimes called records.

Primary key- each row of the table can have one or more columns for its unique identification. Without a primary key, it is very difficult to update, modify, and delete the required rows.

What is SQL?

SQL(English - structured query language) was developed only for working with databases and is currently the standard for all popular DBMS. The syntax of the language consists of a small number of operators and is easy to learn. But, despite the external simplicity, it allows the creation of sql queries for complex operations with a database of any size.

Since 1992, there has been a generally accepted standard called ANSI SQL. It defines the basic syntax and functions of operators and is supported by all the leaders of the DBMS market, such as ORACLE. It is impossible to consider all the features of the language in one small article, so we will briefly consider only basic SQL queries. Examples clearly show the simplicity and capabilities of the language:

  • creation of databases and tables;
  • fetching data;
  • adding records;
  • modification and deletion of information.

SQL data types

All columns in a database table store the same data type. The data types in SQL are the same as in other programming languages.

Create tables and databases

There are two ways to create new databases, tables and other queries in SQL:

  • via the DBMS console
  • Using the online administration tools included with the database server.

A new database is created by the operator CREATE DATABASE<наименование базы данных>; ... As you can see, the syntax is simple and concise.

We create tables inside the database with the CREATE TABLE statement with the following parameters:

  • table name
  • column names and data types

As an example, let's create a Commodity table with the following columns:

We create a table:

CREATE TABLE Commodity

(commodity_id CHAR (15) NOT NULL,

vendor_id CHAR (15) NOT NULL,

commodity_name CHAR (254) NULL,

commodity_price DECIMAL (8,2) NULL,

commodity_desc VARCHAR (1000) NULL);

The table has five columns. The name is followed by the data type, the columns are separated by commas. The column value can be null (NULL) or must be filled (NOT NULL), and this is determined when the table is created.

Fetching data from a table

The data selection operator is the most frequently used SQL queries. To obtain information, it is necessary to indicate what we want to select from such a table. Let's start with a simple example:

SELECT commodity_name FROM Commodity

After the SELECT statement, we specify the name of the column to get the information, and FROM defines the table.

The result of executing the query will be all the rows of the table with the Commodity_name values ​​in the order in which they were entered into the database, i.e. without any sorting. An additional ORDER BY clause is used to order the result.

For a query on several fields, we list them separated by commas, as in the following example:

SELECT commodity_id, commodity_name, commodity_price FROM Commodity

It is possible to get the value of all columns of a row as a result of a query. To do this, use the "*" sign:

SELECT * FROM Commodity

  • Additionally SELECT supports:
  • Sorting data (ORDER BY operator)
  • Selection according to conditions (WHERE)
  • Grouping term (GROUP BY)

Add the line

To add a row to the table, SQL queries with the INSERT statement are used. The addition can be done in three ways:

  • add a new whole line;
  • part of a string;
  • query results.

To add a complete row, you must specify the table name and the values ​​of the columns (fields) of the new row. Let's give an example:

INSERT INTO Commodity VALUES ("106", "50", "Coca-Cola", "1.68", "No Alcogol,)

The example adds a new product to the table. Values ​​are specified after VALUES for each column. If there is no corresponding value for the column, then NULL must be specified. Columns are filled with values ​​in the order specified when the table was created.

If you add only a part of a row, you must explicitly specify the names of the columns, as in the example:

INSERT INTO Commodity (commodity_id, vendor_id, commodity_name)

VALUES ("106", '50 "," Coca-Cola ",)

We entered only the identifiers of the product, supplier and its name, and left the rest of the fields empty.

Adding Query Results

INSERT is mainly used to add rows, but it can also be used to add the results of a SELECT statement.

Data change

To change the information in the fields of the database table, you must use the UPDATE statement. The operator can be used in two ways:

  • All rows in the table are updated.
  • For a specific line only.

UPDATE has three main elements:

  • the table in which you need to make changes;
  • field names and their new values;
  • conditions for selecting rows to change.

Let's look at an example. Let's say the cost of an item with ID = 106 has changed, so this line needs to be updated. We write the following operator:

UPDATE Commodity SET commodity_price = "3.2" WHERE commodity_id = "106"

We indicated the name of the table, in our case Commodity, where the update will be performed, then after SET - the new value of the column and found the required record by specifying the required ID value in WHERE.

To modify multiple columns, multiple column-value pairs are specified after the SET statement, separated by commas. Let's see an example that updates the name and price of a product:

UPDATE Commodity SET commodity_name = 'Fanta', commodity_price = "3.2" WHERE commodity_id = "106"

To remove information in a column, you can set it to NULL if the table structure allows it. It should be remembered that NULL is exactly "no" value, and not zero in the form of text or numbers. Let's delete the product description:

UPDATE Commodity SET commodity_desc = NULL WHERE commodity_id = "106"

Deleting Rows

SQL queries to delete rows in a table are executed by the DELETE statement. There are two use cases:

  • certain rows are deleted in the table;
  • all rows in the table are deleted.

An example of deleting one row from a table:

DELETE FROM Commodity WHERE commodity_id = "106"

After DELETE FROM we specify the name of the table in which the rows will be deleted. The WHERE clause contains a condition by which the rows for deletion will be selected. In the example, we are deleting the line for the product with ID = 106. It is very important to specify WHERE. omitting this statement will delete all rows in the table. This also applies to changing the value of the fields.

The DELETE statement does not include column names or metacharacters. It deletes rows entirely, but it cannot delete a single column.

Using SQL in Microsoft Access

It is usually used interactively to create tables, databases, to manage, modify, analyze data in a database and to embed SQL Access queries through a convenient interactive query designer (Query Designer), using which you can build and immediately execute SQL statements of any complexity ...

The mode of access to the server is also supported, in which the Access DBMS can be used as a generator of SQL queries to any ODBC data source. This capability allows Access applications to interact with any format.

SQL extensions

Since SQL queries do not have all the capabilities of procedural programming languages ​​such as loops, branches, etc., database vendors develop their own version of SQL with advanced capabilities. First of all, this is support for stored procedures and standard operators of procedural languages.

The most common dialects of the language:

  • Oracle Database - PL / SQL
  • Interbase, Firebird - PSQL
  • Microsoft SQL Server - Transact-SQL
  • PostgreSQL - PL / pgSQL.

SQL on the Internet

MySQL is distributed under the GNU General Public License. There is a commercial license with the ability to develop custom modules. As an integral part, it is included in the most popular assemblies of Internet servers, such as XAMPP, WAMP and LAMP, and is the most popular DBMS for developing applications on the Internet.

It was developed by Sun Microsystems and is currently supported by Oracle Corporation. Databases up to 64 terabytes, SQL: 2003 syntax standard, database replication and cloud services are supported.

Table expressions subqueries are named and are used where the table is expected to exist. There are two types of table expressions:

    derived tables;

    generalized table expressions.

These two forms of table expressions are discussed in the following subsections.

Derived tables

Derived table is a table expression included in the FROM clause of the query. Derived tables can be used when column aliases are not feasible because the SQL translator processes another statement before the alias is known. The example below attempts to use a column alias in a situation where another clause is processed before the alias is known:

USE SampleDb; SELECT MONTH (EnterDate) as enter_month FROM Works_on GROUP BY enter_month;

Attempting to execute this query will result in the following error message:

Msg 207, Level 16, State 1, Line 5 Invalid column name "enter_month". (Msg 207: Level 16, State 1, Line 5 Invalid column name enter_month)

The cause of the error is that the GROUP BY clause is processed before the associated SELECT list is processed, and the enter_month column alias is not known when processing this group.

This problem can be solved by using a derived table that contains the preceding query (without the GROUP BY clause), since the FROM clause is executed before the GROUP BY clause:

USE SampleDb; SELECT enter_month FROM (SELECT MONTH (EnterDate) as enter_month FROM Works_on) AS m GROUP BY enter_month;

The result of executing this query will be like this:

Typically, the table expression can be placed anywhere in the SELECT statement where the table name might appear. (The result of a table expression is always a table or, in special cases, an expression.) The following example shows the use of a table expression in the select list of a SELECT statement:

The result of this query:

Generalized table expressions

Common Table Expression (CTE) is a named table expression supported by the Transact-SQL language. Generic table expressions are used in the following two types of queries:

    non-recursive;

    recursive.

These two types of requests are discussed in the following sections.

OTB and non-recursive queries

You can use the non-recursive OTB form as an alternative to derived tables and views. Usually OTB is defined by WITH clauses and an optional query that references the name used in the WITH clause. The WITH keyword is ambiguous in Transact-SQL. To avoid ambiguity, terminate the statement preceding the WITH clause with a semicolon.

USE AdventureWorks2012; SELECT SalesOrderID FROM Sales.SalesOrderHeader WHERE TotalDue> (SELECT AVG (TotalDue) FROM Sales.SalesOrderHeader WHERE YEAR (OrderDate) = "2005") AND Freight> (SELECT AVG (TotalDue) FROM Sales.SalesOrderHeader WHERE YEAR (OrderDate 2005 ") /2.5;

The query in this example selects orders whose total taxes (TotalDue) are greater than the average for all taxes, and whose freight charges (Freight) are greater than 40% of the average for taxes. The main property of this query is its volume, since the subquery needs to be written twice. One possible way to reduce the size of the query construct is to create a view that contains a subquery. But this solution is somewhat difficult, since it requires creating a view, and then deleting it after the end of the query execution. The best approach would be to create an OTB. The example below demonstrates the use of non-recursive OTB, which abbreviates the query definition above:

USE AdventureWorks2012; WITH price_calc (year_2005) AS (SELECT AVG (TotalDue) FROM Sales.SalesOrderHeader WHERE YEAR (OrderDate) = "2005") SELECT SalesOrderID FROM Sales.SalesOrderHeader WHERE TotalDue> (SELECT year_2005 FROM price_calc) AND Fre2005) /2.5;

The syntax for the WITH clause in non-recursive queries is:

The cte_name parameter represents the OTB name that identifies the resulting table, and the column_list parameter represents the list of columns in the table expression. (In the example above, the OTB is named price_calc and has one column, year_2005.) The inner_query parameter represents a SELECT statement that defines the result set of the corresponding table expression. The defined table expression can then be used in the outer_query outer query. (The outer query in the example above uses the OTB price_calc and its column year_2005 to simplify the double-nested query.)

OTB and recursive queries

This section presents material of increased complexity. Therefore, when reading it for the first time, it is recommended to skip it and return to it later. OTBs can implement recursions since OTBs can contain references to themselves. The basic OTB syntax for a recursive query looks like this:

The cte_name and column_list parameters have the same meaning as in OTB for non-recursive queries. The WITH clause body consists of two queries combined by the operator UNION ALL... The first query is called only once and it starts accumulating the result of the recursion. The first operand of the UNION ALL operator does not refer to OTB. This query is called a reference query or source.

The second request contains a link to OTB and represents its recursive part. Because of this, it is called a recursive member. In the first call to the recursive part, the OTB reference represents the result of the reference query. The recursive member uses the result of the first call to the query. After that, the system calls the recursive part again. A call to a recursive member is terminated when a previous call to it returns an empty result set.

The UNION ALL operator concatenates the currently accumulated strings, as well as additional strings added by the current call to the recursive member. (The presence of the UNION ALL operator means that duplicate rows will not be removed from the result.)

Finally, the outer_query parameter defines an outer query that uses OTB to get all calls to the union of both members.

To demonstrate a recursive OTB form, we use the Airplane table defined and populated with the code shown in the example below:

USE SampleDb; CREATE TABLE Airplane (ContainingAssembly VARCHAR (10), ContainedAssembly VARCHAR (10), QuantityContained INT, UnitCost DECIMAL (6,2)); INSERT INTO Airplane VALUES ("Airplane", "Fuselage", 1, 10); INSERT INTO Airplane VALUES ("Airplane", "Wings", 1, 11); INSERT INTO Airplane VALUES ("Airplane", "Tail", 1, 12); INSERT INTO Airplane VALUES ("Fuselage", "Salon", 1, 13); INSERT INTO Airplane VALUES ("Fuselage", "Cabin", 1, 14); INSERT INTO Airplane VALUES ("Fuselage", "Nose", 1, 15); INSERT INTO Airplane VALUES ("Salon", NULL, 1.13); INSERT INTO Airplane VALUES ("Cabin", NULL, 1, 14); INSERT INTO Airplane VALUES ("Nose", NULL, 1, 15); INSERT INTO Airplane VALUES ("Wings", NULL, 2, 11); INSERT INTO Airplane VALUES ("Tail", NULL, 1, 12);

The Airplane table has four columns. The ContainingAssembly column identifies the assembly, and the ContainedAssembly column identifies the parts (one after the other) that make up the corresponding assembly. The figure below provides a graphical illustration of a possible type of aircraft and its constituent parts:

The Airplane table consists of the following 11 rows:

The example below shows the WITH clause used to define a query that calculates the total cost of each assembly:

USE SampleDb; WITH list_of_parts (assembly1, quantity, cost) AS (SELECT ContainingAssembly, QuantityContained, UnitCost FROM Airplane WHERE ContainedAssembly IS NULL UNION ALL SELECT a.ContainingAssembly, a.QuantityContained, CAST (l.quantity * l.cost AS DECIMAL (6,2) ) FROM list_of_parts l, Airplane a WHERE l.assembly1 = a.ContainedAssembly) SELECT assembly1 "Part", quantity "Qty", cost "Price" FROM list_of_parts;

The WITH clause defines an OTB list named list_of_parts with three columns: assembly1, quantity, and cost. The first SELECT statement in the example is called only once to preserve the results of the first step of the recursion process. The SELECT statement on the last line of the example displays the following result.

Last update: 07/05/2017

In the previous topic, a simple database with one table was created in SQL Management Studio. Now let's define and execute the first SQL query. To do this, open SQL Management Studio, right-click on the top-level element in the Object Explorer (server name) and select New Query in the context menu that appears:

After that, a window for entering SQL commands will open in the central part of the program.

Let's run a query to the table that was created in the previous topic, in particular, we will get all the data from it. Our database is called university, and the table is dbo.Students, so to get data from the table, we will enter the following query:

SELECT * FROM university.dbo.Students

The SELECT statement allows you to select data. FROM indicates the source from where to get the data. In fact, with this query, we say "SELECT all FROM table university.dbo.Students". It is worth noting that for the name of the table, its full path is used, indicating the database and schema.

After entering the query, click on the Execute button on the toolbar, or you can press the F5 key.

As a result of the query execution, a small table appears at the bottom of the program that displays the query results - that is, all the data from the Students table.

If we need to make multiple queries to the same database, then we can use the USE command to commit the database. In this case, when making queries to the tables, it is enough to specify their name without the name of the database and schema:

USE university SELECT * FROM Students

In this case, we are performing a request for the server as a whole; we can access any database on the server. But we can also execute queries only within a specific database. To do this, right-click on the required database and select the New Query item in the context menu:

If in this case we want to execute a query to the table Students used above, then we would not have to indicate the name of the database and the schema in the query, since these values ​​would already be clear.