メインコンテンツにスキップ
eLearner.app
モジュール 12 · レッスン 1 / 4コース内の 45/57~15 min
モジュールのレッスン (1/4)

UDF とベース SQL

So far we've been sending queries from the Node.js server. But if a formula is used in dozens of different queries (e.g. computing the final price including VAT), why duplicate the math in JavaScript? SQL Functions (User Defined Functions - UDF) let us create "macros" inside the DB itself.

Here is how to create a mathematical SQL macro:

SQL
CREATE OR REPLACE FUNCTION calculate_tax(price NUMERIC)
RETURNS NUMERIC AS $$
  SELECT price * 1.22;
$$ LANGUAGE sql;

Once this command runs, the function lives forever in our database. It can be called from any query:

SQL
SELECT name, calculate_tax(unit_price) AS price_with_tax FROM products;

Dynamic creation

We can define as many variables as we want, specifying their types, and LANGUAGE sql will run the query and implicitly return the last statement placed between the dollar signs $$.

Try it yourself

運動#sql.m12.l1.e1
試行回数: 0読み込み中…

Create a simple callable function named 'get_full_name' that accepts two TEXT parameters ('first_name' TEXT, 'last_name' TEXT).\nIt must return a TEXT value.\nInside, do a trivial SELECT that concatenates the two arguments with a single space between them, and declare it as language sql.

エディターを読み込み中…
ヒントを表示

CREATE OR REPLACE FUNCTION get_full_name(first_name TEXT, last_name TEXT) RETURNS TEXT AS $$ SELECT first_name || ' ' || last_name; $$ LANGUAGE sql;

3 回の試行後に解決策が利用可能になります

運動#sql.m12.l1.e2
試行回数: 0読み込み中…

In more advanced UDFs we can embed entire queries. Create a function 'get_customer_count()' that accepts no parameters and RETURNS an INTEGER.\nInside, run a trivial 'SELECT COUNT(id) FROM customers'.\nDeclare it as pure sql language.

エディターを読み込み中…
ヒントを表示

Watch out: COUNT returns a bigint, cast it to INTEGER to match the return type! CREATE OR REPLACE FUNCTION get_customer_count() RETURNS INTEGER AS $$ SELECT CAST(COUNT(id) AS INTEGER) FROM customers; $$ LANGUAGE sql;

3 回の試行後に解決策が利用可能になります