Basic sql commands. Data access mechanism. Structured Query Language SQL. History and standards of SQL. Processing SQL commands by the Oracle server. Removal requests
Any conceptual information about relational databases and tables is only useful if you know how to interact with the data. The SQL language consists of structured commands for adding, modifying, and deleting data from a database. These commands form the basis for interacting with the PostgreSQL server.
This section is about the "anatomy" of SQL commands. It examines the structural components of commands, describing the functions of each component and their mutual relationships. The standard PostgreSQL command line client, psql, prints the results of the commands in the examples given.
Most of the SQL command examples are specific to the booktown database. All psql output is prefixed with the form booktown=# .
Some examples use the testdb test database. By default, the psql prompt displays only the database name and =# symbols, indicating that the system is ready to issue a new command (although you will see the = symbol dynamically change as the state of the SQL input is monitored). The book provides this prompt along with the SQL input and output to help you get comfortable with the psql client output.
The psql client is described in detail in Chapter 4. It is mentioned here only to clarify the style of the SQL command examples.
Note
The booktown database schema (along with example records) is located in the booktown.sql file on the CD. To install this database, enter the command psql - U postgres template! at the command prompt. - f /mnt/cdrom/booktown.sql, where /mnt/cdrom is the path to the mounted CD and postgres is the PostgreSQL superuser name.
SQL commands always begin with an action (verb) - a word or group of words that describes the operation being performed. In addition, an SQL command usually contains one or more sections that clarify its meaning. In table 3.2 lists the main actions of SQL.
Table 3.2. Basic PostgreSQL Actions.
CREATE DATABASE | Creating a new database |
CREATE INDEX | Creating a new index on a table column |
CREATE SEQUENCE | Creating a new sequence in an existing database |
CREATE TABLE | Creating a new table in an existing database |
CREATE TRIGGER | Create a new trigger definition |
CREATE VIEW | Create a new view for an existing table |
SELECT | Selecting records from a table |
INSERT | Inserting one or more new records into a table |
UPDATE | Modifying data in existing records |
DELETE | Removing existing records from a table |
DROP DATABASE | Destroying an existing database |
DROP INDEX | Removing a column index from an existing table |
DROP SEQUENCE | Destroying an existing sequence generator |
DROP TABLE | Destroying an existing table |
DROP TRIGGER | Destroying an existing trigger definition |
DROP VIEW | Destroying an existing view |
CREATE USER | Creating a new PostgreSQL user account in the system |
ALTER USER | Modifying an existing PostgreSQL user account |
DROP USER | Deleting an existing PostgreSQL user account |
GRANT | Granting access rights to a database object |
REVOKE | Removing access rights to a database object |
CREATE FUNCTION | Creating a new SQL function in a database |
CREATE LANGUAGE | Creating a new language definition in the database |
CREATE OPERATOR | Creating a new SQL statement in the database |
CREATE TYPE | Creating a new SQL data type in a database |
Structured Query Language was developed by IBM in the early 1970s. In 1986, SQL was first standardized by the ANSI organizations.
SQL is a powerful and at the same time simple language for database management. It is supported by almost all modern databases. SQL is divided into two subsets of commands: DDL (Data Definition Language) and DML (Data Manipulation Language). DDL commands are used to create new databases, tables and columns, and DML commands are used to read, write, sort, filter, delete data.
This article will take a closer look at DML commands, since they are used much more often.
DDL CommandsCREATE - used to create new tables, columns and indexes.
DROP - used to remove columns and indexes.
ALTER - used to add new columns to tables and change specific columns.
DML CommandsSELECT is the most commonly used command and is used to retrieve a set of data from a database table. The SELECT command has the following syntax:
SELECT field_list1 FROM table_name ]
Operators inside square brackets are optional, and the vertical bar means that one of the specified phrases must be present, but not both.
For example, let's create a simple query to obtain data from the "name" and "phone" fields of the "friends" table:
SELECT name, phone FROM friends
If you need to get all the fields of the table, then it is not necessary to list them, just put an asterisk (*):
SELECT * FROM friends
To exclude duplicate entries from the displayed list, use the DISTINCT keyword:
SELECT DISTINCT name FROM friends
If you need to get a separate record, then the WHERE clause is used. For example, we need to get the phone number of “Vasya Pupkin” from the “friends” table:
SELECT * FROM friends WHERE name = "Vasya Pupkin"
or vice versa, we need to find out who owns the phone 44-65-01:
SELECT * FROM friends WHERE phone = "44-65-01"
In addition, you can use wildcard characters, thereby creating search patterns. The LIKE operator is used for this. The LIKE operator has the following substitution operators:
* - matches a string consisting of one or more characters;
Matches any one character;
Matches one character from a specific set;
For example, to retrieve records from the "name" field containing the word "Vasya", the request would look like this:
SELECT * FROM friends WHERE name LIKE "*Vasya*"
The ORDER BY clause is used to determine the order in which data is returned. Without this operator, the order of the returned data cannot be predicted. The keywords ASC and DESC allow you to determine the direction of sorting. ASC sorts in ascending order, and DESC orders in descending order.
For example, a request to get a list of records from the "name" field in alphabetical order would look like this:
SELECT * FROM friends ORDER BY name
Note that the ASC keyword is not required because it is the default.
INSERT - this command is used to add a new record to the table. It is written as follows:
INSERT INTO table_name VALUES ( value_list)
Please note that the value types in the list of values must match the value types of the table fields, for example:
INSERT INTO friends VALUES ( "Anka the Machine Gunner", "32-09-81" )
This example adds a new entry to the friends table with the specified values.
UPDATE - This command is used to update data in a table and is most often used in conjunction with the WHERE clause. The UPDATE command has the following syntax:
UPDATE table_name SET field_name = meaning
If you omit the WHERE clause, the data in all defined fields in the table will be updated. For example, let’s change Vasya Pupkun’s phone number:
UPDATE friends SET phone = "55-55-55" WHERE name = "Vasya Pupkin"
DELETE - as you probably already understood, this command is used to delete records from the table. Like UPDATE, the DELETE command is usually used with a WHERE clause; if this clause is omitted, all data from the specified table will be deleted. The DELETE command syntax is as follows:
DELETE FROM table_name
For example, let's remove this annoying Vasya Pupkin from our table :) :
DELETE FROM friends WHERE name = "Vasya Pupkin"
The endIn this article I talked about the main SQL operators, they are quite sufficient for working with databases; I will talk about the remaining operators in more detail another time.
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 examplesCreate 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 databases1. View available databases SHOW DATABASES; 2. Creating a new database CREATE DATABASE; 3. Selecting a database to use USE; 4. Import SQL commands from the .sql file SOURCE ; 5. Removing the database DROP DATABASE ; Working with tables6. View the tables available in the SHOW TABLES database;
7. Creating a new table CREATE TABLE ( , , PRIMARY KEY (), FOREIGN KEY () REFERENCES ()); Integrity Constraints When Using CREATE TABLEYou 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.
ExampleCreate 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 informationYou 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. Deleting all data from the table DELETE FROM ; 12. Removing a table DROP TABLE ; Commands for creating queries13. SELECTSELECT 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 DISTINCTTable columns may contain duplicate data. Use SELECT DISTINCT to retrieve only non-duplicate data.
SELECT DISTINCT , , … FROM ;
15. WHEREYou 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).
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 BYThe 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 ;
ExampleLet's display the number of courses for each faculty:
SELECT COUNT(course_id), dept_name FROM course GROUP BY dept_name;
17. HAVINGThe HAVING keyword was added to SQL because WHERE cannot be used with aggregate functions.
SELECT , , ... FROM GROUP BY HAVING
ExampleLet'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 BYORDER 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;
ExampleLet'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. BETWEENBETWEEN 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 ;
ExampleLet'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. LIKEThe 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).
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. INUsing IN you can specify multiple values for the WHERE clause:
SELECT , , … FROM WHERE IN (, , …);
ExampleLet'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. JOINJOIN 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 1We 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 2We 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 3We 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. ViewView 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.
Creating CREATE VIEW AS SELECT , , ... FROM WHERE ; Removing DROP VIEW ; ExampleLet's create a view consisting of courses with 3 credits:
24. Aggregate functionsThese 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.
Nested subqueries are SQL queries that include SELECT , FROM , and WHERE clauses nested within another query.
ExampleLet'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);
Kirill Pozdeev, translator
How Yandex uses your data and machine learning to personalize services -.
SQL (ˈɛsˈkjuˈɛl; English structured query language - “structured query language”) is a declarative programming language used to create, modify and manage data in a relational database.
Compliance with SQL standards for different databases:
SQL (Structured Query Language - structured query language). SQL is primarily an information logical language designed to describe stored data, to retrieve stored data, and to modify data.
SQL is not a programming language. As SQL has become more complex, it has become more of an application programming language, and users are now able to use visual query builders.
SQL is a case-insensitive language. Strings in SQL are enclosed in single quotes.
The SQL language is a collection of statements. SQL statements are divided into:
Data Definition Language (DDL) - schema description language in ANSI, consists of commands that create objects (tables, indexes, views, etc.) in the database (CREATE, DROP, ALTER, etc.).
Data manipulation operators (Data Manipulation Language, DML) are a set of commands that determine what values are presented in tables at any time (INSERT, DELETE, SELECT, UPDATE, etc.).
data access definition statements (Data Control Language, DCL) - consists of tools that determine whether to allow the user to perform certain actions or not (GRANT/REVOKE, LOCK/UNLOCK).
Transaction Control Language (TCL) operators
Unfortunately, these terms are not used universally across all implementations. They are emphasized by ANSI and are useful on a conceptual level, but most SQL programs do little to treat them separately, so they essentially become functional categories of SQL commands.
SELECT section JOINSimple JOIN (=intersection JOIN =INNER JOIN) - means to show only the common records of both tables. How records are considered shared is determined by the fields in the join expression. For example, the following entry: FROM t1 JOIN t2 ON t1. id = t2. id
means that records with the same id that exist in both tables will be shown.
LEFT JOIN (or LEFT OUTER JOIN) means to show all records from the left table (the one that comes first in the join expression) regardless of whether there are corresponding records in the right table. If there are no records in the right table, the empty value NULL is set.
RIGHT JOIN (or RIGHT OUTER JOIN) acts in contrast to LEFT JOIN - it shows all records from the right (second) table and only those that match from the left (first) table.
Other types of JOIN joins: MINUS - subtraction; FULL JOIN - complete join; CROSS JOIN - “Everyone with everyone” or the Cartesian product operation.
INSERT IGNORE If you specify the IGNORE keyword in an INSERT command with rows that have multiple values, then any rows that have duplicate PRIMARY or UNIQUE keys in that table will be ignored and not inserted. If you do not specify IGNORE, this insert operation aborts when it encounters a row that has a duplicate value for an existing key
The REPLACE command differs from INSERT only in that if there is a record in the table with the same value in the indexed field (unique index) as the new record, then the old record is deleted before adding the new one.
UPDATE< tablename>SET ( | ) .,. .< COLUMN name> = < VALUE expresslon>[WHERE< predlcate>| WHERE CURRENT OF< cursor name>(*only for attachment*) ] ; UPDATE peers SET zone= "voip" ; # update all rows in the zone column of the peers table UPDATE stat SET whp= "13x13x13" WHERE id = 1 ; UPDATE countries SET nm_ukr= ( SELECT del_countries. ukrainian FROM del_countries WHERE countries. nm_en= del_countries. english ) ;WordPress usage, setting: in the wp_posts table, delete all occurrences of the row
UPDATE wp_posts SET post_content = REPLACE (post_content, "" , "" ) ;DELETE FROM