SET

SET in SQL is a statement used to modify the values of a variable, which is already defined in the database, or to modify the global system variables. This can be used in the preparation of the environment or to adjust the behavior of the database system.

Example

SET @name = 'John Doe';
SELECT @name;

Output

+-----------+
| @name |
+-----------+
| John Doe |
+-----------+

Explanation

The SET command in the SQL statement is used to assign a value to the variable @name. The SELECT command is then executed to display the value of the @name variable, which in this case is ‘John Doe’.

Example

SET timezone TO 'America/New_York';
SHOW timezone;

Output

TimeZone
---------------------------
America/New_York

Explanation

The SET statement is used to change the current setting of a run-time configuration option for the duration of the current session. The example above is changing the timezone to ‘America/New_York’. The SHOW command is displaying the current set timezone.

Example

DECLARE @TestVariable INT;
SET @TestVariable = 5;
SELECT @TestVariable;

Output

5

Explanation

The variable @TestVariable is declared to be of type INT. Subsequently, the SET statement assigns the value 5 to @TestVariable. The SELECT statement then retrieves the value, outputting 5.

Example

SET SERVEROUTPUT ON
DECLARE
test_variable NUMBER(2);
BEGIN
test_variable := 15;
dbms_output.put_line('The value of test_variable is ' || test_variable);
END;
/

Output

The value of test_variable is 15

Explanation

In the example code, the SERVEROUTPUT feature of SQL*PLUS is enabled with the SET SERVEROUTPUT ON command. This allows the DBMS_OUTPUT.PUT_LINE to function. Within a PL/SQL block, a variable named test_variable of NUMBER type is declared and set to 15. The dbms_output.put_line command prints the appended string and the value of test_variable which gives us our output.

For in-depth explanations and examples SQL keywords where you write your SQL, install our extension.