SQL Examples


Examples:


Sample 1: These examples show some of the database work with Nation Water Prediction Service (NWPS) application and checking CATFIM data.

        
        -- ListGauges query from nwps_v2.4.0_rc
        SELECT ahps_gauge.lid,
               st_y(ahps_gauge.geom),
               st_x(ahps_gauge.geom),
               coalesce(hml_site_status.obs_primary_value, -9999.000000),
               coalesce(hml_site_status.obs_primary_unit, 'unknown'),
               coalesce(hml_site_status.obs_secondary_value, -999.000000),
               coalesce(hml_site_status.obs_secondary_unit, 'unknown'),
               coalesce(hml_site_status.obs_flood_category, 'obs_not_current'),
               hml_site_status.obs_valid_time,
               coalesce(hml_site_status.fcst_primary_value, -9999.000000),
               coalesce(hml_site_status.fcst_primary_unit, 'unknown'),
               coalesce(hml_site_status.fcst_secondary_value, -999.000000),
               coalesce(hml_site_status.fcst_secondary_unit, 'unknown'),
               coalesce(hml_site_status.fcst_flood_category, 'fcst_not_current'),
               hml_site_status.fcst_valid_time
        FROM ahps_gauge
        LEFT JOIN hml_site_status ON ahps_gauge.lid = hml_site_status.lid
        JOIN cms_regional_config ON cms_regional_config.id = hml_site_status.lid
        ORDER BY ahps_gauge.lid
        -- (11170 rows)

        -- ListGauges query in storage/postgres/gauge.go from 134029-Create-CATFIM-Location-Page
        SELECT ahps_gauge.lid,
               st_y(ahps_gauge.geom),
               st_x(ahps_gauge.geom),
               coalesce(hml_site_status.obs_primary_value, -9999.000000),
               coalesce(hml_site_status.obs_primary_unit, 'unknown'),
               coalesce(hml_site_status.obs_secondary_value, -999.000000),
               coalesce(hml_site_status.obs_secondary_unit, 'unknown'),
               coalesce(hml_site_status.obs_flood_category, 'obs_not_current'),
               coalesce(hml_site_status.obs_valid_time, '0001-01-01'),
               coalesce(hml_site_status.fcst_primary_value, -9999.000000),
               coalesce(hml_site_status.fcst_primary_unit, 'unknown'),
               coalesce(hml_site_status.fcst_secondary_value, -999.000000),
               coalesce(hml_site_status.fcst_secondary_unit, 'unknown'),
               coalesce(hml_site_status.fcst_flood_category, 'fcst_not_current'),
               coalesce(hml_site_status.fcst_valid_time, '0001-01-01'),
               coalesce(cms_regional_config.config->'location'->>'value', ''),
               coalesce(cms_regional_config.config->'name'->>'value', ''),
               coalesce(cms_regional_config.config->'wfo'->>'value', ''),
               coalesce(cms_regional_config.config->'state'->>'value', ''),
               coalesce(map_rfc.rfc_city, '')
        FROM ahps_gauge
        LEFT JOIN hml_site_status ON ahps_gauge.lid = hml_site_status.lid
        LEFT JOIN cms_regional_config ON cms_regional_config.id = hml_site_status.lid
        JOIN catfim ON upper(catfim.lid) = upper(cms_regional_config.id)
        JOIN map_rfc ON cms_regional_config.config->'rfc'->>'value' = map_rfc.basin_id
        ORDER BY ahps_gauge.lid
        -- (1795 rows)

        -- toSQL, _, _ := q.ToSql()
        -- db.Logger.Debugf("---------- query:  %s", toSQL)


        -- catfim query
        SELECT ahps_gauge.lid,
               st_y(ahps_gauge.geom),
               st_x(ahps_gauge.geom),
               coalesce(hml_site_status.obs_primary_value, -9999.000000),
               coalesce(hml_site_status.obs_primary_unit, 'unknown'),
               coalesce(hml_site_status.obs_secondary_value, -999.000000),
               coalesce(hml_site_status.obs_secondary_unit, 'unknown'),
               coalesce(hml_site_status.obs_flood_category, 'obs_not_current'),
               coalesce(hml_site_status.obs_valid_time, '0001-01-01'),
               coalesce(hml_site_status.fcst_primary_value, -9999.000000),
               coalesce(hml_site_status.fcst_primary_unit, 'unknown'),
               coalesce(hml_site_status.fcst_secondary_value, -999.000000),
               coalesce(hml_site_status.fcst_secondary_unit, 'unknown'),
               coalesce(hml_site_status.fcst_flood_category, 'fcst_not_current'),
               coalesce(hml_site_status.fcst_valid_time, '0001-01-01'),
               coalesce(cms_regional_config.config->'location'->>'value', ''),
               coalesce(cms_regional_config.config->'name'->>'value', ''),
               coalesce(cms_regional_config.config->'wfo'->>'value', ''),
               coalesce(cms_regional_config.config->'state'->>'value', ''),
               coalesce(map_rfc.rfc_city, '')
        FROM ahps_gauge
        LEFT JOIN hml_site_status ON ahps_gauge.lid = hml_site_status.lid
        LEFT JOIN cms_regional_config ON cms_regional_config.id = hml_site_status.lid
        JOIN catfim ON upper(catfim.lid) = upper(cms_regional_config.id)
        JOIN map_rfc ON cms_regional_config.config->'rfc'->>'value' = map_rfc.basin_id
        WHERE catfim.mapped = 'yes'
          AND catfim.cms_available = 'true'
        ORDER BY ahps_gauge.lid
        
    

Sample 2: I used these similar table CREATE queries for the Nation Water Prediction Service (NWPS) QPE partitioning functionality. I also wrote a Postgresql custom function as well.

        
        SET enable_partition_pruning = on;

        ALTER TABLE o_2_qperasters ADD COLUMN IF NOT EXISTS fkey TEXT ;
        ALTER TABLE o_3_qperasters ADD COLUMN IF NOT EXISTS fkey TEXT ;
        ALTER TABLE qperasters ADD COLUMN IF NOT EXISTS fkey TEXT ;


        DROP TABLE IF EXISTS qpe.o_2_qperasters_processed ;
        CREATE TABLE qpe.o_2_qperasters_processed (
            rid integer NOT NULL,
            rast public.raster,
            filename text,
            md5 text,
            fkey text,
            CONSTRAINT enforce_overview_rast CHECK (public._overview_constraint(rast, 2, 'qpe'::name, 'qperasters_processed'::name, 'rast'::name))
        ) PARTITION BY LIST (fkey) ;

        DROP TABLE IF EXISTS qpe.o_3_qperasters_processed ;
        CREATE TABLE qpe.o_3_qperasters_processed (
            rid integer NOT NULL,
            rast public.raster,
            filename text,
            md5 text,
            fkey text,
            CONSTRAINT enforce_overview_rast CHECK (public._overview_constraint(rast, 3, 'qpe'::name, 'qperasters_processed'::name, 'rast'::name))
        ) PARTITION BY LIST (fkey) ;

        DROP TABLE IF EXISTS qpe.qperasters_processed ;
        CREATE TABLE qpe.qperasters_processed (
            rid integer NOT NULL,
            rast public.raster,
            filename text,
            md5 text,
            native_path text,
            fkey text
        ) PARTITION BY LIST (fkey) ;
        
        ...

        --
        -- create the partition tables needed for existing data
        --

        -- create the sub partitions for all distinct fkey values from schema owp_water_website and tables o_2_qperasters, o_3_qperasters, or qperasters.
        -- DROP FUNCTION create_partition(tablename text);
        CREATE OR REPLACE FUNCTION create_partition(tablename text)
        RETURNS void AS $$
          DECLARE temprow RECORD;
        BEGIN
              -- date creation
              FOR temprow IN
                 EXECUTE FORMAT('SELECT DISTINCT UNNEST(REGEXP_MATCHES(filename, ''[0-9]{6}'')) AS FKey FROM owp_water_website.%s', tablename)
              LOOP
                IF NOT EXISTS (
                  SELECT 1 FROM information_schema.tables WHERE table_schema = 'qpe' and table_name = FORMAT('%s_%s_%s', substring(tablename, 1, 3), substring(temprow.FKey, 1, 4), substring(temprow.Fkey, 5, 7)) 
                ) THEN
                  EXECUTE FORMAT('CREATE TABLE qpe.%s_%s_%s PARTITION OF qpe.%s FOR VALUES IN (''%s'');', substring(tablename, 1, 3), substring(temprow.Fkey, 1, 4), substring(temprow.Fkey, 5, 7), tablename, temprow.Fkey) ;
                END IF; 
              END LOOP;

              -- hour creation
              FOR temprow IN
                 EXECUTE FORMAT('SELECT DISTINCT UNNEST(REGEXP_MATCHES(filename, ''1hour|last12hours|last6hours|last2hours|last3hours|last24hours|since12z'')) AS FKey FROM owp_water_website.%s', tablename)
              LOOP
                IF NOT EXISTS (
                  SELECT 1 FROM information_schema.tables WHERE table_schema = 'qpe' and table_name = FORMAT('%s_%s', substring(tablename, 0, 3), temprow.Fkey)
                ) THEN
                  EXECUTE FORMAT('CREATE TABLE qpe.%s_%s PARTITION OF qpe.%s FOR VALUES IN (''%s'');', substring(tablename, 1, 3), temprow.Fkey, tablename, temprow.Fkey) ;
                END IF; 
              END LOOP;

        END;
        $$ LANGUAGE plpgsql;

        ...

        --
        -- Get a list of all user defined custom functions for owp_water_website
        --
        -- SELECT n.nspname, p.proname FROM   pg_catalog.pg_proc p JOIN   pg_catalog.pg_namespace n ON n.oid = p.pronamespace WHERE  n.nspname = 'owp_water_website';
        --

        --
        -- @TODO: RUN ALL FROM HERE TO END BY HAND
        --

        select create_partition('o_2_qperasters');
        select create_partition('o_3_qperasters');
        select create_partition('qperasters');
        ...
        
    

Sample 3: This was an SQL update script I used to update some data rows within a Postgresql system. I like to dump out to a file the data first that I am going to update and document it if it is small.

        
          ...
          select key, config from map_layers where config ilike '%USGS_Stream_Gauges%';

          --
          -- on nwc2
          --
          nwc2=# select key, config from map_layers;
          --               key               |                                                                                 config
          -- 
          -- --------------------------------+---------------------------------------------------------------------------------------------------------------------------------
          -- ---------------------------------------
          --  AHPS_Inundation                | {"src":"http://arc.orionnetworksolutions.com/arcgis/rest/services/Reference_layers/AHPS_Inundation/MapServer"}
          --  regional_snow_obs_stations     | {"filter":"NULL","database":"NULL","host":"NULL","table":"snow_obs_stations","field_mapping":{"key":"key","label":"name","lat":"
          -- NULL","lon":"NULL"},"filter":"region"}
          --  snow_obs_stations              | {"database":"NULL","host":"NULL","table":"snow_obs_stations","field_mapping":{"key":"key","label":"name","lat":"NULL","lon":"NUL
          -- L"}}
          --  regional_highlight             | {}
          --  national_snow_analysis_regions | {"src":"national_snow_analysis_boundaries.kmz"}
          --  usgs_stream_gauges             | {"src":"https://mapservice.nohrsc.noaa.gov/arcgis/rest/services/observations/USGS_Stream_Gauges/MapServer"}
          --  nws_warnings_watches           | {"src":"https://idpgis.ncep.noaa.gov/arcgis/rest/services/NWS_Forecasts_Guidance_Warnings/watch_warn_adv/MapServer"}
          --  nwm_reservoirs                 | {"src":"https://mapservice.nohrsc.noaa.gov/arcgis/rest/services/national_water_model/NWM_Lakes_and_Reservoirs/MapServer"}
          --  nwm_channel_rt_analysis_assim  | {"src":"https://arc.orionnetworksolutions.com/arcgis/rest/services/national_water_model/NWM_Stream_Analysis/MapServer"}
          --  state_counties                 | {"src":"https://mapservice.nohrsc.noaa.gov/arcgis/rest/services/boundaries/US_Census_state_county/MapServer"}
          --  nwm_land_analysis_assim        | {"src":"https://arc.orionnetworksolutions.com/arcgis/rest/services/national_water_model/NWM_Land_Analysis/MapServer"}
          --  snow_analysis                  | {"src":"https://mapservices.weather.noaa.gov/raster/rest/services/snow/NOHRSC_Snow_Analysis/MapServer"}
          -- (12 rows)

          -- this updates
          UPDATE map_layers SET config = replace(config, 'mapservices.weather.noaa.gov', 'arc-04.orionnetworksolutions.com:6443') WHERE key = 'usgs_stream_gauges';

          -- another query
          UPDATE map_layers SET config = replace(config, 'mapservice.nohrsc.noaa.gov', 'arc.orionnetworksolutions.com') WHERE config LIKE '%http%' AND key = 'usgs_stream_gauges';