Unlike MS SQL Server, PostgreSQL doesn't declare variables in the same manner. Instead, the WITH
clause provides a mechanism for defining and assigning values to variables within a query.
The syntax for declaring a variable in a PostgreSQL query uses the WITH
clause:
<code class="language-sql">WITH <variable_name> AS (<value>)</code>
For instance, to create an integer variable myvar
with a value of 5, the syntax is:
<code class="language-sql">WITH myvar AS (SELECT 5)</code>
Note that you must assign a value using a SELECT
statement within the AS
clause.
After declaring a variable, you can use it in your query by referencing its name. For example, this query retrieves all rows from the somewhere
table where the something
column matches the value of myvar
:
<code class="language-sql">WITH myvar AS (SELECT 5) SELECT * FROM somewhere WHERE something = (SELECT * FROM myvar);</code>
Remember, the WITH
clause must precede the SELECT
statement. The variable's value is accessed using a subquery referencing the variable name.
The above is the detailed content of How Do I Declare and Use Variables in PostgreSQL Queries?. For more information, please follow other related articles on the PHP Chinese website!