Using functions in sql queries. SQL aggregate functions - SUM, MIN, MAX, AVG, COUNT. Selecting a Database to Use

Built-in functions SQL designed to facilitate and speed up data processing. The special feature is that they can be specified directly in the expression. All built-in functions can be divided into groups.

Mathematical functions:

    ABS(meaning) – returns the absolute value of a number;

    Round(value, accuracy) – returns a numeric value rounded to the value specified by the argument accuracy number of decimal places;

    SIGN(meaning) – returns minus if the number is negative, and plus otherwise;

    POWER(meaning, degree) – raises a number to a power;

    SQRT(meaning) – extracts the square root of a number;

    CEILING(meaning)– returns the nearest integer greater than or equal to the value;

    - FLOOR(meaning)– returns the nearest integer less than or equal to the value.

String functions:

    ASCII(line) – returns ASCII code of the first character of the line;

    CHAR(number) – return the character by ASCII code;

    LEN (line) – returns the length of the string in characters, excluding trailing spaces;

    LTRIM(line)/ RTRIM(line)- removes spaces at the beginning/end of a line;

    LEFT(string, number)/ RIGHT(string, number)– returns the specified argument number number of characters in the line, starting from the left/right edge;

    SUBSTRING(line, position, length) – returns a substring of the specified length from a string, starting from the specified position;

    LOWER(line) /UPPER(line) – returns a string converted to lowercase/uppercase etc.

Functions for working with dates:

    GETDATE() – returns a value that contains the date and time of the computer on which the instance of SQL Server is running;

    DAY(value_date)– returns a number from the specified date;

    MONTH(value_date)– returns the month number from the specified date;

    YEAR(value_date)– returns the year value from the specified date;

    DATENANE( part, value_date) – returns a character string representing the specified part ( Day, Month, Houretc.) from the specified date;

    DATEPART( part, value_date) – returns an integer representing the specified part ( Day, Month, Houretc.) from the specified date.

Data type conversion functions

    CAST (meaning AS data_type)

    CONVERT(data_type, meaning)

Argument meaning in functions specifies the value that needs to be converted.

7.3. Data Definition Language Commands

The Data Definition Language contains commands that are used to create, modify, and delete a database and its objects.

Creating a table

Creating a new table is done with the command CREATE TABLE. The command describes the structure of the table, each column of the table, and the integrity constraints that must be set on the table.

Command syntax:

CREATE TABLE table_name (( column_description |calculated_column_name AS expression | table_level_integrity_constraints) [, ...])

The table name is an identifier of no more than 128 characters.

A table can contain a calculated column, in which case the value of the column is determined by an expression that is stored in the table structure. A calculated column cannot be modified, so it cannot have NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, or DEFAULT integrity constraints.

The syntax for describing a table column is:

column_name data_type[(size)]

[(DEFAULT default_value | IDENTITY [(value, step)]}]

[column_level_integrity_constraints]

DEFAULT - allows you to specify the value assigned to the column in the newly added record.

IDENTITY – indicates that a column is being created that supports automatic numbering (counter column). Only one counter column can be defined in a table. The value parameter specifies the initial value of the counter, and the step parameter specifies the increment step. If these parameters are not specified, they have the value 1. IDENTITY can only be specified for those columns that are of integer or decimal types. Inserting values ​​into the IDENTITY column is not allowed.

There are two groups of integrity constraints processed by the DBMS:

Declarative integrity constraints, which are declared when a table is created or modified;

Procedural integrity constraints that are processed by triggers.

Declarative integrity constraints can be table-level constraints or table-level constraints. Column-level restrictions apply to only one column. Each declarative integrity constraint can be given a name.

Column level constraint definitions have the following syntax:

((PRIMARY KEY | UNIQUE | NOT NULL ) |FOREIGN KEY REFERENCES table_name( column_name)

|CHECK boolean_expression)

The data integrity constraint name must be unique within the database. Let's look at the constraints that can be defined at the column level:

Primary key constraint PRIMARY KEY. All table primary key values ​​must be unique and different from Null. A table can only have one primary key. If it is composite, then integrity constraints on the primary key are specified at the table level;

Constraints on the uniqueness of a UNIQUE column value. This means that a table cannot have two records that have the same value in that column;

A NOT NULL constraint that prohibits storing a NULL value in a column;

FOREIGN KEY foreign key constraint (referential integrity constraint). For a column that is a foreign key, REFERENCES specifies the name of the table to which the relationship is being established and the name of the column of that table on which the relationship will be established. This table is the main (parent) table in relation to the table being created. The main table column whose values ​​are being linked must have a PRIMARY KEY constraint set.

If the key of an external table consists of several fields, then the FOREIGN KEY constraint must be specified at the table level. In this case, you should list all the columns included in the foreign key, indicate the name of the main table and the names of the columns of the main table that are referenced by the foreign key.

Referential integrity establishes rules for adding and changing data in a table using a foreign key and its corresponding primary key constraint. The ON UPDATE and ON DELETE clauses for a foreign key define the following rules for changing related data:

NO ACTION – allows you to change (delete) only those values ​​in the main table that do not have corresponding foreign key values ​​in the child table. This rule is in effect by default;

CASCADE means that each foreign key value of a child table will be automatically changed (deleted) when the primary key value of the parent table is modified;

SET NULL means that if the primary key of the parent table is changed (deleted), in all referencing rows of the child table, the foreign key values ​​will be automatically assigned NULL values;

SET DEFAULT means that if the primary key of the parent table is changed (deleted), in all referencing rows of the child table, the foreign key values ​​will be automatically assigned default values.

Let us supplement the example of the educational database “University”, the design of which was discussed in Chapter. 4.3 tables DISCIPLINE and GENERAL REPORT. Tables 6 and 7 describe the logical structure of the tables.

Table 6

Logical structure of the DISCIPLINE information object

Table 7

Logical structure of the information object GENERAL STATEMENT

Key sign

Field Format

Name

Accuracy

Record book number

Registered student record book number

text

Discipline code

Discipline code

Numerical

Long integer

numerical

Let us present requests for creating tables in accordance with the one shown in Fig. 35 infological database model.

Rice. 35. Database scheme “University”

As can be seen from the database schema, the FACULTY table is an independent table, so it is created first. Request to create a table taking into account the description of the logical structure in the table. 4 (p.61) will look like:

CREATE TABLE faculty

([department number] tinyint PRIMARY KEY , [department name] char(50))

The SPECIALTY table is also independent; we create it second. When creating a query, it uses the description of the logical structure in the table. 5 (p.62).

CREATE TABLE [specialty] (

[specialty number] int PRIMARY KEY,

[name of specialty] char (60),

[cost of education] )

The GROUP table is a table dependent on FACULTY and SPECIALTY. We use table 3 (p. 61) when creating a query and take into account that the columns faculty number And specialty number are foreign keys:

CREATE TABLE [group] (

[group number] smallint PRIMARY KEY,

[specialty number] int FOREIGN KEY REFERENCES specialty( number special- ness)ON DELETE CASCADE ON UPDADE CASCADE,

[faculty number] tinyint FOREIGN KEY REFERENCES faculty( number faculty) ON DELETE CASCADE ON UPDADE CASCADE, [course number] tinyint)

The STUDENT table is a GROUP dependent table. Based on the data in Table 2 (p. 60), we will create a query. We also take into account that the column group number are foreign keys:

CREATE TABLE [student] (

[group number] smallint NOT NULL FOREIGN KEY REFERENCES group( number groups) ,

[last name] char(15) NOT NULL ,

[date of birth] datetime NOT NULL ,

[commercial] bit NOT NULL ,

[registration name] char(9))

The data in the GENERAL REPORT table depends on the STUDENT and DISCIPLINE tables. In this table, the primary key is composite and each of the primary key columns is a foreign key (see Table 7 and Figure 35).

Let's use the description of the logical structure of the discipline table given in Table 6 and create a query:

CREATE TABLE [discipline] (

[discipline code] int PRIMARY KEY,

[discipline name] char(50))

Now you can create a query to create the general statement table. Since the primary key of a table is composite, the PRIMARY KEY constraint must be specified at the table level. For example, let's set FOREIGN KEY restrictions also at the table level. The request will look like:

CREATE TABLE [general statement] (

[discipline code] int,

[grade book number] char(8),

[grade] NOT NULL , PRIMARY KEY ([discipline code],[grade book number]), FOREIGN KEY ([discipline code]) REFERENCES [discipline] ([discipline code]), FOREIGN KEY ([grade book number]) REFERENCES [student] ([grade book number]))

Changing the table structure

Changing the table structure is performed with the ALTER TABLE command. Using the command, you can change the properties of existing columns, delete them or add new columns to the table, and manage integrity constraints both at the column level and at the table level. The meaning of many of the parameters and keywords is the same as the corresponding parameters and keywords of the CREATE TABLE command.

Delete a table

Dropping a table is done using the DROP TABLE command. Command syntax:

DROP TABLE table

For example, a request to delete the STUDENT table looks like this:

DROP TABLE Student

When deleting a table, you SHOULD take into account the relationships established in the database between the tables. If the table being deleted is referenced by another table using the FOREIGN KEY integrity constraint, the DBMS will not allow its deletion.

Creating an index

Indexes are used to speed up access to specific data in a database table. An index is a structure that organizes the values ​​in one or more columns of a database table, such as the Last Names column of the STUDENT table. If you are searching for a specific student by last name, the index helps you get the information you need faster than searching through all rows of the table.

An index provides pointers to data values ​​stored in specific columns of a table and arranges those pointers according to a specified sort order. Searching for data in a table using an index is similar to searching an index in a book. First a search is carried out specific meaning in the index, and then follows the corresponding pointer to the line containing that value.

The index is created using the CREATE INDEX command:

CREATE INDEX

Name_ index ON name _tables(column [,...])

where UNIQUE specifies that the index should store only unique values.

An index can be created on one or more columns (composite index). Composite indexes allow you to differentiate between records that have the same values ​​in the same column.

Example: Create a composite index on the STUDENT table for the Last Name and Date of Birth fields

CREATE INDEX Ind_Fam ON

Student(Last name, [Date of birth] DESC)

You should only create an index on a table if you expect to frequently query the data in the indexed columns. Indexes take up disk space and slow down row addition, deletion, and update operations.

Removing a table index

The DROP command removes an index from a table. The syntax of the DROP command to remove an index is:

DROP INDEX index ON table

Before you can remove an index from a table or the table itself, you must close the table.

Example: Remove index Ind_Fam from table STUDENT

DROP INDEX Ind_Fam ON Student

The SQL language standard was adopted in 1992 and is still in use today. It was this that became the standard for many. Of course, some manufacturers use their own interpretations of the standard. But any system still has the main components - SQL statements.

Introduction

Using SQL statements, values ​​and tables are managed and obtained for further analysis and display. They are a set of keywords by which the system understands what to do with the data.

Several categories of SQL statements are defined:

  • defining database objects;
  • manipulation of values;
  • protection and control;
  • session parameters;
  • information about the database;
  • static SQL;
  • dynamic SQL.

SQL statements for data manipulation

INSERT. Inserts rows into an existing table. It can be used for one value or several, defined by a certain condition. For example:

table name (column name 1, column name 2)

VALUES(value 1, value 2).

To use the INSERT statement on multiple values, use the following syntax:

table name 1 (column name 1, column name 2)

SELECT column name 1, column name 2

FROM table name 2

WHERE table name 2.column name 1>2

This query will select all data from table 2 that is greater than 2 in column 1 and insert it into the first one.

UPDATE. As the name suggests, this SQL query statement updates data in an existing table based on a specific feature.

UPDATE table name 1

SET column name 2 = "Vasily"

WHERE table name 1.column name 1 = 1

This construction will fill with the value Vasily all lines in which it encounters the number 1 in the first column.

Data from the table. You can specify a condition or remove all lines.

DELETE FROM table name

WHERE table name.column name 1 = 1

The above query will remove from the database all data with the value one in the first column. Here's how you can clear the entire table:

SELECT statement

The main purpose of SELECT is to select data according to certain conditions. The result of his work is always a new table with selected data. The MS operator can be used in a variety of different queries. Therefore, along with it, you can consider other related keywords.

To select all data from a specific table, use the “*” sign.

FROM table name 1

The result of the work of this request will be an exact copy of table 1.

And here a selection is made using the WHERE condition, which retrieves from table 1 all values ​​greater than 2 in column 1.

FROM table name 1

WHERE table name 1.column name 1 > 2

You can also specify in the selection that only certain columns are needed.

SELECT table name 1.column name 1

FROM table name 1

The result of this query will be all rows with values ​​from column 1. Using MS SQL statements, you can create your own table, replacing, calculating and substituting certain values ​​on the fly.

table name 1.column name 1

table name 1.column name 2

table name 1.column name 3

table name 1.column name 2 * table name 1.column name 3 AS SUMMA

FROM table name 1

This seemingly complex query retrieves all values ​​from Table 1, then creates new columns EQ and SUMMA. The first is filled with the “+” sign, and the second is the product of the data from columns 2 and 3. The result can be presented in the form of a table to understand how it works:

When using the SELECT statement, you can immediately sort the data according to any criterion. The word ORDER BY is used for this.

table name 1.column name 1

table name 1.column name 2

table name 1.column name 3

FROM table name 1

ORDER BY column name 2

The resulting table will look like this:

That is, all rows were set in such an order that in column 2 the values ​​were in ascending order.

Data can also be obtained from several tables. For clarity, you first need to imagine that there are two of them in the database, something like this:

Table "Employees"

Table "Salary"

Now we need to somehow connect these two tables to obtain common values. Using basic SQL statements, you can do this like this:

Employees.Number

Employees.Name

Salary.Rate

Salary. Accrued

FROM Employees, Salary

WHERE Employees.Number = Salary.Number

Here we select from two different tables of values, combined by number. The result will be the following data set:

A little more about SELECT. Using Aggregate Functions

One of the main operators can perform some calculations when fetching. To do this, he uses certain functions and formulas.

For example, to get the number of records from the Employees table, you need to use the query:

SELECT COUNT (*) AS N

FROM Employees

The result is a table with one value and a column.

You can run a query like this and see what happens:

SUM(Salary. Accrued) AS SUMMA

MAX(Salary. Accrued) AS MAX

MIN(Salary. Accrued) AS MIN

AVG(Salary. Accrued) AS SRED

FROM Salary

The final table will be like this:

In this way, you can select the desired values ​​from the database, calculating various functions on the fly.

Union, intersection and differences

Combine multiple queries in SQL

SELECT Employees.Name

FROM Employees

WHERE Employees.Number = 1

SELECT Employees.Name

FROM Employees, Salary

WHERE Salary.Number = 1

It should be borne in mind that with such a union, the tables must be compatible. That is, have the same number of columns.

SELECT statement syntax and processing order

The first thing SELECT does is determine the area from which it will take data. For this purpose it is used keyword FROM. If it is not indicated what exactly to choose.

Then the SQL WHERE clause may be present. With its help, SELECT runs through all the rows of the table and checks the data for compliance with the condition.

If the query contains GROUP BY, then the values ​​are grouped according to the specified parameters.

Operators for comparing data

There are several types. IN SQL statements comparisons can check Various types values.

    "=". Denotes, as you might guess, the equality of two expressions. For example, it has already been used in the examples above - WHERE Salary.Number = 1.

    ">". More sign. If the value of the left side of the expression is greater, then the logical TRUE is returned and the condition is considered satisfied.

    «<». Знак меньше. Обратный предыдущему оператор.

    Signs "<=» и «>=". It differs from simple more and less operators in that if the operands are equal, the condition will also be true.

LIKE

This keyword can be translated as “similar”. The LIKE operator in SQL is used in approximately the same way - it executes a query based on a template. That is, it allows you to expand the selection of data from the database using regular expressions.

For example, the following task was set: from the already known “Employees” database, get all the people whose name ends with “I”. Then the query can be written like this:

FROM Employees

WHERE Name LIKE `%i`

The percent sign in this case means a mask, that is, any character and their number. And by the letter “I”, SQL will determine that the last character should be exactly like this.

CASE

This SQL Server statement is an implementation of multiple selection. It is reminiscent of the switch construct in many programming languages. The CASE statement in SQL performs an action based on several conditions.

For example, you need to select the maximum and minimum values ​​from the “Salary” table.

Then the query can be written like this:

FROM Salary

WHERE CASE WHEN SELECT MAX(Accrued) THEN Maximum

WHEN SELECT MIN(Accrued) THEN Minimum

In this context, the system looks for the maximum and minimum value in the Accrued column. Then, using END, a “total” field is created, in which “Maximum” or “Minimum” will be entered, depending on the result of the condition.

By the way, SQL also has a more compact form of CASE - COALESCE.

Data Definition Operators

This view allows you to carry out various modifications to tables - creating, deleting, modifying and working with indexes.

The first one worth considering is CREATE TABLE. It does nothing more than create a table. If you simply type the CREATE TABLE query, nothing will happen, since you still need to specify several parameters.

For example, to create the already familiar “Employees” table, you need to use the commands:

CREATE TABLE Employees

(Number(10) NOT NULL

Name varchar(50) NOT NULL

Last name varchar(50) NOT NULL)

In this query, the names of the fields and their types are immediately determined in parentheses, as well as whether it can be equal to NULL.

DROP TABLE

Performs one simple task - dropping the specified table. It has additional parameter IF EXISTS. It absorbs a drop error if the table you are looking for does not exist. Usage example:

DROP TABLE Employees IF EXISTS.

CREATE INDEX

SQL has an index system that allows you to speed up data access. In general, it is a link that points to a specific column. You can create an index with a simple query:

CREATE INDEX index_name

ON table_name(column_name)

This operator is used in T-SQL, Oracle, PL SQL and many other interpretation technologies.

ALTER TABLE

A very functional operator with numerous options. In general, it changes the structure, definition and placement of tables. The operator is used in Oracle SQL, Postgres and many others.

    ADD. Adds a column to the table. Its syntax is as follows: ALTER TABLE table_name ADD column_name stored_data_type. May have an IF NOT EXISTS option to suppress the error if the column being created already exists;

    DROP. Removes a column. It also has an IF EXISTS key, without which an error will be generated indicating that the required column is missing;

    CHANGE. Serves to rename the field name to the specified one. Usage example: ALTER TABLE table_name CHANGE old_name new_name;

    MODIFY. This command will help you change the type and additional attributes of a certain column. And it is used like this: ALTER TABLE table_name MODIFY column_name data_type attributes;

CREATE VIEW

In SQL there is such a thing as a view. In short, this is a kind of virtual table with data. It is formed as a result of selection using the SQL SELECT statement. Views can restrict access to the database, hide them, and replace real column names.

The creation process occurs using a simple request:

CREATE VIEW view name AS SELECT FROM * table name

Sampling can occur either from the entire database or based on some condition.

A little about the functions

SQL queries very often use various built-in functions that allow you to interact with data and transform it on the fly. It's worth considering them because they form an integral part of a structured language.

    COUNT. Counts records or rows in a specific table. You can specify the column name as a parameter, then the data will be taken from it. SELECT COUNT * FROM Employees;

    AVG. Applies only to columns with numeric data. Its result is the determination of the arithmetic mean of all values;

    MIN and MAX. These functions have already been used in this article. They determine the maximum and minimum values ​​from a specified column;

    SUM. It's simple - the function calculates the sum of the column values. Applies exclusively to numeric data. By adding the DISTINCT parameter to the query, only unique values ​​will be summed;

    ROUND. Function for rounding decimal fractions. The syntax uses the column name and the number of decimal places;

    LEN. A simple function that calculates the length of a column's values. The result will be a new table indicating the number of characters;

    NOW. This keyword is used to calculate the current date and time.

Additional Operators

Many SQL statement examples have keywords that perform small tasks but still greatly simplify retrieval or database manipulation.

    AS. It is used when you need to visually format the result by assigning the specified name to the resulting table.

    BETWEEN. A very convenient sampling tool. It specifies the range of values ​​among which data is to be retrieved. Takes as input a parameter from and to what number the range is used;.

    NOT. The operator gives the opposite of the expression.

    TRUNCATE. Deletes data from the specified section of the database. It differs from similar operators in that it is impossible to restore data after using it. It is worth considering that the implementation of this keyword in different SQL interpretations may differ. Therefore, before trying to use TRUNCATE, it is better to read the help information.

    LIMIT. Sets the number of lines to output. The peculiarity of the operator is that it is always located at the end. Accepts one required parameter and one optional one. The first specifies how many rows of selected data should be shown. And if the second one is used, then the operator works as for a range of values.

    UNION. A very convenient operator for combining multiple queries. It has already been found among examples of this in this article. You can display the desired rows from several tables by combining them with UNION for more convenient use. Its syntax is as follows: SELECT column_name FROM table_name UNION SELECT other_column_name FROM other_table_name. The result is a pivot table with the combined queries.

    PRIMARY KEY. Translated as “primary key”. In fact, this is exactly the terminology used in reference materials. It means a unique row identifier. It is used, as a rule, when creating a table to indicate the field that will contain it.

    DEFAULT. Just like the previous operator, it is used during the execution of the creating request. It defines the default value with which the field will be populated when it is created.

    NULL. Beginners and not only programmers, when writing queries, very often forget about the possibility of obtaining the NULL value. As a result, an error creeps into the code, which is difficult to track down during debugging. Therefore, when creating tables, selecting or recalculating values, you need to stop and think about whether the occurrence of NULL in this part of the query is taken into account.

    Memory. This article showed several functions that can perform some tasks. When developing a shell for working with a database, you can outsource the calculation of simple expressions to the database management system. In some cases, this gives a significant increase in performance.

    Restrictions. If you need to get only two rows from a database with thousands of rows, then you should use operators like LIMIT or TOP. There is no need to extract data using a shell development language.

    Compound. After receiving data from several tables, many programmers begin to bring them together using shell memory. But why? After all, you can create one request in which all this will be present. There is no need to write extra code and reserve additional memory in the system.

    Sorting. If it is possible to apply ordering in a query, that is, using the DBMS, then you need to use it. This will allow you to significantly save on resources when running a program or service.

    Lots of requests. If you have to insert many records sequentially, then for optimization you should think about batch inserting data with one request. This will also increase the performance of the entire system as a whole.

    Thoughtful placement of data. Before compiling the database structure, you need to think about whether so many tables and fields are necessary. Maybe there is a way to combine them or discard some. Very often programmers use an excessive amount of data that will never be used anywhere.

    Types. To save space and resources, you need to be sensitive to the types of data you use. If it is possible to use a type that is less “heavy” for memory, then you should use it. For example, if you know that the numeric value in a given field will not exceed 255, then why use a 4-byte INT if there is a 1-byte TINYINT.

Conclusion

In conclusion, it should be noted that the structured query language SQL is now used almost everywhere - websites, web services, PC programs, applications for mobile devices. Therefore, knowledge of SQL will help all branches of development.

However, modifications of the original language standard sometimes differ from each other. For example, PL SQL statements may have a different syntax than in SQL Server. Therefore, before you start developing with this technology, it is worth reading the tutorials on it.

In the future, analogues that could surpass SQL in functionality and performance are unlikely to appear, so this area is a fairly promising niche for any programmer.

Basic SQL Commands Every Programmer Should Know

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 various ways joins 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 virtual SQL table, created as a result of executing the 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);

Like most programming languages, SQL has functions for data manipulation. It is worth noting that, unlike SQL statements, functions are not standardized for all types of DBMS, that is, to perform the same operations on data, different DBMSs have their own function names. This means that the query code written in one DBMS may not work in another, and this must be taken into account in the future. Most of all this concerns functions for processing text values, data type conversions and date manipulation.

Typically, a DBMS supports a standard set of function types, namely:

  • Text functions that are used for text processing (selecting part of the characters in the text, determining the length of the text, converting characters to upper or lower case...)
  • Numerical functions. Used to perform mathematical operations on numeric values
  • Date and time functions (manipulate date and time, calculate the period between dates, check dates for correctness, etc.)
  • Statistical functions (for calculating maximum/minimum values, average values, counting quantities and sums...)
  • System functions (provide various kinds of service information about the DBMS, the user, etc.).

1. SQL Functions for Text Processing

The SQL implementation in the Access DBMS has the following functions for text processing:

Let's convert product names to upper case using the function UCase():

SELECT Product, UCase(Product) AS Product_UCase FROM Sumproduct

Let's select the first three characters in the text using the function LEFT():

SELECT Product, LEFT(Product, 3) AS Product_LEFT FROM Sumproduct

2. SQL Functions for Number Processing

Number processing functions are designed to perform mathematical operations on numeric data. These functions are intended for algebraic and geometric calculations, so they are used much less often than date and time functions. However, numeric functions are the most standardized across all versions of SQL. Let's take a look at the list of numeric functions:

We have listed only a few basic functions, but you can always refer to the documentation of your DBMS to see a complete list of functions that are supported with their detailed descriptions.

For example, let's write a query to get the square root of the numbers in a column Amount using the function SQR():

SELECT Amount, SQR(Amount) AS Amount_SQR FROM Sumproduct

3. SQL Functions for Date and Time Processing

Date and time manipulation functions are one of the most important and frequently used functions of SQL. Databases store date and time values ​​in a special format, so they cannot be used directly without additional processing. Each DBMS has its own set of functions for processing dates, which, unfortunately, does not allow them to be transferred to other platforms and SQL implementations.

List of some functions for processing date and time in Access DBMS:

Let's look at an example of how the function works DatePart():

SELECT Date1, DatePart("m", Date1) AS Month1 FROM Sumproduct

Function DatePart() has an additional parameter that allows us to display the required part of the date. In the example we used the parameter "m", which displays the month number (in the same way we can reflect the year - "yyyy", quarter - "q", day - "d", week - "w", hour - "h", minutes - "n", seconds - "s" etc.).

4. SQL statistical functions

Statistical functions help us get ready data without sampling it. SQL queries with these functions are often used to analyze and generate various reports. An example of such selections could be: determining the number of rows in a table, obtaining the sum of values ​​for a specific field, searching for the largest/smallest or average value in a specified table column. Also note that statistical functions are supported by all DBMSs without any special changes in writing.

List of statistical functions in Access DBMS:

COUNT():

SELECT COUNT(*) AS Count1 FROM Sumproduct- returns the count of all rows in the table

SELECT COUNT(Product) AS Count2 FROM Sumproduct- returns the number of all non-blank lines in the field Product

We intentionally removed one value in the column Product to show the difference in how the two queries work.

Examples of using the function SUM():

SELECT SUM(Quantity) AS Sum1 FROM Sumproduct WHERE Month = "April"

With this request we reflected the total quantity of goods sold in April.

SELECT SUM(Quantity*Amount) AS Sum2 FROM Sumproduct

As you can see, in statistical functions we can perform calculations over multiple columns using standard mathematical operators.

Example of using the function MIN():

SELECT MIN(Amount) AS Min1 FROM Sumproduct

Example of using the function MAX():

SELECT MAX(Amount) AS Max1 FROM Sumproduct

Example of using the function AVG():

SELECT AVG(Amount) AS Avg1 FROM Sumproduct

Transact-SQL language functions can be aggregate or scalar. These types of functions are discussed in this article.

Aggregate functions

Aggregate functions perform calculations on a group of column values ​​and always return a single value as the result of those calculations. Transact-SQL supports several common aggregate functions:

AVG

Calculates the arithmetic average of the data contained in a column. The values ​​on which the calculation is performed must be numeric.

MIN and MAX

Determines the maximum and minimum values ​​of all data values ​​contained in a column. Values ​​can be numeric, string, or temporal (date/time).

SUM

Calculates the total sum of the values ​​in a column. The values ​​on which the calculation is performed must be numeric.

COUNT

Counts the number of non-null values ​​in a column. The count(*) function is the only aggregate function that does not perform calculations on columns. This function returns the number of rows (regardless of whether individual columns contain null values).

COUNT_BIG

Similar to the count function, with the difference that it returns a BIGINT data value.

The use of regular aggregate functions in a SELECT statement will be discussed in a future article.

Scalar functions

Transact-SQL scalar functions are used in creating scalar expressions. (A scalar function performs calculations on a single value or a list of values, while an aggregate function performs calculations on a group of values ​​over multiple rows.) Scalar functions can be broken down into the following categories:

    numeric functions;

    date functions;

    string functions;

    system functions;

    metadata functions.

These types of functions are discussed in subsequent sections.

Numeric functions

Transact-SQL numeric functions are mathematical functions for modifying numeric values. A list of numerical functions and their brief descriptions are given in the table below:

Transact-SQL Numeric Functions
Function Syntax Description Usage example
ABS ABS(n)

Returns the absolute value (that is, negative values ​​are returned as positive) of a numeric expression n.

SELECT ABS(-5.320) -- Returns 5.320 SELECT ABS(8.90) -- Returns 8.90

ACOS, ASIN, ATAN, ATN2 ACOS(n), ASIN(n), ATAN(n), ATN2(n, m)

Inverse trigonometric functions that calculate the arccosine, arcsine, arctangent of the value n (for ATN2 the arctangent n/m is calculated). The input values ​​n, m and the result are of the FLOAT data type.

COS, SIN, TAN, COT COS(n), SIN(n), TAN(n), COT(n)

Trigonometric functions that calculate cosine, sine, tangent, cotangent of the value n. The result has data type FLOAT.

DEGREES, RADIANS DEGREES(n), RADIANS(n)

The DEGREES function converts radians to degrees, RADIANS, respectively, vice versa.

SELECT DEGREES(PI() / 4) -- Returns 45 SELECT COS(RADIANS(60.0)) -- Returns 0.5

CEILING CEILING(n)

Rounds a number to a higher integer value.

SELECT CEILING(-5.320) -- Returns -5 SELECT CEILING(8.90) -- Returns 9

ROUND ROUND(n, p, [t])

Rounds the value of n to the nearest p. When p is a positive number, the fractional part of n is rounded, and when it is negative, the integer part is rounded. When using the optional argument t, the number n is not rounded but rather truncated (that is, rounded down).

SELECT ROUND(5.3208, 3) -- Returns 5.3210 SELECT ROUND(125.384, -1) -- Returns 130.000 SELECT ROUND(125.384, -1, 1) -- Returns 120.000

FLOOR FLOOR(n)

Rounds down to the lowest integer value.

SELECT FLOOR(5.88) -- Returns 5

EXP EXP(n)

Calculates the value of e n .

LOG, LOG10 LOG(n), LOG10(n)

LOG(n) - calculates the natural logarithm (i.e., base e) of the number n, LOG10(n) - calculates the decimal (base 10) logarithm of the number n.

P.I. PI()

Returns the value of π (3.1415).

POWER POWER(x, y)

Calculates the value of x y .

RAND RAND()

Returns an arbitrary number of type FLOAT in the range of values ​​between 0 and 1.

ROWCOUNT_BIG ROWCOUNT_BIG()

Returns the number of table rows that were processed by the last Transact-SQL statement executed by the system. The return value is of type BIGINT.

SIGN SIGN(n)

Returns the sign of n as a number: +1 if positive, -1 if negative.

SQRT, SQUARE SQRT(n), SQUARE(n)

SQRT(n) - calculates the square root of the number n, SQUARE(n) - returns the square of the argument n.

Date functions

Date functions evaluate the corresponding date or time parts of an expression or return a time interval value. The date functions supported in Transact-SQL and their brief descriptions are given in the table below:

Transact-SQL Date Functions
Function Syntax Description Usage example
GETDATE GETDATE()

Returns the current system date and time.

SELECT GETDATE()

DATEPART DATEPART (item, date)

Returns the date part specified in the item parameter as an integer.

Returns 1 (January) SELECT DATEPART(month, "01/01/2012") -- Returns 4 (Wednesday) SELECT DATEPART(weekday, "01/02/2012")

DATENAME DATENAME (item, date)

Returns the date part specified in the item parameter as a character string.

Returns January SELECT DATENAME(month, "01/01/2012") -- Returns Wednesday SELECT DATENAME(weekday, "01/02/2012")

DATEDIFF DATEDIFF (item, dat1, dat2)

Calculates the difference between two date parts dat1 and dat2 and returns an integer result in the units specified in the item argument.

Returns 19 (19 year interval between dates) SELECT DATEDIFF(year, "01/01/1990", "01/01/2010") -- Returns 7305 (7305 day interval between dates) SELECT DATEDIFF(day, "01/01/1990", "01/01" .2010")

DATEADD DATEADD (item, n, date)

Adds nth quantity units specified in the item argument for the specified date date. (n can also be negative.)

Will add 3 days to the current date SELECT DATEADD(day, 3, GETDATE())

String functions

String functions manipulate column values, which are typically character data types. The supported string functions in Transact-SQL and their brief descriptions are given in the table below:

Transact-SQL String Functions
Function Syntax Description Usage example
ASCII, UNICODE ASCII(char), UNICODE(char)

Converts the specified character to the corresponding ASCII code integer.

SELECT ASCII("W") -- 87 SELECT UNICODE("u") -- 1102

CHAR, NCHAR CHAR(int), NCHAR(int)

Converts an ASCII code (or Unicode if NCHAR) to the appropriate character.

SELECT CHAR(87) -- "W" SELECT NCHAR(1102) -- "yu"

CHARINDEX CHARINDEX (str1, str2)

Returns the starting position of the occurrence of the substring str1 in the string str2. If the string str2 does not contain the substring str1, the value 0 is returned

Returns 5 SELECT CHARINDEX ("morph", "polymorphism")

DIFFERENCE DIFFERENCE (str1, str2)

Returns an integer between 0 and 4 that is the difference between the SOUNDEX values ​​of the two strings str1 and str2. The SOUNDEX method returns a number that characterizes the sound of the string. Using this method, you can identify similar sounding strings. Only works for ASCII characters.

Returns 2 SELECT DIFFERENCE ("spelling", "telling")

LEFT, RIGHT LEFT (str, length), RIGHT (str, length)

Returns the number of first characters of the string str specified by the length parameter for LEFT and the last length characters of the string str for the RIGHT function.

DECLARE @str nvarchar(30) = "Synchronization"; -- Returns "Sync" SELECT LEFT(@str, 4) -- Returns "Zation" SELECT RIGHT(@str, 5)

LEN LEN(str)

Returns the number of characters (not the number of bytes) of the string str specified in the argument, including trailing spaces.

LOWER, UPPER LOWER(str), UPPER(str)

The LOWER function converts all uppercase letters in str1 to lowercase. Lowercase letters and other characters included in the string are not affected. The UPPER function converts all lowercase letters in the string str to uppercase.

DECLARE @str nvarchar(30) = "Synchronization"; -- Returns "SYNCHRONIZATION" SELECT UPPER(@str) -- Returns "synch" SELECT LOWER(@str)

LTRIM, RTRIM LTRIM(str), RTRIM(str)

The LTRIM function removes leading spaces in the string str, RTRIM respectively removes spaces at the end of the string.

QUOTENAME QUOTENAME(char_string)

Returns a Unicode-encoded string with delimiters added to convert the input string to a valid delimited identifier.

DECLARE @str nvarchar(30) = "Synchronization"; -- Return "[Sync]" SELECT QUOTENAME(@str)

PATINDEX PATINDEX (%p%, expr)

Returns the starting position of the first occurrence of the pattern p in the given expr, or zero if the pattern is not found.

Returns 4 SELECT PATINDEX("%chro%", "Synchronization")

REPLACE REPLACE (str1, str2, str3)

Replaces all occurrences of the substring str2 in the string str1 with the substring str3.

Returns "Desynchronization" SELECT REPLACE("Synchronization", "Synchronization", "Desynchronization")

REPLICATE REPLICATE (str, i)

Repeats the string str i times.

Returns "aBaBaBaBaB" SELECT REPLICATE("aB", 5)

REVERSE REVERSE (str)

Prints the string str in reverse order.

Returns "yaitsazinorkhniS" SELECT REVERSE("Synchronization")

SOUNDEX SOUNDEX (str)

Returns a four-character soundex code used to determine whether two strings are similar. Only works for ASCII characters.

SPACE SPACE (length)

Returns a string of spaces with the length specified in the length parameter. Similar to REPLICATE(" ", length).

STR STR (f[, len[, d]])

Converts the specified floating-point expression f to a string, where len is the length of the string, including decimal point, sign, digits, and spaces (defaults to 10), and d is the number of decimal places to return.

Returns "3.14" SELECT STR (3.1415, 4, 2)

STUFF STUFF (str1, a, length, str2)

Removes length characters from string str1, starting at position a, and inserts string str2 in their place.

Note in a book SELECT STUFF("Notebook", 5, 0," in a ") -- Handbook SELECT STUFF("Notebook", 1, 4, "Hand")

SUBSTRING SUBSTRING (str1, a, length)

Extracts from the string str, starting at position a, a substring of length length.

System functions

Transact-SQL system functions provide extensive information about database objects. Most system functions use an internal numeric identifier (ID) that is assigned to each database object when it is created. Using this identifier, the system can uniquely identify each database object.

The following table lists some of the most important system functions along with their brief description:

Transact-SQL System Functions
Function Syntax Description Usage example
CAST CAST (w AS type [(length)]

Converts expression w to specified type data type (if possible). The argument w can be any valid expression.

Returns 3 SELECT CAST (3.1258 AS INT)

COALESCE COALESCE (a1, a2)

Returns the first expression value from the list of expressions a1, a2, ... that is not null.

COL_LENGTH COL_LENGTH (obj, col)

Returns the length of the col column of the database object (table or view) obj.

Returns 4 SELECT COL_LENGTH("Employee", "Id")

CONVERT CONVERT (type[(length)], w)

Equivalent to the CAST function, but the arguments are specified differently. Can be used with any data type.

CURRENT_TIMESTAMP CURRENT_TIMESTAMP

Returns current date and time.

CURRENT_USER CURRENT_USER

Returns the name of the current user.

DATALENGTH DATALENGTH(z)

Returns the number of bytes occupied by the expression z.

This query returns the length of each field SELECT DATALENGTH(FirstName) FROM Employee

GETANSINULL GETANSINULL("dbname")

Returns 1 if the use of null values ​​in database dbname complies with the ANSI SQL standard.

ISNULL ISNULL (expr, value)

Returns the value of expr if it is not NULL; otherwise, value is returned.

ISNUMERIC ISNUMERIC (expr)

Determines whether the expression expr is a valid numeric type.

NEWID NEWID()

Creates a unique identification number ID consisting of a 16-byte binary string designed to store values ​​of the UNIQUEIDENTIFIER data type.

NEWSEQUENTIALID NEWSEQUENTIALID()

Creates a GUID that is larger than any other GUID previously created by this function on the specified computer. (This function can only be used as a default value for a column.)

NULLIF NULLIF (expr1, expr2)

Returns null if the expressions expr1 and expr2 have the same values.

The query returns NULL for a project -- whose Number = "p1" SELECT NULLIF(Number, "p1") FROM Project

SERVERPROPERTY SERVERPROPERTY (propertyname)

Returns information about database server properties.

SYSTEM_USER SYSTEM_USER

Returns the ID of the current user.

USER_ID USER_ID()

Returns the user ID username. If no user is specified, the current user ID is returned.

USER_NAME USER_NAME()

Returns the username with the specified id. If an identifier is not specified, the current user's name is returned.

Metadata functions

Basically, metadata functions return information about a specified database and database objects. The table below summarizes some of the most important metadata functions along with their brief descriptions:

Transact-SQL Metadata Functions
Function Syntax Description Usage example
COL_NAME COL_NAME (tab_id, col_id)

Returns the name of the column with the specified identifier col_id of the table with identifier tab_id.

Returns the name of the column "LastName" SELECT COL_NAME (OBJECT_ID("Employee"), 3)

COLUMNPROPERTY COLUMNPROPERTY (id, col, property)

Returns information about the specified column.

Returns the value of the PRECISION property -- for the Id column of the Employee table SELECT COLUMNPROPERTY (OBJECT_ID("Employee"), "Id", "precision")

DATABASEPROPERTY DATABASEPROPERTY (database, property)

Returns the value of the database property property.

Returns the value of the IsNullConcat property -- for the SampleDb database SELECT DATABASEPROPERTY ("SampleDb", "IsNullConcat")

DB_ID DB_ID()

Returns the database ID db_name. If a database name is not specified, the ID of the current database is returned.

DB_NAME DB_NAME()

Returns the name of the database that has db_id. If an identifier is not specified, the name of the current database is returned.

INDEX_COL INDEX_COL (table, i, no)

Returns the name of the indexed column of table table. A column is indicated by index identifier i and column position no in that index.

INDEXPROPERTY INDEXPROPERTY (obj_id, index_name, property)

Returns the properties of a named index or statistic for the specified table ID number, the name of the index or statistic, and the name of the property.

OBJECT_NAME OBJECT_NAME (obj_id)

Returns the name of the database object that has the identifier obj_id.

SELECT OBJECT_NAME(245575913);

OBJECT_ID OBJECT_ID (obj_name)

Returns the object identifier obj_name of the database.

Returns 245575913 - Employee table ID SELECT OBJECT_ID("Employee")

OBJECTPROPERTY OBJECTPROPERTY (obj_id, property)

Returns information about objects from the current database.