Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA1:256) (Exim 4.89) (envelope-from ) id 1hhLv0-0004NK-Sf for pgsql-general@arkaria.postgresql.org; Sat, 29 Jun 2019 22:34:03 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.89) (envelope-from ) id 1hhLuy-0008VI-2T for pgsql-general@arkaria.postgresql.org; Sat, 29 Jun 2019 22:34:00 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA1:256) (Exim 4.89) (envelope-from ) id 1hhLuw-0008MA-D3 for pgsql-general@lists.postgresql.org; Sat, 29 Jun 2019 22:33:59 +0000 Received: from out3-smtp.messagingengine.com ([66.111.4.27]) by magus.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA1:256) (Exim 4.89) (envelope-from ) id 1hhLun-0001Xo-BM for pgsql-general@postgresql.org; Sat, 29 Jun 2019 22:33:57 +0000 Received: from compute6.internal (compute6.nyi.internal [10.202.2.46]) by mailout.nyi.internal (Postfix) with ESMTP id 8276521C24; Sat, 29 Jun 2019 18:33:47 -0400 (EDT) Received: from mailfrontend2 ([10.202.2.163]) by compute6.internal (MEProxy); Sat, 29 Jun 2019 18:33:47 -0400 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=aklaver.com; h= subject:to:cc:references:from:message-id:date:mime-version :in-reply-to:content-type:content-transfer-encoding; s=fm3; bh=h CTEKbuiA4P4EAQCFqDFd9/wZeWlAsVF8FfeU3vnifM=; b=DVYcRrFcnZQCG/7g9 PwlyyOZejLNFLsUVoQvJcpDnWfUe+B40VPviJoKqOyo/dR0ezm3gRJfAqjH0Y7XK bpjmGO6HbGWGLLq2uuuGfnDXm8ELESuD6WUMTbm7P9a7g1Sq+zmRUBtuKXb5ZBAr AVTlg7r+fvXVPDoNseIzT7ax4vXCI/0cxVHAnUKp8yqsdWRkeXo8xE/mEBoP9BlI QffVg2TCdv468feXT3uP7VSoodVbUu+HSwWXcSux13wxucyQAIHBJSS/KO4V2rIK gKqLUK1AIFW9qfSXpDRGUdiP09RGrAGYhPevyOvP3P5FnOWbkkesNq/Th1FhSDCw Jgxzg== DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d= messagingengine.com; h=cc:content-transfer-encoding:content-type :date:from:in-reply-to:message-id:mime-version:references :subject:to:x-me-proxy:x-me-proxy:x-me-sender:x-me-sender :x-sasl-enc; s=fm3; bh=hCTEKbuiA4P4EAQCFqDFd9/wZeWlAsVF8FfeU3vni fM=; b=PVW65/MF1BKnetK8PsTdiqlvuY10ZBEH2B2yPMBjdDoBAS0/Gd41xNjU1 3fKG/nE1HPc0yXp4DMaPU+EaN2jPjohZKbtYR9XKdUysRQyc8D9pEKM9X5IZHWWE 1rrCy1ohHn0gdPhV/ohHduVKIEKI+WdqEa9uEKsUPEDTjmo+5A/Rf3NnDcNrm/Bv Myq5gGsZYtmOO4ZsCvWzfpAtuQRNoFWnriS3gGTGf67Y3BTfFIDBwilrQ1evHFmf AttcwZ/ZS4pyYql81VEKLkK3j1LfSPq+fqIrySZVa3TxqSXG/PVO83FNQ+FL2Aw7 HEpm3jo54nq0iWr2w/ZlRGI64Ye3w== X-ME-Sender: X-ME-Proxy-Cause: gggruggvucftvghtrhhoucdtuddrgeduvddrvdefgddutdcutefuodetggdotefrodftvf curfhrohhfihhlvgemucfhrghsthforghilhdpqfgfvfdpuffrtefokffrpgfnqfghnecu uegrihhlohhuthemuceftddtnecunecujfgurhepuffvfhfhkffffgggjggtgfesthekre dttdefjeenucfhrhhomheptegurhhirghnucfmlhgrvhgvrhcuoegrughrihgrnhdrkhhl rghvvghrsegrkhhlrghvvghrrdgtohhmqeenucffohhmrghinhepuggsfhhiuggulhgvrd hukhenucfkphepjedurddvuddvrdduhedtrddvtddvnecurfgrrhgrmhepmhgrihhlfhhr ohhmpegrughrihgrnhdrkhhlrghvvghrsegrkhhlrghvvghrrdgtohhmnecuvehluhhsth gvrhfuihiivgeptd X-ME-Proxy: Received: from [192.168.1.4] (unknown [71.212.150.202]) by mail.messagingengine.com (Postfix) with ESMTPA id 7703C380076; Sat, 29 Jun 2019 18:33:46 -0400 (EDT) Subject: Re: How to get non-existant values as NULL or 0? To: =?UTF-8?B?UMOzbCBVYSBMYW/DrW5lY2jDoWlu?= Cc: pgsql-general References: <04592c40-829d-a31e-790a-96afbc108c0a@lucee.org> <1476e550-ac2e-949a-5f4d-b29d0ad1203e@lucee.org> From: Adrian Klaver Message-ID: <1775a838-4e6e-a0b7-9e5e-9849903f6ec4@aklaver.com> Date: Sat, 29 Jun 2019 15:33:45 -0700 User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Thunderbird/60.7.2 MIME-Version: 1.0 In-Reply-To: Content-Type: text/plain; charset=utf-8; format=flowed Content-Language: en-US Content-Transfer-Encoding: 8bit List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk On 6/29/19 9:20 AM, Pól Ua Laoínecháin wrote: > I'm in a bit of a quandary. I'm trying to figure out how to have > non-existent values appear as NULL (or using COALESCE, as 0). > > I have several tables (DDL and DML shown at the bottom of this post - > and there is a fiddle available here: > https://dbfiddle.uk/?rdbms=postgres_11&fiddle=171d207d25981e0db15791e1684de802 As a start added to above fiddle: WITH dist AS (SELECT distinct on(job_id, loc_key) job_id, loc_key FROM the_location, job ) SELECT loc_key, job_id, COALESCE(lj_percent, 0) AS percent FROM dist LEFT JOIN location_job AS lj ON dist.job_id = lj.lj_job AND dist.loc_key = lj.lj_loc ORDER BY loc_key, job_id; loc_key | job_id | percent ---------+--------+--------- 1 | 1 | 0 1 | 2 | 10 1 | 3 | 10 1 | 4 | 10 1 | 5 | 10 1 | 6 | 50 2 | 1 | 30 2 | 2 | 30 2 | 3 | 10 2 | 4 | 10 2 | 5 | 10 2 | 6 | 10 > > The crux of the problem is that there is a joining table location_job > > CREATE TABLE location_job > ( > lj_loc INTEGER NOT NULL, > lj_job INTEGER NOT NULL, > lj_percent INTEGER DEFAULT 0 NOT NULL, > &c... - see fiddle or below > ); > > with entries as follows: > > INSERT INTO location_job > VALUES > (1, 2, 10), (1, 3, 10), (1, 4, 10), (1, 5, 10), (1, 6, 50), -- missing > value (1, 1, 10) > (2, 1, 30), (2, 2, 30), (2, 3, 10), (2, 4, 10), (2, 5, 10), (2, 6, 10); > > Now the lj_job from the missing value corresponds to a job_type of Unknown. > > So, performing this query: > > SELECT > tl.loc_key, tl.loc_coords, > lj.lj_loc, lj.lj_job, lj.lj_percent, > j.job_id, j.job_type > FROM the_location tl > JOIN location_job lj ON tl.loc_key = lj.lj_loc > JOIN job j ON lj.lj_job = j.job_id > ORDER BY tl.loc_key, j.job_id; > > Gives me the results: > > loc_keyloc_coordslj_loclj_joblj_percentjob_idjob_type > 1coord_112102Unemployed > 1coord_113103Blue collar > 1coord_114104White collar > > Notice that (as expected) there is no result for job_type Unknown for > location 1 - it's the missing record - all fine and dandy! > > However, what I want to do is to include a record in my resultset that > has NULL (or 0) for job_type Unknown. > > You will be able to see from the fiddle that I have tried varying the > order of the joins and the join types (LEFT OUTER, RIGHT OUTER, FULL > OUTER), all to no avail. > > My question boils down to how do I get the first line of my resultset to be > > 1 coord_1 1 1 0 1 Unknown -- the 0 corresponds to the percent of > Unknowns in the location coord_1. > > I would be grateful for an explanation of any answer as I'm trying to > learn SQL and this really has me stumped. > > Should you require any further information, please don't hesitate to > let me know, > > TIA, > > Pól... > > > =========== DDL and DML =============== > > CREATE TABLE crime > ( > cr_rating VARCHAR (25) PRIMARY KEY > ); > > INSERT INTO crime VALUES ('Low'), ('Medium'), ('High'); > > CREATE TABLE weather > ( > weather_type VARCHAR (50) PRIMARY KEY > ); > > INSERT INTO weather VALUES ('Scorching'), ('Sunny'), ('Mild'), > ('Overcast'), ('Drizzle'), ('Rainy'), ('Stormy'), ('Hurricane'); > > CREATE TABLE job (job_id SERIAL PRIMARY KEY, job_type VARCHAR (30) NOT NULL); > > INSERT INTO job (job_type) VALUES ('Unknown'), ('Unemployed'), ('Blue > collar'), ('White collar'), ('Manager'), ('Self-employed'); > > CREATE TABLE the_location > ( > > loc_key SERIAL PRIMARY KEY, > loc_coords VARCHAR (50) NOT NULL, -- not sure how you store these in > your system > loc_status INTEGER CHECK (loc_status IN (0,1)), > loc_rating INTEGER CHECK (loc_rating BETWEEN 1 AND 10), > loc_crime VARCHAR (25) NOT NULL, > -- could use a CHECK CONSTRAINT, but use a lookup table instead > -- note also that the types should match exactly > loc_weather VARCHAR (50) NOT NULL, > -- location_rating_tourism, -- same lookup table idea here (Good, > Medium, Poor, Death-zone) > -- location_rating_income, -- list of social classes table > -- location_rating_jobs > CONSTRAINT ct_loc_crime FOREIGN KEY (loc_crime) REFERENCES crime (cr_rating), > CONSTRAINT ct_loc_weather FOREIGN KEY (loc_weather) REFERENCES > weather (weather_type) > ); > > INSERT INTO the_location > (loc_coords, loc_status, loc_rating, loc_crime, loc_weather) > VALUES > ('coord_1', 0, 7, 'Medium', 'Rainy'), > ('coord_2', 1, 7, 'High', 'Mild'); > > CREATE TABLE location_job > ( > lj_loc INTEGER NOT NULL, > lj_job INTEGER NOT NULL, > lj_percent INTEGER DEFAULT 0 NOT NULL, > PRIMARY KEY (lj_loc, lj_job), > CONSTRAINT ct_lj_loc FOREIGN KEY (lj_loc) REFERENCES the_location (loc_key), > CONSTRAINT ct_lj_job FOREIGN KEY (lj_job) REFERENCES job(job_id) > ); > > INSERT INTO location_job > VALUES > (1, 2, 10), (1, 3, 10), (1, 4, 10), (1, 5, 10), (1, 6, 50), -- missing > value (1, 1, 10) > (2, 1, 30), (2, 2, 30), (2, 3, 10), (2, 4, 10), (2, 5, 10), (2, 6, 10); > > -- and my first query - see fiddle for others > > SELECT > tl.loc_key, tl.loc_coords, > lj.lj_loc, lj.lj_job, lj.lj_percent, > j.job_id, j.job_type > FROM the_location tl > JOIN location_job lj ON tl.loc_key = lj.lj_loc > JOIN job j ON lj.lj_job = j.job_id > ORDER BY tl.loc_key, j.job_id; > > > -- Adrian Klaver adrian.klaver@aklaver.com