UPDATE with CASE and IN – Oracle

You said that budgetpost is alphanumeric. That means it is looking for comparisons against strings. You should try enclosing your parameters in single quotes (and you are missing the final THEN in the Case expression). UPDATE tab1 SET budgpost_gr1= CASE WHEN (budgpost in (‘1001′,’1012′,’50055’)) THEN ‘BP_GR_A’ WHEN (budgpost in (‘5′,’10’,’98’,’0′)) THEN ‘BP_GR_B’ WHEN (budgpost in … Read more

Can I optimize a SELECT DISTINCT x FROM hugeTable query by creating an index on column x?

This is likely not a problem of indexing, but one of data design. Normalization, to be precise. The fact that you need to query distinct values of a field, and even willing to add an index, is a strong indicator that the field should be normalized into a separate table with a (small) join key. … Read more

How to generate a random, unique, alphanumeric ID of length N in Postgres 9.6+?

Figured this out, here’s a function that does it: CREATE OR REPLACE FUNCTION generate_uid(size INT) RETURNS TEXT AS $$ DECLARE characters TEXT := ‘ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789’; bytes BYTEA := gen_random_bytes(size); l INT := length(characters); i INT := 0; output TEXT := ”; BEGIN WHILE i < size LOOP output := output || substr(characters, get_byte(bytes, i) % l … Read more

Using a join in a merge statement

The query you have will give the error Msg 8156, Level 16, State 1, Line 59 The column ‘AnotherKey’ was specified multiple times for ‘tmpTable’. That is because you are using * in the using clause and AnotherKey is part of both table2 and table3. Specify the columns you need. Also there is no use … Read more

Is possible to reuse subqueries?

You can take the aggregations out into a CTE (common table expression): with minima as (select t.id, t.type, min(value) min_value from table2 t where t.type in (1,2,3,4) group by t.id, t.type) select a.id, a.name, (select min_value from minima where minima.id = subquery.id and minima.type = 1) as column1, (select min_value from minima where minima.id = … Read more

Count the Null columns in a row in SQL

This method assigns a 1 or 0 for null columns, and adds them all together. Hopefully you don’t have too many nullable columns to add up here… SELECT ((CASE WHEN col1 IS NULL THEN 1 ELSE 0 END) + (CASE WHEN col2 IS NULL THEN 1 ELSE 0 END) + (CASE WHEN col3 IS NULL … Read more

Why are the queries in SQL mostly written in Capital Letters?

It was meant for readability. Before, SQL was written in plain-text editors (no syntax/code highlighting) and keywords needed to be differentiated for better readability and maintenance. SELECT column_name FROM table_name WHERE column_name = column_value vs select column_name from table_name where column_name = column_value See the difference? The first word in each line told the reader … Read more