Contacts

Examples of SQL queries to the MySQL database. SQL query language Ready-made sql queries

Welcome to my blog site. Today we will talk about sql queries for beginners. Some webmasters may have a question. Why learn sql? Can't get by?

It turns out that this will not be enough to create a professional Internet project. Sql is used to work with the database and create applications for WordPress. Let's take a look at how to use queries in more detail.

What it is

Sql is a structured query language. Created to determine the type of data, provide access to them and process information in short periods of time. It describes the components or some results that you want to see on the Internet project.

In simple terms, this programming language allows you to add, modify, search and display information in the database. The popularity of mysql is due to the fact that it is used to create dynamic Internet projects, which are based on a database. Therefore, to develop a functional blog, you need to learn this language.

What can do

The sql language allows:

  • create tables;
  • change receive and store different data;
  • combine information into blocks;
  • protect data;
  • create requests in access.

Important! Having dealt with sql, you can write applications for WordPress of any complexity.

What structure

The database consists of tables that can be represented as an Excel file.

She has a name, columns and a row with some information. You can create such tables using sql queries.

What you need to know


Key Points When Learning Sql

As noted above, queries are used to process and enter new information into a database consisting of tables. Each line is a separate entry. So let's create a database. To do this, write the command:

Create database 'bazaname'

In quotation marks we write the name of the database in Latin. Try to think of a meaningful name for her. Don't create a database like "111", "www" and the like.

After creating the database, install:

SET NAMES ‘utf-8’

This is necessary so that the content on the site is displayed correctly.

Now we create a table:

CREATE TABLE 'bazaname' . 'table' (

id INT(8) NOT NULL AUTO_INCREMENT PRIMARY KEY,

log VARCHAR(10),

pass VARCHAR(10),

date DATE

In the second line, we have written three attributes. Let's see what they mean:

  • The attribute NOT NULL means that the cell will not be empty (the field is required);
  • The value of AUTO_INCREMENT is autocomplete;
  • PRIMARY KEY is the primary key.

How to add information

To fill the fields of the created table with values, the INSERT statement is used. We write the following lines of code:

INSERT INTO 'table'

(login , pass , date) VALUES

('Vasa', '87654321', '2017-06-21 18:38:44');

In brackets we indicate the name of the columns, and in the next - the values.

Important! Follow the sequence of column names and values.

How to update information

For this, the UPDATE command is used. Let's see how to change the password for a specific user. We write the following lines of code:

UPDATE 'table' SET pass = '12345678' WHERE id = '1'

Now change the password to '12345678'. Changes occur in the line with "id"=1. If you do not write the WHERE command, all lines will change, not a specific one.

I recommend that you buy the book SQL for Dummies ". With its help you will be able to professionally work with the database step by step. All information is built on the basis of the principle from simple to complex, and will be well received.

How to delete an entry

If you wrote something wrong, correct it with the DELETE command. Works the same as UPDATE. We write the following code:

DELETE FROM 'table' WHERE id = '1'

Information sampling

The SELECT command is used to retrieve values ​​from the database. We write the following code:

SELECT * FROM 'table' WHERE id = '1'

In this example, we select all available fields in the table. This happens if you write an asterisk "*" in the command. If you need to choose some sample value, write like this:

SELECT log , pass FROM table WHERE id = '1'

It should be noted that the ability to work with databases will not be enough. To create a professional Internet project, you will have to learn how to add data from the database to the pages. To do this, familiarize yourself with the php web programming language. This will help you Mikhail Rusakov's cool course .


Deleting a table

Occurs with a DROP request. To do this, write the following lines:

DROP TABLE table;

Outputting a record from a table according to a certain condition

Consider this code:

SELECT id, countri, city FROM table WHERE people>150000000

It will display the records of countries where the population is more than one hundred and fifty million.

An association

Linking multiple tables together is possible using Join. See how it works in this video:

PHP and MySQL

Once again I want to emphasize that requests when creating an Internet project are a common thing. To use them in php documents, follow the following algorithm of actions:

  • Connect to the database using the mysql_connect() command;
  • Using mysql_select_db() select the desired database;
  • Processing the query with mysql_fetch_array();
  • We close the connection with the mysql_close() command.

Important! Working with a database is not difficult. The main thing is to write the request correctly.

Novice webmasters will think. And what to read on this topic? I would like to recommend Martin Graber's book " SQL for mere mortals ". It is written in such a way that beginners will understand everything. Use it as a reference book.

But this is a theory. How does it work in practice? In fact, an Internet project must not only be created, but also brought to the TOP of Google and Yandex. The video course will help you with this " Creation and promotion of the site ».


Video instruction

Still have questions? Watch more online video.

Conclusion

So, dealing with writing sql queries is not as difficult as it seems, but any webmaster needs to do this. The video courses described above will help with this. Subscribe to my VKontakte group to be the first to know about new interesting information.

Data selection from a table in SQL is carried out using the following construction:
SELECT *|
[AS ] FROM [WHERE [AND ]]
[GROUP BY | [ HAVING ]]
[ORDER BY [COLLATE ] ]

SELECT section


Define list of output columns
The list of output columns can be specified in several ways:
. Specify the * character to indicate that all query columns are included in the query results in natural order.
. List in the desired order only those you need.
Example: SELECT * FROM Customer

Enable calculated columns
The calculated columns of a query can be:
. Results of simple arithmetic expressions (+, -, /, *_ or string concatenation (||).
. Results of aggregation functions COUNT(*)|(AVG|SUM|MAX|MIN|COUNT) ()

Note: In SQL Server, you can additionally use the % operator - modulo (integer modulo).
Enable Constants
Columns can be constants of numeric and character types.

Note: SELECT DISTINCT 'For ', SNum, Comm*100, '%', SName FROM SalesPeople

Rename output columns
Calculated columns, as well as any other columns, if desired, can be assigned a unique name using the AS keyword: AS

Note: In SQL SERVER, you can give a new name to a column using the assignment operator =

Specify the principle of processing duplicate lines
DISTINCT - prohibits the appearance of duplicate rows in the output set. It can be specified once per SELECT statement. In practice, the output set is initially formed, ordered, and then duplicate values ​​are removed from it. This usually takes a long time and should not be abused.
ALL (default) - ensures that duplicate values ​​are also included in the query results

Enable aggregate functions
Aggregation functions (functions on sets, statistical or basic) are designed to calculate some values ​​for a given set of rows. The following aggregate functions are used:
. AVG|SUM(|) - calculates the average | sum of or possibly ignoring duplicates, ignoring NULL.
. MIN|MAX() – finds the maximum | minimum value.
. COUNT(*) – counts the number of rows in the set, taking into account NULL values ​​| values ​​in the column, ignoring NULL values, possibly without duplicates.

Usage Notes:
. Aggregate functions cannot be nested.
. Due to NULL values, the expression SUM(F1)-SUN(F2)Sum(F1-F2)
. Within aggregation functions, expressions AVG(Comm*100) are allowed
. If no rows are returned from the query, or if all values ​​are NULL, then the COUNT function returns 0, and the others return NULL.
. The AVG and SUM functions can only be used for numeric data types in Interval, and the rest can be used for any data type.
. The COUNT function returns an integer (of type Integer), while others inherit the data types of the processed values, so you should pay attention to the precision of the result of the SUM function (possible overflow) and the scale of the AVG function.

Examples for aggregate functions:

SELECT COUNT(*) FROM Customer
. SELECT COUNT(DISTINCT SNum) FROM Orders
. SELECT MAX(Amt+Binc) FROM Orders //If Binc is an additional numeric field in Orders
. SELECT AVG(Comm*100) FROM SalesPeople //Expression inside the function

Features of industrial servers
In the Oracle DBMS, in the SELECT section, you can specify additional hints (hints) (27 pieces) that affect the choice of the query optimizer type and its operation.
SELECT /*+ ALL_ROWS */ FROM Orders... //best performance

In SQL Server DBMS:
] – sets the number or percentage of lines to be read. With the same last values, it is possible to read all such rows and the total number may be greater than the specified one.

DECLARE @p AS Int
SELECT @p=10
SELECT TOP(@p) WITH TIES * FROM Orders

FROM section

This section is mandatory and allows you to:
Specify source table names
The FROM clause specifies the names of the tables and/or views from which the data will be retrieved. Moreover, the same table can be included in this section several times.
Note: In Oracle, you can also select rows from Snapshots.

Specify table aliases
A table alias is an optional, usually short, identifier, separated by a space after the table/view name.
Example: Customer C

Specify an outer join option for tables
If more than one table is specified in the FROM clause, then all of them are implicitly considered outer joins. The standard provides for the following main types of table joins:

1) Cross connection
CROSS JOIN - all possible combinations of pairs of rows are defined, one for each row of each of the tables to be joined. Equivalent to the Cartesian connection. Sometimes called the Cartesian product.

2) Natural connection
JOIN - only those rows of tables A and B are determined in which the column values ​​\u200b\u200bare the same. They call it not quite a full-fledged equiconnection. This is an automatic join over multiple columns with all the same names (join over).

3) Union connection
UNION JOIN - only those rows of each of the tables for which matches have not been established are determined. Columns from another table are populated with NULL values. Note that a UNION join and a UNIUN operator are not the same thing. A join is the opposite of an INNER join.

4) Union via predicate
JOIN ON - filters rows. The predicate may contain subqueries.

5) Combining via column names
JOIN USING() - defines a join only for the specified columns, while NATURAL - automatically for all of the same name.

Connection types

is one of the arguments: INNER|{LEFT|RIGHT|FULL)
. INNER– includes rows that have columns with matching data from the tables being joined. Used by default.
. LEFT- includes all rows of table A (left table) and all matching values ​​from table B. Columns of non-matching rows are filled with NULL values.
. RIGHT- includes all rows of table B (right table) and all matching values ​​of table A. Reverse for left join.
. FULL– includes all rows of both tables. The columns of matching rows are filled with real values, and those of non-matching rows are filled with NULL values.
. OUTER (external) is a qualifying word meaning that non-matching rows from the leading table are included along with matching ones.

Outer join examples:

SELECT * FROM SalesPeople INNER JOIN Customer ON SalesPeople.City=Customer.City
. SELECT * FROM Customer LEFT OUTER JOIN SalesPeople ON SalesPeople.City=Customer.City
. SELECT * FROM Customer FULL OUTER JOIN SalesPeople ON SalesPeople.City=Customer.City

Cartesian joins and self-joins
. If, when including several tables, certain options for joining tables are not used, then such joins are called Cartesian. They are used to get rows from two different tables. Then, for example, when joining two tables, each of which contains 20 rows, the resulting table will contain 100 rows - each of the rows of one table with each of the rows of another table. SELECT * FROM Customer, Orders.
. Joins of identical tables are called self-joins.

WHERE clause

1. Create inner connections
Communication between tables is carried out using comparison operators, and the list of output columns includes qualifying names for columns of the same name from the source tables.

Main types of connections:
. Equijoins are joins of tables based on equalities. Linking between tables on key columns ensures referential integrity. If the connection uses a primary and a foreign key, then there is always a one-to-many relationship (ancestor / descendant).

. Theta compounds is a join where inequality (, >=, SQL Server Notes) is used as the comparison operator
In SQL Server, left, right, and full joins can be specified in the WHERE clause with [*]=[*]. In fact, an outer join is implemented, which in other DBMS is implemented in the FROM section.

Examples of internal connections

SELECT C.CName, S.SName, S.City FROM SalesPeople S, Customer C WHERE S.City=C.City
SELECT SName, CName FROM SalesPeople, Customer WHERE SName

2. Filtering rows of the output set
The WHERE clause also allows you to define, i.e. a boolean condition that can be either true or false. In addition, one or both of the compared values ​​in the predicate may be NULL, in which case the result of the comparison may be UNKNOWN. The SELECT statement retrieves only those rows from tables for which TRUE is true, excluding rows for which it is FALSE or UNKNOWN.

SQL - Lesson 4. Selecting data - SELECT statement

So, in our forum database there are three tables: users (users), topics (topics) and posts (messages). And we want to see what data they contain. To do this, there is an operator in SQL SELECT. The syntax for using it is as follows:

SELECT select_what FROM select_from;


Instead of "what_to_select", we must specify either the name of the column whose values ​​we want to see, or the names of several columns separated by commas, or the asterisk character (*), which means the selection of all columns of the table. Instead of "from_choose" you should specify the name of the table.

Let's first look at all the columns from the users table:

SELECT * FROM users;

That's all our data that we entered into this table. But suppose we only want to look at the id_user column (for example, in the last lesson, we needed to know what id_users are in the users table to populate the topics table). To do this, we will specify the name of this column in the query:

SELECT id_user FROM users;

Well, if we want to see, for example, the names and e-mails of our users, then we will list the columns of interest separated by commas:

SELECT name, email FROM users;

Similarly, you can see what data our other tables contain. Let's see what topics we have:

SELECT * FROM topics;

Now we have only 4 topics, and if there are 100 of them? I would like them to be displayed, for example, alphabetically. There is a keyword for this in SQL. ORDER BY followed by the name of the column by which sorting will occur. The syntax is the following:

SELECT column_name FROM table_name ORDER BY sort_column_name;



The default sorting is ascending, but this can be changed by adding the keyword DESC

Now our data is sorted in descending order.

You can sort by several columns at once. For example, the following query will sort the data by the topic_name column, and if there are several identical rows in this column, then the id_author column will be sorted in descending order:

Compare the result with the result of the previous query.

Very often we do not need all the information from the table. For example, we want to know which topics were created by the user sveta (id=4). There is a keyword for this in SQL. WHERE, the syntax for such a request is as follows:

For our example, the condition is the user ID, i.e. we only want rows that have 4 in the id_author column (user ID sveta):

Or we want to know who created the "bicycles" theme:

Of course, it would be more convenient to display the author's name instead of the author's id, but the names are stored in another table. In later lessons, we will learn how to select data from multiple tables. In the meantime, let's learn what conditions can be specified using the WHERE keyword.

Operator Description
= (equal) Selected values ​​equal to the specified

Example:

SELECT * FROM topics WHERE id_author=4;

Result:

> (more) Values ​​greater than the specified are selected

Example:

SELECT * FROM topics WHERE id_author>2;

Result:

< (меньше) Values ​​less than specified are selected

Example:

SELECT * FROM topics WHERE id_author
Result:

>= (greater than or equal to) Values ​​greater than or equal to the specified value are selected.

Example:

SELECT * FROM topics WHERE id_author>=2;

Result:

<= (меньше или равно) Values ​​less than or equal to the specified value are selected.

Example:

SELECT * FROM topics WHERE id_author
Result:

!= (not equal) Values ​​not equal to the specified are selected

Example:

SELECT * FROM topics WHERE id_author!=1;

Result:

IS NOT NULL Rows that have values ​​in the specified field are selected

Example:

SELECT * FROM topics WHERE id_author IS NOT NULL;

Result:

IS NULL Rows that do not have a value in the specified field are selected

Example:

SELECT * FROM topics WHERE id_author IS NULL;

Result:

Empty set - no such strings.

BETWEEN (between) Values ​​between the specified values ​​are selected.

Example:

SELECT * FROM topics WHERE id_author BETWEEN 1 AND 3;

Result:

IN (value contained) The values ​​corresponding to the specified

Example:

SELECT * FROM topics WHERE id_author IN (1, 4);

Result:

NOT IN (value not contained) Selected values ​​other than those specified

Example:

SELECT * FROM topics WHERE id_author NOT IN (1, 4);

Result:

LIKE (match) Sample values ​​are selected

Example:

SELECT * FROM topics WHERE topic_name LIKE "vel%";

Result:

Possible metacharacters of the LIKE operator will be discussed below.

NOT LIKE Values ​​that do not match the sample are selected

Example:

SELECT * FROM topics WHERE topic_name NOT LIKE "vel%";

Result:

LIKE operator metacharacters

Metacharacter searches can only be performed in text fields.

The most common metacharacter is % . It means any characters. For example, if we want to find words that start with the letters "vel", then we will write LIKE "vel%", and if we want to find words that contain the characters "club", then we will write LIKE "%club%". For example:

Another commonly used metacharacter is _ . Unlike %, which denotes few or no characters, underscore denotes exactly one character. For example:

Pay attention to the space between the metacharacter and "fish", if you skip it, the request will not work, because metacharacter _ stands for exactly one character, and a space is also a character.

It's enough for today. In the next lesson, we will learn how to query two or more tables. In the meantime, try to make your own queries against the posts table (messages).

So, there are three tables in the forum database:

users (users);

Topics (topics);

· posts (messages).

You need to see what data they contain. To do this, there is an operator in SQL SELECT. The syntax for using it is as follows:

SELECT select_what FROM select_from;

Instead of “what_to_select”, you must specify either the name of the column whose values ​​you want to see, or the names of several columns separated by commas, or the asterisk symbol (*), meaning the selection of all columns of the table. Instead of "from_choose" you should specify the name of the table.

First, let's look at all the columns from the users table:

SELECT * FROM users;

This is all the data that has been entered into the table.

Let's assume that we only need to look at the id_user column (because we need to know what id_users are in the users table to populate the topics table). To do this, specify the name of this column in the query:

SELECT id_user FROM users;

If you need to see, for example, the names and e-mails of users, then you need to list the columns of interest separated by commas:

SELECT name, email FROM users;

Similarly, you can see what data other tables contain.

First, let's see what themes are:

SELECT * FROM topics;

Now there are only 4 topics in the table, but what if there are 100 of them? I would like them to be displayed, for example, alphabetically. There is a keyword for this in SQL. ORDER BY followed by the name of the column to sort by. The syntax is the following:

SELECT column_name FROM table_name ORDER BY sort_column_name;

The default sorting is ascending, but this can be changed by adding the keyword DESC.

The data is now sorted in descending order.

You can sort by several columns at once. For example, the following query will sort the data by the topic_name column, and if there are several identical rows in this column, then the id_author column will be sorted in descending order:

Compare the result with the result of the previous query.

Very often the user does not need all the information from the table. For example, you need to find out which topics were created by the user sveta (id = 4). There is a keyword for this in SQL. WHERE, the syntax for such a request is as follows:

SELECT column_name FROM table_name WHERE condition;

For our example, the condition is the user ID, i.e. only those rows are needed, in the id_author column of which is 4 (user ID sveta):

SELECT * FROM topics WHERE id_author=4;

Now you need to find out who created the theme "bicycles":

Of course, it would be more convenient to display the author's name instead of the author's id, but the names are stored in another table. Next, let's look at how to select data from multiple tables. In the meantime, let's learn what conditions can be specified using the WHERE keyword.

Operator Description
= (equal) Values ​​equal to the specified are selected. Example: SELECT * FROM topics WHERE id_author=4; Result:
> (more) Values ​​greater than the specified are selected. Example: SELECT * FROM topics WHERE id_author > 2; Result:
< (меньше) Values ​​less than the specified are selected. Example: SELECT * FROM topics WHERE id_author< 3; Результат:
>= (greater than or equal to) Values ​​greater than and equal to the specified value are selected. Example: SELECT * FROM topics WHERE id_author >= 2; Result:
<= (меньше или равно) Values ​​less than or equal to the specified value are selected. Example: SELECT * FROM topics WHERE id_author<= 3; Результат:
!= (not equal) Values ​​not equal to the specified are selected. Example: SELECT * FROM topics WHERE id_author != 1; Result:
IS NOT NULL Rows that have values ​​in the specified field are selected. Example: SELECT * FROM topics WHERE id_author IS NOT NULL; Result:
IS NULL Rows that do not have a value in the specified field are selected. Example: SELECT * FROM topics WHERE id_author IS NULL; Result:
Empty set - no such strings.
BETWEEN (between) Values ​​between the specified values ​​are selected. Example: SELECT * FROM topics WHERE id_author BETWEEN 1 AND 3; Result:
IN (value contained) The values ​​corresponding to the specified ones are selected. Example: SELECT * FROM topics WHERE id_author IN (1, 4); Result:
NOT IN (value not contained) Values ​​other than those specified are selected. Example: SELECT * FROM topics WHERE id_author NOT IN (1, 4); Result:
LIKE (match) Values ​​that match the sample are selected. Example: SELECT * FROM topics WHERE topic_name LIKE "vel%"; Result:
Possible metacharacters of the LIKE operator will be discussed below.
NOT LIKE Values ​​that do not match the sample are selected. Example: SELECT * FROM topics WHERE topic_name NOT LIKE "vel%"; Result:

Practical work No. 9

Lesson topic: Creating SQL queries.

Purpose of the lesson: Learn how to use the SQL language to create queries.

Lesson plan :

1. Creation of SQL queries for selection.

2. Creation of SQL queries for a selection with a selection condition.

3. Creation of SQL queries with calculation.

4. Creation of SQL queries for grouping.

SQL ( Structured Query language) - a structured query language that provides tools for creating and processing data in a database.

In order to create a query using SQL language tools, you must perform the following steps:

    Create a query using the constructor.

· In the Query Builder, right-click in the table display area and select "SQL Mode" from the context menu.

1. CreationSQL queries for selection.

Let's create a simple query to select goods and orders for these goods using SQL.

· Open the SQL query editor.

In the editor window, enter the following query procedure

SELECT Orders.[Order ID], Products.[Product name], Orders. Quantity, Goods. Price, Products.[Unit], Orders.[Order Date]

FROM Products INNER JOIN Orders ON Products.[Product ID] = Orders. Product;

· Save the query as SQL query.

· Check that the query works correctly.

Let's analyze the syntax of this operation:

SELECT is a statement that tells the database that this operation is a query (almost all queries begin with this word). After the SELECT statement, a listing of those fields that will be included in the query usually begins. For example, the record SELECT Orders.[Order Code] will mean that the query will include the field Order code from the order table. If the field name contains spaces, it must be enclosed in square brackets.

FROM is the operator responsible for the data source. If you need to specify relationships between tables, then you need to use the INNER JOIN operator.

INNER JOIN - Joins records from two tables if the join fields of these tables contain the same values. For example, the entry “FROM Products INNER JOIN Orders ON Products.[Product Code] = Orders. Product" means that in this request procedure, the field Product code From the Products table is the record source for the field Product tables "Orders"

Exercise: Create an SQL query that allows you to display information about customers who bought the product.

2. Creation of SQL queries for a selection with a selection condition.

Using the SQL language, we will create a query that allows you to display information about employees who sold goods in quantities greater than 3.

To create queries with a selection condition, the WHERE clause is used.

Create an SQL select query containing the following fields: Full Name Employee Order code Which one to serve Quantity. Check if it works correctly.

· Now you need to add a selection condition. Open the SQL editor and add "WHERE (((Orders. Quantity)>3))" to the end of the query procedure.

· Save the query under the name "Select with SQL selection condition". Check if the request works.

Exercise: Create an SQL query that selects all products for which the price is not stopped and the price does not exceed 20 currency units.

3. Creation of SQL queries with calculation.

Let's create an SQL query that allows you to display the customer's last name, product name, order amount (price*quantity).

The request procedure looks like this:

SELECT Clients. Surname, Products.[Product Name], Orders! Quantity*Products! Price AS [Order Amount]

FROM Products INNER JOIN (Customers INNER JOIN Orders ON Clients.[Customer ID]=Orders. Customer) ON Products.[Product ID]=Orders. Product;

4. Creation of SQL queries for grouping.

Let's create a query that will allow us to determine the total amount of goods ordered by each client.

The GROUP BY clause is used to group records.

The request procedure looks like this:

SELECT Clients. Last Name, Sum(Orders! Quantity*Items! Price) AS [Sum of Orders]

FROM Products INNER JOIN (Customers INNER JOIN Orders ON Clients.[Customer ID] = Orders. Customer) ON Products.[Product ID] = Orders. Product

GROUP BY Clients. Surname;

Control questions:

1. What is SQL?

2. How to create a SQL query?

3. Structural components of the SQL language.

4. List the main operators of the SQL language.

5. General information about SELECT, WHERE, FROM, INNER JOIN, GROUP BY statements.

Task for successful students: Try to create a SQL query yourself that allows you to delete all records from the "Products" table, the price of which is less than 3 monetary units

Conclusion: In the course of this work, the main ways and methods of creating SQL queries were studied. The structural components of the query language were considered, and the syntax for using operators was described.



Liked the article? Share it