sql dual что такое
ДВОЙНАЯ таблица SQL
Что такое ДВОЙНОЙ стол?
Смотрите следующие команды:
Следующая команда отображает структуру таблицы DUAL:
Следующая команда отображает содержимое таблицы DUAL:
Следующая команда отображает количество строк таблицы DUAL:
Следующая команда отображает строковое значение из таблицы DUAL:
Следующая команда отображает числовое значение из таблицы DUAL:
Следующая команда пытается удалить все строки из таблицы DUAL:
Следующая команда пытается удалить все строки из таблицы DUAL:
Примечание. Команда DELETE используется для удаления строк из таблицы. После выполнения операции DELETE вам нужно выполнить COMMIT или ROLLBACK транзакцию, чтобы сделать изменение постоянным или отменить его. TRUNCATE удаляет все строки из таблицы. Операция не может быть отменена.
Следующая команда выбирает две строки из двух:
Вы также можете проверить системную дату из таблицы DUAL, используя следующую инструкцию:
Вы также можете проверить арифметическое вычисление из таблицы DUAL, используя следующую инструкцию:
Следующий код отображает числа 1..10 от DUAL:
В следующем коде DUAL предполагает использование декодирования с NULL.
ДВОЙНАЯ таблица: Oracle против MySQL
Но следующая команда будет выполнена (см. Вывод предыдущего примера):
В случае MySQL будет выполнена следующая команда:
В следующей таблице показано использование фиктивной таблицы в стандартной СУБД.
СУБД | Концепция пустышки |
---|---|
MSSQL | Нет концепции пустышки. |
MySQL | Нет концепции пустышки. |
оракул | Пустой стол: ДВОЙНОЙ. |
Informix | Начиная с версии 11.10, фиктивная таблица была включена: sysmaster: sysdual |
PostgreSQL | Нет концепции пустышки. |
DB2 | Пустой стол: SYSIBM.SYSDUMMY1 |
Упражнения по SQL
Хотите улучшить вышеуказанную статью? Вносите свои заметки / комментарии / примеры через Disqus.
Sql dual что такое
Серьезные знакомства teamo wearelove.ru/teamo/.
Еще раз о таблице DUAL
И.Гершанов с комментарием А.Бачина
Наш читатель Илья Гершанов написал в редакцию:
В недавней апрельской статье «Предупреждение проблем с таблицей DUAL», раздел «Опыт пользователей», написано, что если в таблице DUAL может оказаться более одной строки или не оказаться строк вовсе, то могут возникнуть проблемы.
Но, раз таблица фиктивная, то у нее нет сегмента, то и речи быть не может о добавлении строк. Был проведен эксперимент:
1. Запуск экземпляра в режиме » startup nomount » и запрос:
SVRMGR> select * from dual;
ADDR INDX INST_ID D
2. Перевод экземпляра в режим » alter database mount; » и запрос
SVRMGR> select * from dual;
ADDR INDX INST_ID D
3. Перевод экземпляра в работоспособное состояние » alter database open; » и запрос
SVRMGR> select * from dual;
Продолжим эксперименты с DML на таблице DUAL
4. Выполним следующие запросы в SQL*Plus. (Проверено на Oracle 8.0.6 и 8.1.7.)
SQL> select * from dual;
SQL> insert into dual values (‘Y’);
SQL> select * from dual;
SQL> delete from dual;
SQL> select * from dual;
SQL> delete from dual;
SQL> select * from dual;
Таким образом, SQL*Plus ограничивает все DML для DUAL по псевдостолбцу «. WHERE ROWNUM = 1. «.
Комментарий А.Бачина : Скажем спасибо Илье Гершанову за интересный эксперимент. Немного его продолжим и покажем, что именно механизм SQL*Plus ограничивает выборку одной строкой.
SVRMGR> insert into dual values (‘V’);
SVRMGR> insert into dual values (‘W’);
SVRMGR> insert into dual values (‘Y’);
SVRMGR> select * from dual;
И так далее. Но SQL*Plus верен себе
SQL> select * from dual;
SQL> select count(*) from dual;
SQL> select dummy from dual where dummy = ‘W’ ;
SQL> delete from dual where dummy in (‘Y’,’V’,’W’);
SQL> select * from dual;
Следовательно, в «недооткрытом» состоянии работает фиксированная (И.Гершанов неправильно называет ее фиктивной) таблица DUAL, вмонтирования в ядро Oracle.
После открытия базы начинает работать обычная (но специализированная) таблица словаря данных DUAL, про которую (скорее всего) только SQL*Plus «знает», что в ней только одно значение. Другие программные механизмы могут этого не знать, НО все пользуются однозначностью таблицы DUAL. Поэтому, если эта однозначность по каким-то причинам нарушена, то у многих приложений может «поехать крыша», со всеми вытекающими для пользователя результатами.
Поэтому АБД должен, как дворник (я не шучу), следить за чистотой вверенного ему пространства. Хорошо еще, что хоть не всякий scott/tiger сможет совершить такую диверсию.
What is the dual table in Oracle?
I’ve heard people referring to this table and was not sure what it was about.
14 Answers 14
It’s a sort of dummy table with a single record used for selecting when you’re not actually interested in the data, but instead want the results of some system function in a select statement:
e.g. select sysdate from dual;
It is a dummy table with one element in it. It is useful because Oracle doesn’t allow statements like
You can work around this restriction by writing
History
The DUAL table was created by Chuck Weiss of Oracle corporation to provide a table for joining in internal views:
I created the DUAL table as an underlying object in the Oracle Data Dictionary. It was never meant to be seen itself, but instead used inside a view that was expected to be queried. The idea was that you could do a JOIN to the DUAL table and create two rows in the result for every one row in your table. Then, by using GROUP BY, the resulting join could be summarized to show the amount of storage for the DATA extent and for the INDEX extent(s). The name, DUAL, seemed apt for the process of creating a pair of rows from just one. 1
It may not be obvious from the above, but the original DUAL table had two rows in it (hence its name). Nowadays it only has one row.
Optimization
DUAL was originally a table and the database engine would perform disk IO on the table when selecting from DUAL. This disk IO was usually logical IO (not involving physical disk access) as the disk blocks were usually already cached in memory. This resulted in a large amount of logical IO against the DUAL table.
Later versions of the Oracle database have been optimized and the database no longer performs physical or logical IO on the DUAL table even though the DUAL table still actually exists.
В каких случаях применяется DUAL и какой смысл этом?
Вопрос теоретический. Изучаю Oracle и встречаю такую конструкцию как DUAL. Понимаю, что это некоторая виртуальная таблица, но мне бы хотелось понять сам смысл этой штуки, зачем и когда применяется.
1 ответ 1
В синтаксически корректном запросе ОБЯЗАНА быть секция FROM.
Например, в запросе требуется набор чисел от 1 до 9. Задача решается простейшим CTE.
Аналогично будет, если в запросе нужен список кастомных литеральных значений. Например
Или если нужно выполнить какие-то вычисления с константами
Если обратиться к документации (Selecting from the DUAL Table), то:
DUAL is a table automatically created by Oracle Database along with the data dictionary. DUAL is in the schema of the user SYS but is accessible by the name DUAL to all users. It has one column, DUMMY, defined to be VARCHAR2(1), and contains one row with a value X. Selecting from the DUAL table is useful for computing a constant expression with the SELECT statement. Because DUAL has only one row, the constant is returned only once. Alternatively, you can select a constant, pseudocolumn, or expression from any table, but the value will be returned as many times as there are rows in the table. Refer to «About SQL Functions» for many examples of selecting a constant value from DUAL.
SQL DUAL table
What is DUAL table?
The DUAL is special one row, one column table present by default in all Oracle databases. The owner of DUAL is SYS (SYS owns the data dictionary, therefore DUAL is part of the data dictionary.) but DUAL can be accessed by every user. The table has a single VARCHAR2(1) column called DUMMY that has a value of ‘X’. MySQL allows DUAL to be specified as a table in queries that do not need data from any tables. In SQL Server DUAL table does not exist, but you could create one.
The DUAL table was created by Charles Weiss of Oracle corporation to provide a table for joining in internal views.
See the following commands :
The following command displays the structure of DUAL table :
The following command displays the content of the DUAL table :
The following command displays the number of rows of DUAL table :
The following command displays the string value from the DUAL table :
The following command displays the numeric value from the DUAL table :
The following command tries to delete all rows from the DUAL table :
The following command tries to remove all rows from the DUAL table :
Note : The DELETE command is used to remove rows from a table. After performing a DELETE operation you need to COMMIT or ROLLBACK the transaction to make the change permanent or to undo it. TRUNCATE removes all rows from a table. The operation cannot be rolled back.
The following command select two rows from dual :
You can also check the system date from the DUAL table using the following statement :
You can also check the arithmetic calculation from the DUAL table using the following statement :
Following code display the numbers 1..10 from DUAL :
In the following code, DUAL involves the use of decode with NULL.
DUAL table : Oracle vs MySQL
We have already learned that DUAL is a special one row one column table. For Oracle, it is useful because Oracle doesn’t allow statements like :
But the following command will execute (see the output of the previous example) :
In case of MySQL the following command will execute :
The following table shows the uses of dummy table in standard DBMS.
DBMS | Dummy-table concept |
---|---|
MSSQL | No dummy-table concept. |
MySQL | No dummy-table concept. |
Oracle | Dummy-table : DUAL. |
Informix | Since version 11.10, a dummy table has been included : sysmaster:sysdual |
PostgreSQL | No dummy-table concept. |
DB2 | Dummy-table : SYSIBM.SYSDUMMY1 |
Practice SQL Exercises
Want to improve the above article? Contribute your Notes/Comments/Examples through Disqus.