DO
DO executes an anonymous code block, or a series of operations, that provide procedural language capabilities but do not return a value. It’s primarily used when an operation is to be performed multiple times in sequence. Unlike SQL commands, DO blocks cannot take arguments nor return values.
Example
DO$do$BEGIN IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'test') THEN RAISE NOTICE 'Table exists.'; ELSE RAISE NOTICE 'Table does not exist.'; END IF;END$do$;
Output
NOTICE: Table does not exist.
Explanation
The DO
statement in PostgreSQL executes an anonymous code block, which does not need to be stored in the database. The example statement checks if a table named test
exists in the database. If it exists, it outputs the message ‘Table exists.’, otherwise it outputs ‘Table does not exist.’.
Example
DO SELECT CURRENT_DATE;
Output
No result set returned.
Explanation
The DO
statement in MySQL is used to execute an expression or command but does not provide any output. In the provided example, although the CURRENT_DATE
function is being called, no result is returned due to the nature of the DO
statement. In contrast, if we used SELECT CURRENT_DATE;
without the DO
, MySQL would return the current date.
It should be noted that in practical applications, the DO
statement is typically used with expressions that have side-effects (e.g., storing values to variables), as it does not provide any results.