home..

SQL stuff to remember

sql

count(*) vs count(id)


where vs having


Tuple Distinct Counting in PostgreSQL

when lower(business_name) like '%cafe%' or lower(business_name) like '%café%' 
when lower(business_name) like any(array['%cafe%','%café%'])
when lower(business_name) similar to '%cafe|café%'

Using CASE WHEN Inside COUNT() and SUM()

Using CASE WHEN Inside COUNT()

Purpose: Count rows based on specific conditions.

Syntax:

COUNT(CASE WHEN condition THEN 1 END)

Example:

SELECT 
    COUNT(CASE WHEN status = 'completed' THEN 1 END) AS completed_sales_count
FROM 
    sales;

Using CASE WHEN Inside SUM()

Purpose: Sum values conditionally based on specific criteria.

Syntax:

SUM(CASE WHEN condition THEN value_column ELSE 0 END)

Example:

SELECT 
    SUM(CASE WHEN status = 'completed' THEN quantity ELSE 0 END) AS total_completed_quantity
FROM 
    sales;

Using CASE WHEN in Other Functions

You can use CASE WHEN with various aggregate and non-aggregate functions in SQL, including:

  1. AVG(): Calculate the average based on conditions.
    AVG(CASE WHEN condition THEN value_column END)
    
  2. MAX(): Get the maximum value based on conditions.
    MAX(CASE WHEN condition THEN value_column END)
    
  3. MIN(): Get the minimum value based on conditions.
    MIN(CASE WHEN condition THEN value_column END)
    
  4. STRING_AGG(): Concatenate values conditionally (in databases that support it).
    STRING_AGG(CASE WHEN condition THEN value_column END, ', ')
    

Regular Expression description ~* '\y(plum|cherry|rose|hazelnut)\y'

This is the regular expression pattern that is being matched against the description. Let’s break down this pattern:

Example Matches


THIS

© 2025 Jithendra Yenugula