How to insert a row in postgresql pgadmin?
Inserting a row into a PostgreSQL database can be done in multiple ways, including using the pgAdmin GUI or writing SQL commands. When using pgAdmin, it is important to understand the structure of the table in order to insert data into the correct columns. This tutorial will provide the steps and methods to insert a row into a PostgreSQL table using pgAdmin.
Method 1: Using pgAdmin's Query Tool
To insert a row in PostgreSQL using pgAdmin's Query Tool, you can follow these steps:
- Open pgAdmin and connect to your PostgreSQL server.
- Navigate to the database where you want to insert the row.
- Right-click on the table where you want to insert the row and select "Scripts" > "INSERT Script".
- In the Query Tool window, you will see a template for the INSERT statement.
- Replace the placeholders in the template with the actual values you want to insert.
- Execute the query by clicking the "Execute" button or pressing F5.
Here is an example of an INSERT statement using pgAdmin's Query Tool:
In this example, we are inserting a new row into the "employees" table with the values 'John' for the "first_name" column, 'Doe' for the "last_name" column, 'john.doe@example.com' for the "email" column, and '555-555-5555' for the "phone_number" column.
You can also insert multiple rows at once using a single INSERT statement by separating each set of values with a comma, like this:
In this example, we are inserting three new rows into the "employees" table at once.
That's it! With these examples and steps, you should now be able to insert a row in PostgreSQL using pgAdmin's Query Tool.
Method 2: Using pgAdmin's Object Browser
To insert a row in PostgreSQL using pgAdmin's Object Browser, follow these steps:
- Open pgAdmin and connect to your database.
- Navigate to the table you want to insert a row into using the Object Browser.
- Right-click on the table and select "View/Edit Data" -> "All Rows".
- Click on the "Add New Row" button in the toolbar.
- Enter the values for the new row in the columns.
- Click the "Save" button in the toolbar to save the new row.
Here is an example of inserting a new row into a table called "users" with columns "id", "name", and "email":
You can also insert multiple rows at once by separating the values with commas:
If you want to insert a row with default values for some columns, you can omit those columns from the INSERT statement:
If the table has a serial column (auto-incrementing), you can use the keyword "DEFAULT" to insert the next available value:
Method 3: Writing SQL INSERT Statement
To insert a row in PostgreSQL using pgAdmin, you can use the SQL INSERT statement. Here are the steps:
Open pgAdmin and connect to your PostgreSQL server.
Open the SQL editor by right-clicking on the database and selecting "Query Tool".
Write the INSERT statement, specifying the table name and the values you want to insert. For example:
Execute the statement by clicking the "Execute query" button or pressing F5.
Verify that the row has been inserted by running a SELECT statement. For example:
Here are some additional examples of INSERT statements:
Inserting a row with a NULL value:
Inserting multiple rows at once:
Inserting data from another table:
Using a subquery to insert data:
These examples should help you get started with inserting rows in PostgreSQL using pgAdmin and SQL INSERT statements.
Учебное пособие по PGAdmin4 для начинающих

Перед тем, как начать это руководство, вам необходимо подтвердить, что pgAdmin4 установлен и правильно работает в вашей операционной системе Ubuntu. Если pgAdmin4 не установлен в вашей системе, вы можете выполнить шаги из следующего руководства, чтобы установить pgAdmin4 сначала и запустите этот учебник.
После успешной установки pgAdmin4, откройте следующую ссылку в любом браузере, чтобы открыть pgAdmin4 клиент.
http: // локальный: 5050

Если развернуть Базы данных а также Вход / Групповые роли разделы из Элемент управления деревом pgAdmin тогда будет показан весь ранее созданный список баз данных и роли. Здесь одна база данных с именем ‘postgres’ и две роли входа / группы, ‘pg_signal_backend’ а также ‘postgres’ созданы во время pgAdmin4 монтаж.

Создать нового пользователя
Каждая база данных связана с конкретным пользователем или группой пользователей. Вы можете создать базу данных, связавшись с любым существующим пользователем / группой или любым новым пользователем после создания. В этом руководстве новый пользователь с именем ‘админ‘создан со всеми привилегиями. Выполните следующие шаги, чтобы создать нового пользователя.
Шаг 1:
Щелкните правой кнопкой мыши на Вход / Групповые роли, Выбрать Создавать и нажмите на Вход / Групповые роли… для создания нового пользователя.
Шаг 2:
Появится следующее диалоговое окно Create. Тип ‘админ ‘ в Имя поле в качестве имени пользователя и нажмите Определение вкладка.

Шаг 3:
Введите логин пароль для пользователя админ и нажмите на Привилегии вкладка. Если вы хотите создать пользователя на ограниченное время, установите Срок действия учетной записи истекает данные и временная стоимость.

Шаг 4:
Чтобы установить все разрешения на админ пользователь делает все параметры для ‘да‘. Нажмите ‘Сохранить’ кнопка для создания пользователя.

‘админ’ запись пользователя будет отображаться в Вход / Групповые роли раздел.

Создать новую базу данных
Предположим, вам нужно создать базу данных с именем ‘Online_Library ‘. Выполните следующие шаги для создания базы данных.
Шаг 1:
Щелкните правой кнопкой мыши на Базы данных, Выбрать Создавать и нажмите База данных… возможность создания новой базы данных.

Шаг 2:
Появится следующее диалоговое окно для создания новой базы данных. Тип «Online_Library» в База данных поле и выберите ‘admin’ как владелец базы данных. Нажмите ‘Сохранить’ кнопка для создания базы данных.

«Online_Library» база данных будет показана в разделе Базы данных.

Создать таблицы
Предполагать, «Online_Library» база данных содержит две таблицы ‘book_type’ а также ‘Список книг’. Таблицы с примерами данных приведены ниже.
Таблица: book_type
| Я БЫ | Категория | Тип |
| 1 | CSE | Программирование |
| 2 | MBBS | Анатомия |
| 3 | BBA | Финансы |
По данным таблицы, book_type таблица имеет три поля, которые Я БЫ, Категория а также Тип. Здесь значение Я БЫ поле является числовым и будет увеличиваться автоматически, Категория а также Тип поля являются строковыми. Первичный ключ этой таблицы Я БЫ и все поля обязательны.
Таблица: book_list
| Я БЫ | Book_Name | Имя автора | Версия | Type_ID |
| E001 | Java — полный справочник | Герберт Шильдт | 7 th | 1 |
| M001 | Анатомические поезда | Томас В. Майерс | 3 rd | 2 |
| E002 | Поваренная книга Python | Брайан Джонс и Дэвид Бизли | 3 rd | 1 |
| B001 | Финансовый учет для BBA | Д-р С. Н. Махешвари и К. А. Шарад К. Махешвари | 3 |
По данным таблицы, Список книг таблица имеет 5 полей, которые ID, имя книги, имя автора, Версия а также Type_ID. Здесь, ID, Book_Name а также Имя автора поля не могут быть пустыми и Версия поля могут быть пустыми. Я БЫ поле является первичным ключом и Type_ID поле является внешним ключом для этой таблицы. Теперь выполните следующие шаги, чтобы создать эти таблицы в «Online_Library» база данных с использованием pgAdmin4.
Шаг 1:
Нажмите на ‘Схемы«раздел»Online_Library ‘ база данных. Расширять ‘общественный’ раздел и узнайте ‘Таблицы’ раздел.

Шаг 2:
Щелкните правой кнопкой мыши «Таблицы», выберите ‘Создавать’ и нажмите ‘Таблица… ‘ вариант.

Шаг 3:
Появится следующее диалоговое окно для создания новой таблицы. Тип ‘book_type’ в Имя поле выберите Владелец стола (здесь, админ выбран как владелец) и выберите Схема а также Табличное пространство.

Шаг 4:
Выбирать ‘Столбцы’ вкладка и нажмите на ‘+’ кнопка для создания нового поля для таблицы.

Шаг — 5:
Добавьте три обязательных поля ‘book_type’ таблица, как в следующем диалоговом окне. Набор ‘bigserial‘как тип данных (для добавления атрибута автоматического увеличения) и установить’да‘ в ‘Ненулевой’ а также ‘Первичный ключ’ поля Я БЫ столбец. Значение Категория а также Тип столбец может отличаться. Так что выберите ‘характер меняющийся ‘ как тип данных для этих полей. Нажмите ‘Сохранить’ кнопка для создания таблицы.

Шаг 6:
Снова откройте следующее диалоговое окно для создания другой таблицы с именем ‘Список книг’. Тип ‘Список книг’ в Имя поле и выберите другие значения других полей, например шаг 3.

Шаг 7:
Нажмите на Столбец вкладку и добавьте поля в соответствии с требованиями таблицы. Здесь, Я БЫ столбец будет содержать данные фиксированной длины (4 символа). За это, ‘персонаж’ тип данных выбран для Я БЫ столбец. Значение Book_Name, Имя автора а также Версия может изменяться. Так, ‘характер меняющийся ‘ для этих столбцов выбран тип данных. ‘Ненулевой’ опция установлена на ‘Да’ для Версия столбец для принятия Ноль значение, когда данные не будут отправлены.

Шаг 8:
Нажмите ‘Ограничения ‘ вкладка для установки первичного и внешнего ключей. Эта вкладка содержит еще 5 вкладок. Первая вкладка ‘Первичный ключ’. На этой вкладке будет отображаться информация о первичном ключе таблицы. Один первичный ключ установлен на предыдущем шаге, который отображается здесь. Если вы хотите добавить или удалить какой-либо первичный ключ, вы можете выполнить эту задачу на этой вкладке.

Шаг 9:
Эта таблица содержит внешний ключ на основе информации таблицы, упомянутой выше. Нажмите ‘Иностранный ключ’ вкладка для определения внешнего ключа. Нажмите кнопку «+», чтобы добавить внешний ключ.

Шаг-10:
Нажмите кнопку Edit (), чтобы открыть вкладку для создания внешнего ключа.

Шаг 11:
Введите имя внешнего ключа в Имя поле. Здесь, ‘Book_Type ‘ устанавливается как имя внешнего ключа. Далее нажмите Столбцы вкладка.

Шаг 12:
Выбирать Локальный столбец, Рекомендации а также Ссылка из раскрывающегося списка. Для этого стола, Type_ID поле является внешним ключом и установлено как Локальный столбец. ‘book_type‘таблица выбрана как Справка стол и Я БЫ поле ‘book_type‘выбрано как Ссылка столбец. После настройки нажмите кнопку «+», чтобы добавить внешний ключ.

Шаг 13:
Информация о добавленном внешнем ключе будет отображаться внизу. Нажмите на ‘Действие‘, чтобы добавить конкретное действие на Обновить а также Удалить данные справочной таблицы.

Шаг 14:
Выбирать ‘КАСКАД‘вариант для операции обновления и удаления. Когда Я БЫ значение book_type таблица обновит или удалит связанную запись (и) Список книг таблица будет произведена. Нажмите ‘Сохранить’ кнопка для завершения задачи создания таблицы.

После выполнения вышеуказанных шагов, Таблицы раздел будет содержать следующие два имени таблицы. Если вы хотите изменить структуру таблицы, щелкните правой кнопкой мыши имя конкретной таблицы и нажмите характеристики открыть диалоговое окно для изменения структуры таблицы.

После создания базы данных и таблиц вы можете выполнять различные типы команд SQL, такие как выбор, вставка, обновление и удаление в определенной таблице. Вы также можете выполнять другие операции с базой данных, такие как создание функции, просмотра, триггера и т. Д. в pgAdmin4. Надеюсь, вы сможете выполнять основные операции с базой данных в pgAdmin4 после прочтения этого руководства.
Игры 
View/Edit Data¶
To view or modify data, right click on a table or view name in the Object Explorer. When the context menu opens, use the View/Edit Data menu to specify the number of rows you would like to display in the editor panel.

To modify the content of a table, each row in the table must be uniquely identifiable. If the table definition does not include an OID or a primary key, the displayed data is read only. Note that views cannot be edited; updatable views (using rules) are not supported.
The editor features a toolbar that allows quick access to frequently used options, and a work environment divided into two panels:
The upper panel displays the SQL command that was used to select the content displayed in the lower panel.
The lower panel (the Data Grid) displays the data selected from the table or view.
The View/Edit Data Toolbar¶
The Query Tool and View/Edit Data tools are actually different operating modes of the same tool. Some controls will be disabled in either mode. Please see The Query Tool Toolbar for a description of the available controls.
The Data Grid¶
The top row of the data grid displays the name of each column, the data type, and if applicable, the number of characters allowed. A column that is part of the primary key will additionally be marked with [PK].
To modify the displayed data:
To change a numeric value within the grid, double-click the value to select the field. Modify the content in the square in which it is displayed.
To change a non-numeric value within the grid, double-click the content to access the edit bubble. After modifying the contentof the edit bubble, click the Ok button to display your changes in the data grid, or Cancel to exit the edit bubble without saving.
To enter a newline character, click Ctrl-Enter or Shift-Enter. Newline formatting is only displayed when the field content is accessed via an edit bubble.
To add a new row to the table, enter data into the last (unnumbered) row of the table. As soon as you store the data, the row is assigned a row number, and a fresh empty line is added to the data grid.
To write a SQL NULL to the table, simply leave the field empty. When you store the new row, the will server fill in the default value for that column. If you store a change to an existing row, the value NULL will explicitly be written.
To write an empty string to the table, enter the special string ‘’ (two single quotes) in the field. If you want to write a string containing solely two single quotes to the table, you need to escape these quotes, by typing »
To delete a row, press the Delete toolbar button. A popup will open, asking you to confirm the deletion.
To commit the changes to the server, select the Save Data toolbar button.
Geometry Data Viewer
If PostGIS is installed, you can view GIS objects in a map by selecting row(s) and clicking the ‘View Geometry’ button in the column. If no rows are selected, the entire data set will be rendered:

You can adjust the layout by dragging the title of the panel. To view the properties of the geometries directly in map, just click the specific geometry:

Supported data types: The Geometry Viewer supports 2D and 3DM geometries in EWKB format including Point, LineString, Polygon MultiPoint, MultiLineString, MultiPolygon and GeometryCollection .
SRIDs: If there are geometries with different SRIDs in the same column, the viewer will render geometries with the same SRID in the map. If SRID=4326 the OSM tile layer will be added into the map.
Data size: For performance reasons, the viewer will render no more than 100000 geometries, totaling up to 20MB.
Internet access: An internet connection is required for the Geometry Viewer to function correctly.
JSON Data Editor
A built in json editor is provided for JSON/JSONB Data.Double clicking on json/jsonb data type cell in data grid will open JSON Editor.Editor provides different mode to view and edit json data.

Code Mode: Provides way to format & compact json data.Also provides ability to repair json data by fixing quotes and escape characters, removing comments and JSONP notation and turn JavaScript objects into JSON.
Tree Mode: Enabled to change, add, move, remove, and duplicate fields and values.Provides ability to searh & hilight data.
Form Mode: Allows only to edit values in json data there by providing ability to keep data structure unchanged while editing.
Preview Mode: Provides ability to check data before saving and also shows size of current json data. Format and compact json data as well.
Different options are provided to manipulate json data.





