To display a record having multiple values in a table in postgres - postgresql

Desired output-
Emp_name|Hobbies|age|DOB
______________________________
LOPEZ |Football , Swimming , Fishing |19| 1999-05-11
Here in the question, the Hobbies column is having multiple records with comma separate, BUT I want in a SINGLE line (Vertically).
All the records for hobbies should be a single record, like multiple values in single record.
And, last display in one row.
Please help me creating a table and way to insert and fetch the record in postgres DB.

So we want to reformat your 'hobbies' string to an array. You can use the ARRAY_AGG() function:
CREATE TABLE new_hobbies AS
SELECT
name
, age
, DOB
, ARRAY_AGG(hobbies) AS hobbies
FROM table
GROUP BY
name
, age
, dob
But yeah I agree with sticky bit's answer that normalisation of this single table would be a good idea. As well as not having an age value - to avoid issues with updates.

Related

How to save a query result into a column using postgresql

This may be a simple fix but Im somehow drawing a blank. I have this code below, and I want the results that I got from it to be added into their own column in an existing table. How would i go about doing this.
Select full_name, SUM(total) as sum_sales
FROM loyalty
where invoiceyear = 2013
GROUP BY full_name
order by sum_sales DESC;
This leaves me with one column with the name of employee and the second with their sales from that year.
How can i just take these results and add them into a column in addition to the table
Is it as simple as...
Alter table loyalty
Add column "2013 sales"
and then add in some sort of condition?
Any help would be greatly appreciated!
If i got your question right, you need to first alter the table allowing the new field to be null (you can change it later on) then you could use an insert clause to store the value permanently.

Timestamp comparison query not actually filtering results

I'm having a really weird issue running a timestamp comparison query in my postgresql database.
I have a table called user (I know it's a terrible name) and we have a column named createdAt that's the type of timestamp with timezone. I should be able to run a query comparing against this column no problem. Yet, the WHERE in this clause (and the AND) don't seem to have any effect. I get back every single user from this table including ones with a null value in the createdAt column. I'm perplexed.
select * from "user"
where 'createdAt' >= '2017-08-01 23:25:53+00'
and 'createdAt' is not null
order by id desc;
EDIT:
relevant table structure and sample data
*** table columns ***
id serial primary key
createdAt timestamp with time zone
first_name text
last_name text
** sample data ***
id first_name last_name createdAt
1 john smith 2018-09-21 02:53:42+00
2 james smith 2018-09-19 00:27:14+00
EDIT: SOLVED
This was a weird issue but I wasn't getting any feedback from my where clause. The problem is the original devs named the columns camel cased which makes it necessary that any future queries referencing this column use the double quotes. Ended up having to say "user"."createdAt". That was a syntax issue on my part since I only ever name my columns snake case.
Are PostgreSQL column names case-sensitive?

SQL statement that returns exactly one row with columns

I'm having trouble creating a query for the following task: i want to return exactly one row with columns: region_id, region_name, province_name, province_code, country_name, country_code for any given regionid. The database has 3 tables "countrylist" , "provinces" and "regionlist"
the table countrylist has the following columns : countryid, language code, countryname, countrycode and continentid
provinces : country_code, country_name, province_code, province_name
regionlist: regionid, regiontype.
So I tried writing a query for joining the table but I'm sure if I'm doing it correct.
exactly one row with columns: region_id, region_name, province_name, province_code, country_name, country_code for any given regionid.
I am not 100% aware of the differences between Postgres and MySQL - but guess you get the idea at the very least.
One way to do it, to get your id with WHERE regionlist.regionid = and join the other tables. From either the regionlist you can use the LIMIT (reference) to get a limited amount of rows.
Apparently neither provinces nor country have a common column with regionlist, so I can not tell where the link between those are. However, once you have 1 row of the region list you should have no troubles joining them with the others (if the links are trivial).

Postgresql get some last rows from table

I have PostgreSQL table:
Username1 SomeBytes1
Username2 SomeBytes1
Username1 SomeBytes1
Username1 SomeBytes1
I need to get some rows from with name Username1 but from the end of the table. For example i need last to rows with Username1
select from my_table where user = Username1 LIMIT 2
Gives me first 2 rows, but i need last two.
How can i select it?
Thank you.
first and last in a table is very arbitrary. In order to have a good predictable result you should always have an order by clause. And if you have that, then getting the last two rows will become easy.
For instance, if you have a primary key or something like an ID (which is populated by a sequence), then you can do:
select * from my_table where user = 'Username1' order by ID desc limit 2.
desc tells the database to sort the rows in reverse order, which means that last will be first.
Does your table have a primary key ? / Can your table be sorted?
Because the notion of 'first' and 'last' implies some sorting of the tuples. If this is the case, you could sort the data the other way around, so that your 'last' entries are on top. Then you can access them with the statement you tried.
To view tail of a table you may use ctid. It is a temporary physical identifier of a record in PostgreSQL.
SELECT * from my_table
WHERE user = Username1
ORDER BY ctid DESC
LIMIT 2

SQLite - a smart way to remove and add new objects

I have a table in my database and I want for each row in my table to have an unique id and to have the rows named sequently.
For example: I have 10 rows, each has an id - starting from 0, ending at 9. When I remove a row from a table, lets say - row number 5, there occurs a "hole". And afterwards I add more data, but the "hole" is still there.
It is important for me to know exact number of rows and to have at every row data in order to access my table arbitrarily.
There is a way in sqlite to do it? Or do I have to manually manage removing and adding of data?
Thank you in advance,
Ilya.
It may be worth considering whether you really want to do this. Primary keys usually should not change through the lifetime of the row, and you can always find the total number of rows by running:
SELECT COUNT(*) FROM table_name;
That said, the following trigger should "roll down" every ID number whenever a delete creates a hole:
CREATE TRIGGER sequentialize_ids AFTER DELETE ON table_name FOR EACH ROW
BEGIN
UPDATE table_name SET id=id-1 WHERE id > OLD.id;
END;
I tested this on a sample database and it appears to work as advertised. If you have the following table:
id name
1 First
2 Second
3 Third
4 Fourth
And delete where id=2, afterwards the table will be:
id name
1 First
2 Third
3 Fourth
This trigger can take a long time and has very poor scaling properties (it takes longer for each row you delete and each remaining row in the table). On my computer, deleting 15 rows at the beginning of a 1000 row table took 0.26 seconds, but this will certainly be longer on an iPhone.
I strongly suggest that you re-think your design. In my opinion your asking yourself for troubles in the future (e.g. if you create another table and want to have some relations between the tables).
If you want to know the number of rows just use:
SELECT count(*) FROM table_name;
If you want to access rows in the order of id, just define this field using PRIMARY KEY constraint:
CREATE TABLE test (
id INTEGER PRIMARY KEY,
...
);
and get rows using ORDER BY clause with ASC or DESC:
SELECT * FROM table_name ORDER BY id ASC;
Sqlite creates an index for the primary key field, so this query is fast.
I think that you would be interested in reading about LIMIT and OFFSET clauses.
The best source of information is the SQLite documentation.
If you don't want to take Stephen Jennings's very clever but performance-killing approach, just query a little differently. Instead of:
SELECT * FROM mytable WHERE id = ?
Do:
SELECT * FROM mytable ORDER BY id LIMIT 1 OFFSET ?
Note that OFFSET is zero-based, so you may need to subtract 1 from the variable you're indexing in with.
If you want to reclaim deleted row ids the VACUUM command or pragma may be what you seek,
http://www.sqlite.org/faq.html#q12
http://www.sqlite.org/lang_vacuum.html
http://www.sqlite.org/pragma.html#pragma_auto_vacuum