An example of creating a query (Query) in a MS SQL Server database. The database is located in a local *.mdf file. How to Write SQL Queries - Detailed Examples Placing a DataGridView Control and Setting Up Database Communications

An example of creating a query (Query) in a MS SQL Server database. The database is located in a local *.mdf file. How to Write SQL Queries - Detailed Examples Placing a DataGridView Control and Setting Up Database Communications

An example of creating a query (Query) in a MS SQL Server database. The database is located in a local *.mdf file

The task

A database has been specified, which is located in the Education.mdf file. The database contains two interconnected tables Student and Session.

The tables are linked to each other by the ID_Book field.

Using Microsoft Visual Studio tools, create a query named Query1, which will have the following structure:

Field name Table
Num_Book Student
Name Student
Mathematics Session
Informatics Session
Philosophy Session
Average Computational field

Execution (step by step instructions)

1. Download Microsoft Visual Studio
2. Connect the Education.mdf database to the list of databases in the Server Explorer utility

In order not to waste time on developing and linking tables of the Education.mdf database, an archive of a previously prepared database can be downloaded. After downloading and saving in a certain folder, the database needs to be unzipped and connected to the list of databases in the Server Explorer utility.

Connecting a database is implemented in one of several standard ways:

  • selecting the “Connect to Database...” command from the Tools menu;
  • selecting the button (command) “Connect to Database...” from the Server Explorer utility.

As a result, a wizard window will open in which, using several steps (windows), you need to configure the database connection.

Rice. 1. Methods for adding/connecting a database

A detailed description of how to connect a database such as Microsoft SQL Server in Microsoft Visual Studio is given in the topic:

  • Example of creation/connection I local Microsoft SQL Server database, which is located in a *.mdf file

After connecting, the Server Explorer utility window will look like shown in Figure 2.

Rice. 2. Server Explorer utility with connected Education.mdf database

3. Adding a new request. New Query Team

You can create queries against the database. In our case, we need to create a request in accordance with the task conditions.

The query is created using the “New Query” command, which is called from the context menu (Figure 3). To call the command, just right-click in the field area that is highlighted for displaying the Education.mdb database elements. It should be noted that requests are not saved by the system. Views are used to display saved (complex) queries.

Figure 3 shows the context menu that is called up when you click on the Views tab. In this menu you need to select the command “New Query”. This command is in the list of context menus of other database components (tables, charts, etc.).

Rice. 3. New Query command

As a result, the “Add Table” window will open, in which you need to select the tables whose data will be used in the query (Figure 4).

Rice. 4. Selecting the tables to be used in the query

For our case, we need to select both tables.

As a result, the Microsoft Visual Studio window will look like shown in Figure 5.

Rice. 5. MS Visual Studio window after creating a request

In the tables, you need to select the fields that will be used in the query. The order in which fields are selected must correspond to how they are displayed in the request in accordance with the task conditions. This means that first the fields of the Student table are selected (NumBook, Name), and then the fields of the Session table are selected (Mathematics, Informatics, Philosophy).

For our case, the choice of fields is shown in Figure 6.

Rice. 6. Selecting fields for the request

As can be seen from Figure 6, a query in SQL language generated by the system is displayed at the bottom of the window

SELECT Student.Num_Book, Student.Name, Session.Mathematics, Session.Informatics, Session.Philosophy FROM
4. Add a calculated field Average

To create a calculated field Average , you need to change the text of this query in the window where the SQL query is displayed. For example:

SELECT Student.Num_Book, Student.Name, Session.Mathematics, Session.Informatics, Session.Philosophy, (Session.Mathematics + Session.Informatics + Session.Philosophy) / 3.0 AS Average FROM Session INNER JOIN Student ON Session.ID_Book = Student.ID_Book

The calculation field Average is added, which is the arithmetic mean (Figure 7).

SQL - Structured Query Language.
In this review we will look at the most common types of SQL queries.
The SQL standard is defined ANSI(American National Standards Institute).
SQL is a language aimed specifically at relational databases.

SQL partitioning:


DDL
(Data Definition Language) - the so-called Schema Description Language in ANSI, consists of commands that create objects (tables, indexes, views, and so on) in the database.
DML(Data Manipulation Language) is a set of commands that determine what values ​​are represented in tables at any given time.
DCD(Data Management Language) consists of facilities that determine whether to allow a user to perform certain actions or not. They are part of ANSI DDL. Don't forget these names. These are not different languages, but sections of SQL commands grouped by their functions.

Data types:

SQL Server - Data Types

Description

bigint (int 8)

bigint (int 8)

binary(n)

binary(n) or image

character
(synonym char)

national character or ntext

character varying(synonym char varying varchar)

national character varying or ntext

Datetime

datetime

decimal

aka numeric

double precision

double precision

integer (int 4) (synonym: int)

integer (int 4)

national character(synonym: national character, nchar)

national character

Numeric(synonyms: decimal, dec)

national character varying(synonyms: national char varying, nvarchar)

National character varying

Smalldatetime

datetime

smallint (int 2)

smallint (int 2)

Smallmoney

sql_variant

No longer supported

Ntext
Starting with SQL Server 2005, it is not recommended for use.

Timestamp

Not supported

tinyint (int 1)

tinyint (int 1)

Uniqueidentifier

uniqueidentifier

varbinary(n)

varbinary(n) or image

smalldatetime

datetime

smallint (int 2)

smallint (int 2)

smallmoney

sql_variant

Not supported

timestamp

Not supported

tinyint (int 1)

tinyint (int 1)

uniqueidentifier

uniqueidentifier

varbinary(n)

varbinary(n) or image

Data Type Table in SQL Server 2000

WHAT IS A REQUEST?

Request is a command you give to your database program. Queries are part of the DML language. All SQL queries consist of a single command. The structure of this command is deceptively simple because you must extend it to perform highly complex evaluations and data manipulations.

SELECT command:

SELECT“Select” is the most frequently used command; it is used to select data from the table.
Type of query using SELECT:

SELECT id, user_name, city, birth_day FROM users_base;

Such a query will display from the users_base table all the values ​​of the columns specified separated by commas after the SELECT command. Also, you can display all columns with one character, * i.e. SELECT * FROM users_base ; - such a query will display all data from the table.

SELECT command structure:

SELECT (Column names separated by commas that need to be displayed in the query) FROM (table name in the database)
- This is the simplest type of request. There are additional commands for convenient data retrieval (see below “Functions”)

DML commands:

Values ​​can be placed and removed from fields using three DML (Data Manipulation Language) commands:
INSERT(Insert)
UPDATE(Update, modification),
DELETE(Delete)

INSERT command:

INSERT INTO users_base (user_name, city, birth_day) VALUES ('Alexander', 'Rostov', '06/20/1991');

The INSERT command comes with the prefix INTO (in to), then in brackets are the names of the columns into which we must insert data, then comes the VALUES command (values) and in brackets the values ​​come in turn (it is necessary to observe the order of the values ​​with the columns , the values ​​must be in the same order as the columns you specified).

UPDATE command:

UPDATE users_base SET user_name = 'Alexey';

The UPDATE command updates values ​​in a table. First comes the UPDATE command itself, then the table name, after the SET command (set), then the column name and its value in quotes (quotes are placed if the value is in string format, if it is a numeric value and the column is not tied to the data type vchar or any other string types, the quotes have no meaning.)

DELETE command:

DELETE FROM users_base WHERE user_name = 'Vasily';

The DELETE command deletes the entire row and identifies the row using the WHERE criterion. In this case, this query would delete all rows in which the user_name column value was Vasily. We'll talk about the WHERE criterion and others a little later.

Criteria, functions, conditions, etc. what helps us in SQL:

WHERE clause is a clause of the SELECT command and other DML commands that allows you to set predicates whose condition can be either true or false for any row in the table. The command retrieves only those rows from the table for which this statement is true.
Example:
SELECT id, city, birth_day FROM users_base WHERE user_name = ‘Alexey’;- such a query will display only those rows that match the WHERE condition, namely all rows in which the user_name column has the value Alexey.

ORDER BY - condition for sorting the selected rows. Has 2 criteria ASC and DESC. ASC (sorting from A to Z or from 0 to 9)

DESC (opposite of ASC).
Example:
SELECT id, city, birth_day FROM users_base ORDER BY user_name ASC; - such a query will display values ​​sorted by the user_name column from A to Z (A-Z; 0-9)

This condition can also be used in conjunction with the WHERE clause.
Example:
SELECT id, city, birth_day FROM users_base WHERE user_name = ‘Alexey’ ORDER BY id ASC;

DISTINCT is an argument that provides you with a way to eliminate double values ​​from your SELECT clause. Those. if you have duplicate values ​​in a column, let’s say user_name, then DISTINCT will show you only one value, for example, you have 2 people named Alexey in your database, then a query using the DISTINCT function will show you only 1 value that is encountered first...
Example:
SELECT DISTINCT user_name FROM users_base;- such a query will show us the values ​​of all records in the user_name column, but they will not be repeated, i.e. if you had an infinite number of repeating values, then they will not be shown...

AND - takes two Boolean (in the form A AND B) as arguments and evaluates them against the truth whether they are both true.
Example:
SELECT * FROM users_base WHERE city = 'Rostov' AND user_name = 'Alexander';- will display all the values ​​from the table where the name of the city appears in one line (in this case, Rostov and the user name Alexander.

OR - takes two Boolean (in the form A OR B) as arguments and evaluates whether one of them is correct.

SELECT * FROM users_base WHERE city = 'Rostov' OR user_name = 'Alexander';- will display all values ​​from the table where the name of the city of Rostov or the username Alexander appears in the line.

NOT - takes a single Boolean (in the form NOT A) as arguments and changes its value from false to true or true to false.
SELECT * FROM users_base WHERE city = 'Rostov' OR NOT user_name = 'Alexander';- will display all values ​​from the table where the name of the city of Rostov appears in one line or the user name is not exactly Alexander.

IN - defines a set of values ​​in which a given value may or may not be included.
SELECT * FROM users_base WHERE city IN ('Vladivostok', 'Rostov');- such a query will display all values ​​from the table that contain the names of the specified cities in the city column

Between is similar to the IN operator. Unlike defining by numbers from a set, as IN does, BETWEEN defines a range whose values ​​must decrease to make the predicate true.
SELECT * FROM users_base WHERE id BETWEEN 1 AND 10;- displays all values ​​from the table that will be in the range from 1 to 10 in the id column

COUNT - Produces the row numbers or non-NULL values ​​of the fields that the query selected.
SELECT COUNT (*) FROM users_base ;- will display the number of rows in this table.
SELECT COUNT (DISTINCT user_name) FROM users_base ;- will display the number of lines with user names (not repeated)

SUM - produces the arithmetic sum of all selected values ​​for a given field.
SELECT SUM (id) FROM users_base ;- will display the sum of the values ​​of all rows of the id column.

AVG - averages all selected values ​​of this field.
SELECT AVG (id) FROM users_base ;- will display the average of all selected values ​​of the id column

MAX - produces the largest of all selected values ​​for this field.

MIN - produces the smallest of all selected values ​​for this field.

Creating tables:

CREATE TABLE users_base (id integer, user_name text, city text, birth_day datetime);- executing such a command will lead to the creation of the table for which I gave examples... Everything is simple here, we write the CREATE TABLE command, followed by the name of the table that we want to create, then in parentheses, separated by commas, the names of the columns and their data type. This is the standard way to create a table in SQL. Now I will give an example of creating tables in SQL Server 2005:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N."") AND type in (N"U"))
BEGIN
CREATE TABLE .(

NOT NULL,
NOT NULL,
NOT NULL,
PRIMARY KEY CLUSTERED
A.S.C.


END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N."") AND type in (N"U"))
BEGIN
CREATE TABLE .(
IDENTITY(1,1) NOT NULL,
NULL,
NULL,
PRIMARY KEY CLUSTERED
A.S.C.
)WITH (IGNORE_DUP_KEY = OFF) ON
) ON TEXTIMAGE_ON
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N."") AND type in (N"U"))
BEGIN
CREATE TABLE .(
IDENTITY(1,1) NOT NULL,
NULL,
NULL,
PRIMARY KEY CLUSTERED
A.S.C.
)WITH (IGNORE_DUP_KEY = OFF) ON
) ON
END

Syntax in SQL Server 2005 is another topic, I just wanted to show that I described the basics of SQL programming, you can reach the top by yourself knowing the basics.

If you have any questions on this topic, please write to me

SQL or Structured Query Language is a language used to manage data in a relational database system (RDBMS). This article will cover commonly used SQL commands that every programmer should be familiar with. This material is ideal for those who want to brush up on their knowledge of SQL before a job interview. To do this, look at the examples given in the article and remember that you studied databases in pairs.

Note that some database systems require a semicolon at the end of each statement. The semicolon is the standard pointer to the end of every statement in SQL. The examples use MySQL, so a semicolon is required.

Setting up a database for examples

Create a database to demonstrate how teams work. To work, you will need to download two files: DLL.sql and InsertStatements.sql. After that, open a terminal and log into the MySQL console using the following command (the article assumes that MySQL is already installed on the system):

Mysql -u root -p

Then enter your password.

Run the following command. Let's call the database “university”:

CREATE DATABASE university; USE university; SOURCE ; SOURCE

Commands for working with databases

1. View available databases

SHOW DATABASES;

2. Create a new database

CREATE DATABASE;

3. Selecting a database to use

USE ;

4. Import SQL commands from a .sql file

SOURCE ;

5. Delete the database

DROP DATABASE ;

Working with tables

6. View the tables available in the database

SHOW TABLES;

7. Create a new table

CREATE TABLE ( , , PRIMARY KEY ( ), FOREIGN KEY ( ) REFERENCES ());

Integrity Constraints When Using CREATE TABLE

You may need to create restrictions on certain columns in a table. When creating a table, you can set the following restrictions:

  • a table cell cannot have a NULL value;
  • primary key - PRIMARY KEY (col_name1, col_name2, ...) ;
  • foreign key - FOREIGN KEY (col_namex1, …, col_namexn) REFERENCES table_name(col_namex1, …, col_namexn) .

You can specify more than one primary key. In this case, you will get a composite primary key.

Example

Create a table "instructor":

CREATE TABLE instructor (ID CHAR(5), name VARCHAR(20) NOT NULL, dept_name VARCHAR(20), salary NUMERIC(8,2), PRIMARY KEY (ID), FOREIGN KEY (dept_name) REFERENCES department(dept_name));

8. Table information

You can view various information (value type, key or not) about table columns with the following command:

DESCRIBE ;

9. Adding data to the table

INSERT INTO (, , , ...) VALUES ( , , , …);

When you add data to each column in a table, you do not need to specify column names.

INSERT INTO VALUES ( , , , …);

10. Updating table data

UPDATE SET = , = , ... WHERE ;

11. Removing all data from the table

DELETE FROM ;

12. Delete a table

DROP TABLE ;

Commands for creating queries

13. SELECT

SELECT is used to retrieve data from a specific table:

SELECT , , … FROM ;

The following command can display all the data from the table:

SELECT * FROM ;

14. SELECT DISTINCT

Table columns may contain duplicate data. Use SELECT DISTINCT to retrieve only non-duplicate data.

SELECT DISTINCT , , … FROM ;

15. WHERE

You can use the WHERE keyword in SELECT to specify conditions in a query:

SELECT , , … FROM WHERE ;

The following conditions can be specified in the request:

  • text comparison;
  • comparison of numerical values;
  • logical operators AND (and), OR (or) and NOT (negation).

Example

Try the following commands. Pay attention to the conditions specified in WHERE:

SELECT * FROM course WHERE dept_name=’Comp. Sci.'; SELECT * FROM course WHERE credits>3; SELECT * FROM course WHERE dept_name="Comp. Sci." AND credits>3;

16. GROUP BY

The GROUP BY operator is often used with aggregate functions such as COUNT, MAX, MIN, SUM, and AVG to group output values.

SELECT , , … FROM GROUP BY ;

Example

Let's display the number of courses for each faculty:

SELECT COUNT(course_id), dept_name FROM course GROUP BY dept_name;

17. HAVING

The HAVING keyword was added to SQL because WHERE cannot be used with aggregate functions.

SELECT , , ... FROM GROUP BY HAVING

Example

Let's display a list of faculties that have more than one course:

SELECT COUNT(course_id), dept_name FROM course GROUP BY dept_name HAVING COUNT(course_id)>1;

18. ORDER BY

ORDER BY is used to sort query results in descending or ascending order. ORDER BY will sort in ascending order unless ASC or DESC is specified.

SELECT , , … FROM ORDER BY , , …ASC|DESC;

Example

Let's display a list of courses in ascending and descending order of credits:

SELECT * FROM course ORDER BY credits; SELECT * FROM course ORDER BY credits DESC;

19. BETWEEN

BETWEEN is used to select data values ​​from a specific range. Numeric and text values, as well as dates, can be used.

SELECT , , … FROM WHERE BETWEEN AND ;

Example

Let's display a list of instructors whose salary is more than 50,000, but less than 100,000:

SELECT * FROM instructor WHERE salary BETWEEN 50000 AND 100000;

20. LIKE

The LIKE operator is used in WHERE to specify a search pattern for a similar value.

There are two free operators that are used in LIKE:

  • % (none, one or more characters);
  • _ (one character).
SELECT , , … FROM WHERE LIKE ;

Example

Let's display a list of courses whose names contain "to" and a list of courses whose names begin with "CS-":

SELECT * FROM course WHERE title LIKE ‘%to%’; SELECT * FROM course WHERE course_id LIKE "CS-___";

21. IN

Using IN you can specify multiple values ​​for the WHERE clause:

SELECT , , … FROM WHERE IN ( , , …);

Example

Let's display a list of students from Comp majors. Sci., Physics and Elec. Eng.:

SELECT * FROM student WHERE dept_name IN ('Comp. Sci.', 'Physics', 'Elec. Eng.');

22. JOIN

JOIN is used to link two or more tables using common attributes within them. The image below shows the different ways to join in SQL. Note the difference between a left outer join and a right outer join:

SELECT , , … FROM JOIN ON = ;

Example 1

We will display a list of all courses and relevant information about the faculties:

SELECT * FROM course JOIN department ON course.dept_name=department.dept_name;

Example 2

We will display a list of all required courses and details about them:

SELECT prereq.course_id, title, dept_name, credits, prereq_id FROM prereq LEFT OUTER JOIN course ON prereq.course_id=course.course_id;

Example 3

We will display a list of all courses, regardless of whether they are required or not:

SELECT course.course_id, title, dept_name, credits, prereq_id FROM prereq RIGHT OUTER JOIN course ON prereq.course_id=course.course_id;

23. View

View is a virtual SQL table created as a result of executing an expression. It contains rows and columns and is very similar to a regular SQL table. View always shows the latest information from the database.

Creation

CREATE VIEW AS SELECT , , … FROM WHERE ;

Removal

DROP VIEW ;

Example

Let's create a view consisting of courses with 3 credits:

24. Aggregate functions

These functions are used to obtain an aggregate result related to the data in question. The following are commonly used aggregate functions:

  • COUNT (col_name) - returns the number of rows;
  • SUM (col_name) - returns the sum of the values ​​in this column;
  • AVG (col_name) - returns the average value of a given column;
  • MIN (col_name) - returns the smallest value of a given column;
  • MAX (col_name) - Returns the largest value of a given column.

25. Nested subqueries

Nested subqueries are SQL queries that include SELECT , FROM , and WHERE clauses nested within another query.

Example

Let's find courses that were taught in the fall of 2009 and spring of 2010:

SELECT DISTINCT course_id FROM section WHERE semester = 'Fall' AND year= 2009 AND course_id IN (SELECT course_id FROM section WHERE semester = 'Spring' AND year= 2010);

Each of us regularly encounters and uses various databases. When we select an email address, we are working with a database. Databases are used by search services, banks to store customer data, etc.

But despite the constant use of databases, even for many software system developers there are still many blind spots due to different interpretations of the same terms. We'll give a brief definition of basic database terms before covering the SQL language. So.

Database - a file or collection of files for storing ordered data structures and their relationships. Very often a management system is called a database - it is only a repository of information in a specific format and can work with various DBMSs.

Table - Let's imagine a folder in which documents are stored, grouped according to a certain characteristic, for example, a list of orders for the last month. This is a table in a computer. A separate table has its own unique name.

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

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

Primary key- Each row of a table can have one or more columns to uniquely identify it. Without a primary key, it is very difficult to update, change, and delete relevant rows.

What is SQL?

SQL(English - structured query language) was developed only for working with databases and is currently the standard for all popular DBMSs. The language syntax consists of a small number of operators and is easy to learn. But, despite its apparent 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 DBMS market leaders, such as ORACLE. It is impossible to consider all the capabilities of the language in one short article, so we will briefly consider only basic SQL queries. Examples clearly show the simplicity and capabilities of the language:

  • creating databases and tables;
  • data sampling;
  • adding records;
  • modification and deletion of information.

SQL Data Types

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

We create tables and databases

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

  • via the DBMS console
  • Using the interactive 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 using 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:

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 consists of five columns. After the name comes the data type, the columns are separated by commas. The column value can accept empty values ​​(NULL) or must be filled (NOT NULL), and this is determined when the table is created.

Retrieving data from a table

The data fetch operator is the most commonly used SQL query. To obtain information, we must indicate what we want to select from such a table. First a simple example:

SELECT commodity_name FROM Commodity

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

The result of the query will be all rows of the table with 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.

To query for several fields, 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 query result. 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 a line

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

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

To add a full row, you must specify the table name and the values ​​of the columns (fields) of the new row. Here's 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 listed after VALUES for each column. If there is no corresponding value for the column, then NULL must be specified. The columns are populated with values ​​in the order specified when the table was created.

If you add only 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 remaining fields blank.

Adding Query Results

INSERT is primarily used to append rows, but can also be used to append the results of a SELECT statement.

Changing data

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

  • All rows in the table are updated.
  • Only for a specific line.

UPDATE consists of three main elements:

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

Let's look at an example. Let's say the price of a product 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 specified 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 desired record by specifying the required ID value in WHERE.

To change multiple columns, the SET statement is followed by multiple column-value pairs separated by commas. Let's look at an example in which the name and price of a product are updated:

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

To remove information in a column, you can assign it the value NULL if the table structure allows it. It must be remembered that NULL is precisely “no” value, and not zero in the form of text or number. Let's remove the product description:

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

Removing rows

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

  • Certain rows in the table are deleted;
  • 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 indicate the name of the table in which the rows will be deleted. The WHERE clause contains the condition by which rows will be selected for deletion. In the example, we delete the product line with ID=106. Specifying WHERE is very important because omitting this statement will delete all rows in the table. This also applies to changing the value of fields.

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

Using SQL in Microsoft Access

Typically used interactively to create tables, databases, to manage, modify, analyze data in a database and to implement 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 server access mode is also supported, in which the Access DBMS can be used as a generator of SQL queries to any ODBC data source. This feature 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, branching, etc., DBMS manufacturers are developing 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

The MySQL DBMS is distributed under the free GNU General Public License. There is a commercial license with the ability to develop custom modules. As a component, 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 in size, SQL:2003 syntax standard, replication of databases and cloud services are supported.

Table expressions are called subqueries that are used where the presence of a table is expected. 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 a query. Derived tables can be used in cases where using column aliases is not possible because the SQL translator processes another statement before the alias is known. The example below shows an attempt to use a column alias in a situation where another clause is being processed before the alias is known:

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

Trying to run this query will produce the following error message:

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

The reason for the error is that the GROUP BY clause is processed before the corresponding list of the SELECT statement is processed, and the enter_month column alias is unknown when the group is processed.

This problem can be solved by using a derived table that contains the preceding query (without the GROUP BY clause) because 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 this query will be like this:

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

The result of this query:

Generic table expressions

Common Table Expression (OTB) is a named table expression supported by the Transact-SQL language. Common 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

The non-recursive form of OTB can be used as an alternative to derived tables and views. Typically OTB is determined by WITH clauses and an additional query that references the name used in the WITH clause. In Transact-SQL, the meaning of the WITH keyword is ambiguous. To avoid ambiguity, the statement preceding the WITH statement should be terminated 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 of all taxes and whose freight charges (Freight) are greater than 40% of the average taxes. The main property of this query is its length, since the subquery needs to be written twice. One possible way to reduce the amount of query construction is to create a view that contains a subquery. But this solution is a bit complicated because it requires creating a view and then deleting it after the query has finished executing. A better approach would be to create an OTB. The example below shows the use of non-recursive OTB, which shortens 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 Freight > (SELECT year_2005 FROM price_cal c) /2.5;

The WITH clause syntax in non-recursive queries is as follows:

The cte_name parameter represents the OTB name that defines the resulting table, and the column_list parameter represents the list of columns of the table expression. (In the example above, the OTB is called price_calc and has one column, year_2005.) The inner_query parameter represents a SELECT statement that specifies the result set of the corresponding table expression. The defined table expression can then be used in the outer_query. (The outer query in the example above uses OTB price_calc and its year_2005 column to simplify the doubly 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 be used to implement recursions because 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 body of a WITH clause consists of two queries combined by the operator UNION ALL. The first query is called only once, and it begins to accumulate the result of the recursion. The first operand of the UNION ALL operator does not reference OTB. This query is called a reference query or source.

The second query contains a reference to the 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 query call. After this, the system calls the recursive part again. A call to a recursive member stops when a previous call to it returns an empty result set.

The UNION ALL operator joins the currently accumulated rows, as well as additional rows 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 specifies the outer query that OTB uses to retrieve all calls to the join of both members.

To demonstrate the recursive form of OTB, 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", "Cockpit", 1, 14); INSERT INTO Airplane VALUES ("Fuselage", "Nose",1, 15); INSERT INTO Airplane VALUES ("Cabin", NULL, 1,13); INSERT INTO Airplane VALUES ("Cockpit", 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 by one) that make up the corresponding assembly. The figure below shows a graphic illustration of a possible type of aircraft and its component parts:

The Airplane table consists of the following 11 rows:

The following example uses the WITH clause to define a query that calculates the total cost of each build:

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 "Quantity", cost "Price" FROM list_of_parts;

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

views