question
stringlengths
11
28.2k
answer
stringlengths
26
27.7k
tag
stringclasses
130 values
question_id
int64
935
78.4M
score
int64
10
5.49k
How can I SELECT the last row in a MySQL table? I'm INSERTing data and I need to retrieve a column value from the previous row. There's an auto_increment in the table.
Yes, there's an auto_increment in there If you want the last of all the rows in the table, then this is finally the time where MAX(id) is the right answer! Kind of: SELECT fields FROM table ORDER BY id DESC LIMIT 1;
MySQL
4,073,923
250
How can I drop the "Unique Key Constraint" on a column of a MySQL table using phpMyAdmin?
A unique constraint is also an index. First use SHOW INDEX FROM tbl_name to find out the name of the index. The name of the index is stored in the column called key_name in the results of that query. Then you can use DROP INDEX: DROP INDEX index_name ON tbl_name or the ALTER TABLE syntax: ALTER TABLE tbl_name DROP IN...
MySQL
3,487,691
250
I want to remove the password for user root in localhost. How can I do that? By mistake I have set the password of root user. That's why phpmyadmin is giving an error: #1045 - Access denied for user 'root'@'localhost' (using password: NO)
You need to set the password for root@localhost to be blank. There are two ways: The MySQL SET PASSWORD command: SET PASSWORD FOR root@localhost=PASSWORD(''); -- MySQL 5.x SET PASSWORD FOR root@localhost=''; -- MySQL 8.x Using the command-line mysqladmin tool: mysqladmin -u root -pType_in_your_current_password_here ...
MySQL
3,032,054
250
Background I'm a first year CS student and I work part time for my dad's small business. I don't have any experience in real world application development. I have written scripts in Python, some coursework in C, but nothing like this. My dad has a small training business and currently all classes are scheduled, recorde...
Some more answers to your questions: 1) You're pretty much on target for someone who is approaching a problem like this for the first time. I think the pointers from others on this question thus far pretty much cover it. Good job! 2 & 3) The performance hit you will take will largely be dependent on having and optimiz...
MySQL
2,320,633
250
I know how to use INDEX as in the following code. And I know how to use foreign key and primary key. CREATE TABLE tasks ( task_id int unsigned NOT NULL AUTO_INCREMENT, parent_id int unsigned NOT NULL DEFAULT 0, task varchar(100) NOT NULL, date_added timestamp NOT NULL, ...
There's no difference. They are synonyms, though INDEX should be preferred (as INDEX is ISO SQL compliant, while KEY is a MySQL-specific, non-portable, extension). From the CREATE TABLE manual entry: KEY is normally a synonym for INDEX. The key attribute PRIMARY KEY can also be specified as just KEY when given in a co...
MySQL
1,401,572
250
Error Code: 2013. Lost connection to MySQL server during query I am using MySQL Workbench. Also, I am running a batch of inserts, about 1000 lines total (Ex. INSERT INTO mytable SELECT * FROM mysource1; INSERT INTO mytable SELECT * FROM mysource2;...mysource3...mysource4 multiplied 1000 times) Each batch takes a consid...
From the now unavailable internet archive: Go to Edit -> Preferences -> SQL Editor and set to a higher value this parameter: DBMS connection read time out (in seconds). For instance: 86400. Close and reopen MySQL Workbench. Kill your previously query that probably is running and run the query again.
MySQL
15,712,512
248
I have the following sql create statement mysql> CREATE TABLE IF NOT EXISTS `erp`.`je_menus` ( -> `id` INT(11) NOT NULL AUTO_INCREMENT , -> `name` VARCHAR(100) NOT NULL , -> `description` VARCHAR(255) NOT NULL , -> `live_start_date` DATETIME NULL DEFAULT NULL , -> `live_end_date` DATETIME...
That is because of server SQL Mode - NO_ZERO_DATE. From the reference: NO_ZERO_DATE - In strict mode, doesn't allow '0000-00-00' as a valid date. You can still insert zero dates with the IGNORE option. When not in strict mode, the date is accepted but a warning is generated.
MySQL
9,192,027
248
Is it possible to set a user variable based on the result of a query in MySQL? What I want to achieve is something like this (we can assume that both USER and GROUP are unique): set @user = 123456; set @group = select GROUP from USER where User = @user; select * from USER where GROUP = @group; Please note that I know ...
Yes, but you need to move the variable assignment into the query: SET @user := 123456; SELECT @group := `group` FROM user WHERE user = @user; SELECT * FROM user WHERE `group` = @group; Test case: CREATE TABLE user (`user` int, `group` int); INSERT INTO user VALUES (123456, 5); INSERT INTO user VALUES (111111, 5); Res...
MySQL
3,888,735
248
I have a mysqldump backup of my mysql database consisting of all of our tables which is about 440 megs. I want to restore the contents of just one of the tables from the mysqldump. Is this possible? Theoretically, I could just cut out the section that rebuilds the table I want but I don't even know how to effectively e...
You can try to use sed in order to extract only the table you want. Let say the name of your table is mytable and the file mysql.dump is the file containing your huge dump: $ sed -n -e '/CREATE TABLE.*`mytable`/,/Table structure for table/p' mysql.dump > mytable.dump This will copy in the file mytable.dump what is loc...
MySQL
1,013,852
248
I've just started with Laravel and I get the following error: Unknown column 'updated_at' insert into gebruikers (naam, wachtwoord, updated_at, created_at) I know the error is from the timestamp column when you migrate a table but I'm not using the updated_at field. I used to use it when I followed the Laravel tut...
In the model, write the below code; public $timestamps = false; This would work. Explanation : By default laravel will expect created_at & updated_at column in your table. By making it to false it will override the default setting.
MySQL
28,277,955
247
I am trying to create a container with a MySQL database and add a schema to these database. My current Dockerfile is: FROM mysql MAINTAINER (me) <email> # Copy the database schema to the /data directory COPY files/epcis_schema.sql /data/epcis_schema.sql # Change the working directory WORKDIR data CMD mysql -u $MYSQ...
I had this same issue where I wanted to initialize my MySQL Docker instance's schema, but I ran into difficulty getting this working after doing some Googling and following others' examples. Here's how I solved it. 1) Dump your MySQL schema to a file. mysqldump -h <your_mysql_host> -u <user_name> -p --no-data <schema_...
MySQL
29,145,370
245
I'm using now() in MySQL query. INSERT INTO table SET data = '$data', date = now() But I want to add 1 day to this date (so that date should contain tomorrow). Is it possible?
You can use: NOW() + INTERVAL 1 DAY If you are only interested in the date, not the date and time then you can use CURDATE instead of NOW: CURDATE() + INTERVAL 1 DAY
MySQL
3,887,509
245
I have a table like this: TITLE DESCRIPTION test1 value blah blah value test2 value test test3 test test test test4 valuevaluevaluevaluevalue I am trying to figure out how to return the number of times a string occurs in each of the DESCRIPTION's. So, if I want to count the number of times 'value' app...
This should do the trick: SELECT title, description, ROUND ( ( LENGTH(description) - LENGTH( REPLACE ( description, "value", "") ) ) / LENGTH("value") ) AS count FROM <table>
MySQL
12,344,795
244
What's the equivalent to show tables (from MySQL) in PostgreSQL?
From the psql command line interface, First, choose your database \c database_name Then, this shows all tables in the current schema: \dt Programmatically (or from the psql interface too, of course): SELECT * FROM pg_catalog.pg_tables; The system tables live in the pg_catalog database.
PostgreSQL
769,683
2,500
How do you perform the equivalent of Oracle's DESCRIBE TABLE in PostgreSQL with psql command?
Try this (in the psql command-line tool): \d+ tablename See the manual for more info.
PostgreSQL
109,325
2,192
I'd like to select the first row of each set of rows grouped with a GROUP BY. Specifically, if I've got a purchases table that looks like this: SELECT * FROM purchases; My Output: id customer total 1 Joe 5 2 Sally 3 3 Joe 2 4 Sally 1 I'd like to query for the id of the largest purchase (total) made ...
DISTINCT ON is typically simplest and fastest for this in PostgreSQL. (For performance optimization for certain workloads see below.) SELECT DISTINCT ON (customer) id, customer, total FROM purchases ORDER BY customer, total DESC, id; Or shorter (if not as clear) with ordinal numbers of output columns: SELECT...
PostgreSQL
3,800,551
2,017
What command or short key can I use to exit the PostgreSQL command line utility psql?
Type \q and then press ENTER to quit psql. UPDATE: 19-OCT-2018 As of PostgreSQL 11, the keywords "quit" and "exit" in the PostgreSQL command-line interface have been included to help make it easier to leave the command-line tool.
PostgreSQL
9,463,318
1,967
How do I change the password for a PostgreSQL user?
To log in without a password: sudo -u user_name psql db_name To reset the password if you have forgotten: ALTER USER user_name WITH PASSWORD 'new_password';
PostgreSQL
12,720,967
1,877
In MySQL, I used use database_name; What's the psql equivalent?
In PostgreSQL, you can use the \connect meta-command of the client tool psql: \connect DBNAME or in short: \c DBNAME
PostgreSQL
3,949,876
1,536
I'm in a corporate environment (running Debian Linux) and didn't install it myself. I access the databases using Navicat or phpPgAdmin (if that helps). I also don't have shell access to the server running the database.
Run this query from PostgreSQL: SELECT version();
PostgreSQL
13,733,719
1,358
I'm getting the error: FATAL: Peer authentication failed for user "postgres" when I try to make postgres work with Rails. Here's my pg_hba.conf, my database.yml, and a dump of the full trace. I changed authentication to md5 in pg_hba and tried different things, but none seem to work. I also tried creating a new user...
The problem is still your pg_hba.conf file*. This line: local all postgres peer Should be: local all postgres md5 After altering this file, don't forget to restart your PostgreSQL server. If you're on Linux, that would be sudo s...
PostgreSQL
18,664,074
1,213
Final update: I had forgotten to run the initdb command. By running this command ps auxwww | grep postgres I see that postgres is not running > ps auxwww | grep postgres remcat 1789 0.0 0.0 2434892 480 s000 R+ 11:28PM 0:00.00 grep postgres This raises the question: How do I start the PostgreSQL ...
The Homebrew package manager includes launchctl plists to start automatically. For more information, run brew info postgres. Start manually pg_ctl -D /usr/local/var/postgres start Stop manually pg_ctl -D /usr/local/var/postgres stop Start automatically "To have launchd start postgresql now and restart at login:" brew s...
PostgreSQL
7,975,556
1,186
What is the easiest way to save PL/pgSQL output from a PostgreSQL database to a CSV file? I'm using PostgreSQL 8.4 with pgAdmin III and PSQL plugin where I run queries from.
Do you want the resulting file on the server, or on the client? Server side If you want something easy to re-use or automate, you can use Postgresql's built in COPY command. e.g. Copy (Select * From foo) To '/tmp/test.csv' With CSV DELIMITER ',' HEADER; This approach runs entirely on the remote server - it can't write...
PostgreSQL
1,517,635
1,127
I'm setting up my PostgreSQL 9.1. I can't do anything with PostgreSQL: can't createdb, can't createuser; all operations return the error message Fatal: role h9uest does not exist h9uest is my account name, and I sudo apt-get install PostgreSQL 9.1 under this account. Similar error persists for the root account.
Use the operating system user postgres to create your database - as long as you haven't set up a database role with the necessary privileges that corresponds to your operating system user of the same name (h9uest in your case): sudo -u postgres -i As recommended here or here. Then try again. Type exit when done with o...
PostgreSQL
11,919,391
1,075
What's the difference between the text data type and the character varying (varchar) data types? According to the documentation If character varying is used without length specifier, the type accepts strings of any size. The latter is a PostgreSQL extension. and In addition, PostgreSQL provides the text type, which ...
There is no difference, under the hood it's all varlena (variable length array). Check this article from Depesz: http://www.depesz.com/index.php/2010/03/02/charx-vs-varcharx-vs-varchar-vs-text/ A couple of highlights: To sum it all up: char(n) – takes too much space when dealing with values shorter than n (pads them ...
PostgreSQL
4,848,964
1,029
I'm using Postgres.app for Mac. I've used it in the past on other machines but it's giving me some trouble when installing on my MacBook. I've installed the application and I ran: psql -h localhost It returns: psql: FATAL: database "<user>" does not exist It seems I can't even run the console to create the database ...
It appears that your package manager failed to create the database named $user for you. The reason that psql -d template1 works for you is that template1 is a database created by postgres itself, and is present on all installations. You are apparently able to log in to template1, so you must have some rights assigned...
PostgreSQL
17,633,422
1,018
I am using the Ruby on Rails 3.1 pre version. I like to use PostgreSQL, but the problem is installing the pg gem. It gives me the following error: $ gem install pg Building native extensions. This could take a while... ERROR: Error installing pg: ERROR: Failed to build gem native extension. /home/u/.rvm/...
It looks like in Ubuntu that header is part of the libpq-dev package (at least in the following Ubuntu versions: 11.04 (Natty Narwhal), 10.04 (Lucid Lynx), 11.10 (Oneiric Ocelot), 12.04 (Precise Pangolin), 14.04 (Trusty Tahr) and 18.04 (Bionic Beaver)): ... /usr/include/postgresql/libpq-fe.h ... So try installing lib...
PostgreSQL
6,040,583
992
What's the correct way to copy entire database (its structure and data) to a new one in pgAdmin?
Postgres allows the use of any existing database on the server as a template when creating a new database. I'm not sure whether pgAdmin gives you the option on the create database dialog but you should be able to execute the following in a query window if it doesn't: CREATE DATABASE newdb WITH TEMPLATE originaldb OWNER...
PostgreSQL
876,522
915
I need to write a script that will drop a PostgreSQL database. There may be a lot of connections to it, but the script should ignore that. The standard DROP DATABASE db_name query doesn't work when there are open connections. How can I solve the problem?
This will drop existing connections except for yours: Query pg_stat_activity and get the pid values you want to kill, then issue SELECT pg_terminate_backend(pid int) to them. PostgreSQL 9.2 and above: SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = 'TARGET_DB' --...
PostgreSQL
5,408,156
853
Basically, I want to do this: update vehicles_vehicle v join shipments_shipment s on v.shipment_id=s.id set v.price=s.price_per_vehicle; I'm pretty sure that would work in MySQL (my background), but it doesn't seem to work in postgres. The error I get is: ERROR: syntax error at or near "join" LINE 1: update veh...
The UPDATE syntax is: [ WITH [ RECURSIVE ] with_query [, ...] ] UPDATE [ ONLY ] table [ [ AS ] alias ] SET { column = { expression | DEFAULT } | ( column [, ...] ) = ( { expression | DEFAULT } [, ...] ) } [, ...] [ FROM from_list ] [ WHERE condition | WHERE CURRENT OF cursor_name ] [ RETURNING...
PostgreSQL
7,869,592
817
Several months ago I learned from an answer on Stack Overflow how to perform multiple updates at once in MySQL using the following syntax: INSERT INTO table (id, field, field2) VALUES (1, A, X), (2, B, Y), (3, C, Z) ON DUPLICATE KEY UPDATE field=VALUES(Col1), field2=VALUES(Col2); I've now switched over to PostgreSQL a...
PostgreSQL since version 9.5 has UPSERT syntax, with ON CONFLICT clause. with the following syntax (similar to MySQL) INSERT INTO the_table (id, column_1, column_2) VALUES (1, 'A', 'X'), (2, 'B', 'Y'), (3, 'C', 'Z') ON CONFLICT (id) DO UPDATE SET column_1 = excluded.column_1, column_2 = excluded.column_2; ...
PostgreSQL
1,109,061
808
I have some .sql files with thousands of INSERT statements in them and need to run these inserts on my PostgreSQL database in order to add them to a table. The files are that large that it is impossible to open them and copy the INSERT statements into an editor window and run them there. I found on the Internet that yo...
Of course, you will get a fatal error for authenticating, because you do not include a user name... Try this one, it is OK for me :) psql -U username -d myDataBase -a -f myInsertFile If the database is remote, use the same command with host psql -h host -U username -d myDataBase -a -f myInsertFile
PostgreSQL
9,736,085
785
I have a table test(id,name). I need to insert values like: user's log, 'my user', customer's. insert into test values (1,'user's log'); insert into test values (2,''my users''); insert into test values (3,'customer's'); I am getting an error if I run any of the above statements. If there is any method to do this ...
String literals Escaping single quotes ' by doubling them up → '' is the standard way and works of course: 'user's log' -- incorrect syntax (unbalanced quote) 'user''s log' Plain single quotes (ASCII / UTF-8 code 39), mind you, not backticks `, which have no special purpose in Postgres (unlike certain other RDBMS)...
PostgreSQL
12,316,953
768
I'm a postgres novice. I installed the postgres.app for mac. I was playing around with the psql commands and I accidentally dropped the postgres database. I don't know what was in it. I'm currently working on a tutorial: http://www.rosslaird.com/blog/building-a-project-with-mezzanine/ And I'm stuck at sudo -u postgre...
NOTE: If you installed postgres using homebrew, see the comments from @user3402754 and @originalhat below. Note that the error message does NOT talk about a missing database, it talks about a missing role. Later in the login process it might also stumble over the missing database. But the first step is to check the mis...
PostgreSQL
15,301,826
751
In postgres, how do I change an existing user to be a superuser? I don't want to delete the existing user, for various reasons. # alter user myuser ...?
ALTER USER myuser WITH SUPERUSER; You can read more at the Documentation for ALTER USER
PostgreSQL
10,757,431
739
I ran into the problem that my primary key sequence is not in sync with my table rows. That is, when I insert a new row I get a duplicate key error because the sequence implied in the serial datatype returns a number that already exists. It seems to be caused by import/restores not maintaining the sequence properly.
-- Login to psql and run the following -- What is the result? SELECT MAX(id) FROM your_table; -- Then run... -- This should be higher than the last result. SELECT nextval('your_table_id_seq'); -- If it's not higher... run this set the sequence last to your highest id. -- (wise to run a quick pg_dump first...) BEGI...
PostgreSQL
244,243
737
We are switching hosts and the old one provided a SQL dump of the PostgreSQL database of our site. Now, I'm trying to set this up on a local WAMP server to test this. The only problem is that I don't have an idea how to import this database in the PostgreSQL 9 that I have set up. I tried pgAdmin III but I can't seem to...
psql --username=<db_user_name> databasename < data_base_dump That's the command you are looking for. Beware: databasename must be created before importing. Have a look at the PostgreSQL Docs Chapter 23. Backup and Restore.
PostgreSQL
6,842,393
710
I am trying to automate database creation process with a shell script and one thing I've hit a road block with passing a password to psql. Here is a bit of code from the shell script: psql -U $DB_USER -h localhost -c"$DB_RECREATE_SQL" How do I pass a password to psql in a non-interactive way?
Set the PGPASSWORD environment variable inside the script before calling psql PGPASSWORD=pass1234 psql -U MyUsername myDatabaseName For reference, see http://www.postgresql.org/docs/current/static/libpq-envars.html Edit Since Postgres 9.2 there is also the option to specify a connection string or URI that can contain...
PostgreSQL
6,405,127
709
I'm switching from MySQL to PostgreSQL and I was wondering how can I have an INT column with AUTO INCREMENT. I saw in the PostgreSQL docs a datatype called SERIAL, but I get syntax errors when using it.
Yes, SERIAL is the equivalent function. CREATE TABLE foo ( id SERIAL, bar varchar ); INSERT INTO foo (bar) VALUES ('blah'); INSERT INTO foo (bar) VALUES ('blah'); SELECT * FROM foo; +----------+ | 1 | blah | +----------+ | 2 | blah | +----------+ SERIAL is just a create table time macro around sequences. Y...
PostgreSQL
787,722
696
My question is rather simple. I'm aware of the concept of a UUID and I want to generate one to refer to each 'item' from a 'store' in my DB with. Seems reasonable right? The problem is the following line returns an error: honeydb=# insert into items values( uuid_generate_v4(), 54.321, 31, 'desc 1', 31.94); ERROR: func...
uuid-ossp is a contrib module, so it isn't loaded into the server by default. You must load it into your database to use it. For modern PostgreSQL versions (9.1 and newer) that's easy: CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; but for 9.0 and below you must instead run the SQL script to load the extension. See the ...
PostgreSQL
12,505,158
663
After I did brew update and brew upgrade, my postgres got some problem. I tried to uninstall postgres and install it again, but it didn't work as well. This is the error message. (I also got this error message when I try to do rake db:migrate) $ psql psql: could not connect to server: No such file or directory Is t...
Had a similar problem; a pid file was blocking postgres from starting up. To fix it: $ rm /usr/local/var/postgres/postmaster.pid $ brew services restart postgresql and then all is well. UPDATE: For Apple M1 (Big Sur) users, do this instead: $ rm /opt/homebrew/var/postgres/postmaster.pid $ brew services restart postgr...
PostgreSQL
13,410,686
646
I'm looking to copy a production PostgreSQL database to a development server. What's the quickest, easiest way to go about doing this?
You don't need to create an intermediate file. You can do pg_dump -C -h localhost -U localuser dbname | psql -h remotehost -U remoteuser dbname or pg_dump -C -h remotehost -U remoteuser dbname | psql -h localhost -U localuser dbname using psql or pg_dump to connect to a remote host. With a big database or a slow con...
PostgreSQL
1,237,725
645
I'd like to create a user in PostgreSQL that can only do SELECTs from a particular database. In MySQL the command would be: GRANT SELECT ON mydb.* TO 'xxx'@'%' IDENTIFIED BY 'yyy'; What is the equivalent command or series of commands in PostgreSQL? I tried... postgres=# CREATE ROLE xxx LOGIN PASSWORD 'yyy'; postgres=#...
Grant usage/select to a single table If you only grant CONNECT to a database, the user can connect but has no other privileges. You have to grant USAGE on namespaces (schemas) and SELECT on tables and views individually like so: GRANT CONNECT ON DATABASE mydb TO xxx; -- This assumes you're actually connected to mydb.. ...
PostgreSQL
760,210
629
I am beginner to PostgreSQL. I want to connect to another database from the query editor of Postgres - like the USE command of MySQL or MS SQL Server. I found \c databasename by searching the Internet, but its runs only on psql. When I try it from the PostgreSQL query editor I get a syntax error. I have to change the ...
When you get a connection to PostgreSQL it is always to a particular database. To access a different database, you must get a new connection. Using \c in psql closes the old connection and acquires a new one, using the specified database and/or credentials. You get a whole new back-end process and everything. Example...
PostgreSQL
10,335,561
612
I have recently installed PostgreSQL on Ubuntu with the EnterpriseDB package. I can connect to the database locally, but I can't configure it because I can't find config files. I searched through entire hard drive and found only samples like pg_hba.conf.sample Where are the PostgreSQL .conf files?
Or ask your database: $ psql -U postgres -c 'SHOW config_file' or, if logged in as the ubuntu user: $ sudo -u postgres psql -c 'SHOW config_file'
PostgreSQL
3,602,450
609
I have installed PostgreSQL 8.4, Postgres client and Pgadmin 3. Authentication failed for user "postgres" for both console client and Pgadmin. I have typed user as "postgres" and password "postgres", because it worked before. But now authentication is failed. I did it before a couple of times without this problem. What...
If I remember correctly the user postgres has no DB password set on Ubuntu by default. That means, that you can login to that account only by using the postgres OS user account. Assuming, that you have root access on the box you can do: sudo -u postgres psql If that fails with a database "postgres" does not exists err...
PostgreSQL
7,695,962
596
Is there any way to write case-insensitive queries in PostgreSQL, E.g. I want that following 3 queries return same result. SELECT id FROM groups where name='administrator' SELECT id FROM groups where name='ADMINISTRATOR' SELECT id FROM groups where name='Administrator'
Use LOWER function to convert the strings to lower case before comparing. Try this: SELECT id FROM groups WHERE LOWER(name)=LOWER('Administrator')
PostgreSQL
7,005,302
596
I'm looking for a way to find the row count for all my tables in Postgres. I know I can do this one table at a time with: SELECT count(*) FROM table_name; but I'd like to see the row count for all the tables and then order by that to get an idea of how big all my tables are.
There's three ways to get this sort of count, each with their own tradeoffs. If you want a true count, you have to execute the SELECT statement like the one you used against each table. This is because PostgreSQL keeps row visibility information in the row itself, not anywhere else, so any accurate count can only be r...
PostgreSQL
2,596,670
593
I need to retrieve all rows from a table where 2 columns combined are all different. So I want all the sales that do not have any other sales that happened on the same day for the same price. The sales that are unique based on day and price will get updated to an active status. So I'm thinking: UPDATE sales SET status ...
SELECT DISTINCT a,b,c FROM t is roughly equivalent to: SELECT a,b,c FROM t GROUP BY a,b,c It's a good idea to get used to the GROUP BY syntax, as it's more powerful. For your query, I'd do it like this: UPDATE sales SET status='ACTIVE' WHERE id IN ( SELECT id FROM sales S INNER JOIN ( SELE...
PostgreSQL
54,418
591
How can I kill all my postgresql connections? I'm trying a rake db:drop but I get: ERROR: database "database_name" is being accessed by other users DETAIL: There are 1 other session(s) using the database. I've tried shutting down the processes I see from a ps -ef | grep postgres but this doesn't work either: kill: k...
You can use pg_terminate_backend() to kill a connection. You have to be superuser to use this function. This works on all operating systems the same. SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE -- don't kill my own connection! pid <> pg_backend_pid() -- don't kill the connecti...
PostgreSQL
5,108,876
569
Locally, I use pgadmin3. On the remote server, however, I have no such luxury. I've already created the backup of the database and copied it over, but is there a way to restore a backup from the command line? I only see things related to GUI or to pg_dumps.
There are two tools to look at, depending on how you created the dump file. Your first source of reference should be the man page pg_dump as that is what creates the dump itself. It says: Dumps can be output in script or archive file formats. Script dumps are plain-text files containing the SQL commands required to...
PostgreSQL
2,732,474
560
I have this table in a postgres 8.4 database: CREATE TABLE public.dummy ( address_id SERIAL, addr1 character(40), addr2 character(40), city character(25), state character(2), zip character(5), customer boolean, supplier boolean, partner boolean ) WITH ( OIDS=FALSE ); I want to update the table. ...
Postgres allows: UPDATE dummy SET customer=subquery.customer, address=subquery.address, partn=subquery.partn FROM (SELECT address_id, customer, address, partn FROM /* big hairy SQL */ ...) AS subquery WHERE dummy.address_id=subquery.address_id; This syntax is not standard SQL, but it is much more conven...
PostgreSQL
6,256,610
555
When I do a \dt in psql I only get a listing of tables in the current schema (public by default). How can I get a list of all tables in all schemas or a particular schema?
In all schemas: => \dt *.* In a particular schema: => \dt public.* It is possible to use regular expressions with some restrictions \dt (public|s).(s|t) List of relations Schema | Name | Type | Owner --------+------+-------+------- public | s | table | cpn public | t | table | cpn s | t | t...
PostgreSQL
15,644,152
549
How do I modify the owner of all tables in a PostgreSQL database? I tried ALTER TABLE * OWNER TO new_owner but it doesn't support the asterisk syntax.
You can use the REASSIGN OWNED command. Synopsis: REASSIGN OWNED BY old_role [, ...] TO new_role This changes all objects owned by old_role to the new role. You don't have to think about what kind of objects that the user has, they will all be changed. Note that it only applies to objects inside a single database. I...
PostgreSQL
1,348,126
522
I want a random selection of rows in PostgreSQL, I tried this: select * from table where random() < 0.01; But some other recommend this: select * from table order by random() limit 1000; I have a very large table with 500 Million rows, I want it to be fast. Which approach is better? What are the differences? What i...
Fast ways Given your specifications (plus additional info in the comments): You have a numeric ID column (integer numbers) with only a few (or moderately few) gaps. Obviously no or few write operations. Your ID column has to be indexed! A primary key serves nicely. The query below does not need a sequential scan of t...
PostgreSQL
8,674,718
510
I have a timezone aware timestamptz field in PostgreSQL. When I pull data from the table, I then want to subtract the time right now so I can get it's age. The problem I'm having is that both datetime.datetime.now() and datetime.datetime.utcnow() seem to return timezone unaware timestamps, which results in me getting t...
Have you tried to remove the timezone awareness? From http://pytz.sourceforge.net/ naive = dt.replace(tzinfo=None) may have to add time zone conversion as well. edit: Please be aware the age of this answer. An answer involving ADDing the timezone info instead of removing it in python 3 is below. https://stackoverflow....
PostgreSQL
796,008
503
I'm trying to export a PostgreSQL table with headings to a CSV file via command line, however I get it to export to CSV file, but without headings. My code looks as follows: COPY products_273 to '/tmp/products_199.csv' delimiters',';
COPY products_273 TO '/tmp/products_199.csv' WITH (FORMAT CSV, HEADER); as described in the manual.
PostgreSQL
1,120,109
499
How to enable logging of all SQL executed by PostgreSQL 8.3? Edited (more info) I changed these lines : log_directory = 'pg_log' log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log' log_statement = 'all' And restart PostgreSQL service... but no log was created... I'm using Windows Server 2003. Any ideas...
In your data/postgresql.conf file, change the log_statement setting to 'all'. Edit Looking at your new information, I'd say there may be a few other settings to verify: make sure you have turned on the log_destination variable make sure you turn on the logging_collector also make sure that the log_directory directory...
PostgreSQL
722,221
497
I'm interested in learning some (ideally) database agnostic ways of selecting the nth row from a database table. It would also be interesting to see how this can be achieved using the native functionality of the following databases: SQL Server MySQL PostgreSQL SQLite Oracle I am currently doing something like the fo...
There are ways of doing this in optional parts of the standard, but a lot of databases support their own way of doing it. A really good site that talks about this and other things is http://troels.arvin.dk/db/rdbms/#select-limit. Basically, PostgreSQL and MySQL supports the non-standard: SELECT... LIMIT y OFFSET x Or...
PostgreSQL
16,568
495
I'm trying to create a cronjob to back up my database every night before something catastrophic happens. It looks like this command should meet my needs: 0 3 * * * pg_dump dbname | gzip > ~/backup/db/$(date +%Y-%m-%d).psql.gz Except after running that, it expects me to type in a password. I can't do that if I run it f...
Create a .pgpass file in the home directory of the account that pg_dump will run as. The format is: hostname:port:database:username:password Then, set the file's mode to 0600. Otherwise, it will be ignored. chmod 600 ~/.pgpass See the Postgresql documentation libpq-pgpass for more details.
PostgreSQL
2,893,954
492
Does Postgres automatically put indexes on foreign keys and primary keys? How can I tell? Is there a command that will return all indexes on a table?
PostgreSQL automatically creates indexes on primary keys and unique constraints, but not on the referencing side of foreign key relationships. When Pg creates an implicit index it will emit a NOTICE-level message that you can see in psql and/or the system logs, so you can see when it happens. Automatically created ind...
PostgreSQL
970,562
489
I am looking for a way to concatenate the strings of a field within a group by query. So for example, I have a table: ID COMPANY_ID EMPLOYEE 1 1 Anna 2 1 Bill 3 2 Carol 4 2 Dave and I wanted to group by company_id to get something like: COMPANY_ID EMPLOYEE 1 Anna, Bill 2 Carol, Dave Ther...
PostgreSQL 9.0 or later: Modern Postgres (since 2010) has the string_agg(expression, delimiter) function which will do exactly what the asker was looking for: SELECT company_id, string_agg(employee, ', ') FROM mytable GROUP BY company_id; Postgres 9 also added the ability to specify an ORDER BY clause in any aggregate...
PostgreSQL
43,870
487
How do I declare a variable for use in a PostgreSQL 8.3 query? In MS SQL Server I can do this: DECLARE @myvar INT; SET @myvar = 5/ SELECT * FROM somewhere WHERE something = @myvar; How do I do the same in PostgreSQL? According to the documentation variables are declared simply as "name type;", but this gives me a...
I accomplished the same goal by using a WITH clause, it's nowhere near as elegant but can do the same thing. Though for this example it's really overkill. I also don't particularly recommend this. WITH myconstants (var1, var2) as ( values (5, 'foo') ) SELECT * FROM somewhere, myconstants WHERE something = var1 OR...
PostgreSQL
1,490,942
482
I am using PostgreSQL 8.4 on Ubuntu. I have a table with columns c1 through cN. The columns are wide enough that selecting all columns causes a row of query results to wrap multiple times. Consequently, the output is hard to read. When the query results constitute just a few rows, it would be convenient if I could view...
I just needed to spend more time staring at the documentation. This command: \x on will do exactly what I wanted. Here is some sample output: select * from dda where u_id=24 and dda_is_deleted='f'; -[ RECORD 1 ]------+---------------------------------------------------------------------------------------------------...
PostgreSQL
9,604,723
481
In PostgreSQL, how do I get the last id inserted into a table? In MS SQL there is SCOPE_IDENTITY(). Please do not advise me to use something like this: select max(id) from table
( tl;dr : goto option 3: INSERT with RETURNING ) Recall that in postgresql there is no "id" concept for tables, just sequences (which are typically but not necessarily used as default values for surrogate primary keys, with the SERIAL pseudo-type). If you are interested in getting the id of a newly inserted row, there...
PostgreSQL
2,944,297
474
I use postgres from homebrew in my OS X, but when I reboot my system, sometimes the postgres doesn't start after the reboot, and so I manually tried to start it with postgres -D /usr/local/var/postgres, but then the error occurred with the following message: FATAL: could not open directory "pg_tblspc": No such file or...
Solved... in part. Apparently, Installing the latest versions of OS X (e.g. Yosemite or El Capitan) removes some directories in /usr/local/var/postgres. To fix this you simply recreate the missing directories: mkdir -p /usr/local/var/postgres/pg_commit_ts mkdir -p /usr/local/var/postgres/pg_dynshmem mkdir -p /usr/local...
PostgreSQL
25,970,132
470
How can I accomplish this using Postgres? I've tried the code below but it doesn't work: ALTER TABLE mytable ALTER COLUMN mycolumn BIGINT NULL;
From the fine manual: ALTER TABLE mytable ALTER COLUMN mycolumn DROP NOT NULL; There's no need to specify the type when you're just changing the nullability.
PostgreSQL
4,812,933
468
I have installed PostgreSQL and pgAdminIII on my Ubuntu Karmic box. I am able to use pgAdminIII successfully (i.e. connect/log on), however when I try to login to the server using the same username/pwd on the command line (using psql), I get the error: psql: FATAL: Ident authentication failed for user "postgres" Does...
The following steps work for a fresh install of postgres 9.1 on Ubuntu 12.04. (Worked for postgres 9.3.9 on Ubuntu 14.04 too.) By default, postgres creates a user named 'postgres'. We log in as her, and give her a password. $ sudo -u postgres psql \password Enter password: ... ... Logout of psql by typing \q or ctrl+d...
PostgreSQL
2,942,485
460
I tried to run simple SQL command: SELECT * FROM site_adzone; And I got this error: ERROR: permission denied for relation site_adzone What could be the problem here? I tried also to do select for other tables and got same issue. I also tried to do this: GRANT ALL PRIVILEGES ON DATABASE jerry TO tom; But I got this...
GRANT on the database is not what you need. Grant on the tables directly. Granting privileges on the database mostly is used to grant or revoke connect privileges. This allows you to specify who may do stuff in the database if they have sufficient other permissions. You want instead: GRANT ALL PRIVILEGES ON TABLE si...
PostgreSQL
15,520,361
454
I'm using psql's \dt to list all tables in a database and I need to save the results. What is the syntax to export the results of a psql command to a file?
From psql's help (\?): \o [FILE] send all query results to file or |pipe The sequence of commands will look like this: [wist@scifres ~]$ psql db Welcome to psql 8.3.6, the PostgreSQL interactive terminal db=>\o out.txt db=>\dt Then any db operation output will be written to out.txt. Enter '\o' to revert the ou...
PostgreSQL
5,331,320
442
Official page do not mention such case. But many users need only psql without a local database (I have it on AWS). Brew do not have psql.
You could also use homebrew to install libpq. brew install libpq This would give you psql, pg_dump and a whole bunch of other client utilities without installing Postgres. Unfortunately since it provides some of the same utilities as are included in the full postgresql package, brew installs it "keg-only" which means ...
PostgreSQL
44,654,216
441
Is there a command in PostgreSQL to select active connections to a given database? psql states that I can't drop one of my databases because there are active connections to it, so I would like to see what the connections are (and from which machines)
Oh, I just found that command on PostgreSQL forum: SELECT * FROM pg_stat_activity; To limit to just one database: SELECT * FROM pg_stat_activity WHERE datname = 'dbname';
PostgreSQL
27,435,839
438
How do I list all extensions that are already installed in a database or schema from psql? See also Finding a list of available extensions that PostgreSQL ships with
In psql that would be \dx See the manual of psql for details. Doing it in plain SQL it would be a select on pg_extension: SELECT * FROM pg_extension;
PostgreSQL
21,799,956
425
I would like to force the auto increment field of a table to some value, I tried with this: ALTER TABLE product AUTO_INCREMENT = 1453 AND ALTER SEQUENCE product RESTART WITH 1453; ERROR: relation "your_sequence_name" does not exist I have a table product with Id and name field
If you created the table product with an id column, then the sequence is not simply called product, but rather product_id_seq (that is, ${table}_${column}_seq). This is the ALTER SEQUENCE command you need: ALTER SEQUENCE product_id_seq RESTART WITH 1453 You can see the sequences in your database using the \ds command ...
PostgreSQL
5,342,440
424
I have a table column that uses an enum type. I wish to update that enum type to have an additional possible value. I don't want to delete any existing values, just add the new value. What is the simplest way to do this?
PostgreSQL 9.1 introduces ability to ALTER Enum types: ALTER TYPE enum_type ADD VALUE 'new_value'; -- appends to list ALTER TYPE enum_type ADD VALUE 'new_value' BEFORE 'old_value'; ALTER TYPE enum_type ADD VALUE 'new_value' AFTER 'old_value';
PostgreSQL
1,771,543
423
I am trying to copy an entire table from one database to another in Postgres. Any suggestions?
Extract the table and pipe it directly to the target database: pg_dump -t table_to_copy source_db | psql target_db Note: If the other database already has the table set up, you should use the -a flag to import data only, else you may see weird errors like "Out of memory": pg_dump -a -t table_to_copy source_db | psql t...
PostgreSQL
3,195,125
422
I have a table with this layout: CREATE TABLE Favorites ( FavoriteId uuid NOT NULL PRIMARY KEY, UserId uuid NOT NULL, RecipeId uuid NOT NULL, MenuId uuid ); I want to create a unique constraint similar to this: ALTER TABLE Favorites ADD CONSTRAINT Favorites_UniqueFavorite UNIQUE(UserId, MenuId, RecipeId); How...
Postgres 15 or newer Postgres 15 adds the clause NULLS NOT DISTINCT. The release notes: Allow unique constraints and indexes to treat NULL values as not distinct (Peter Eisentraut) Previously NULL values were always indexed as distinct values, but this can now be changed by creating constraints and indexes using UNIQ...
PostgreSQL
8,289,100
419
I'm trying to drop my database and create a new one through the command line. I log in using psql -U username and then do a \connect template1, followed by a DROP DATABASE databasename;. I get the error database databasename is being accessed by other users I shut down Apache and tried this again, but I'm still getti...
You can run the dropdb command from the command line: dropdb 'database name' Note that you have to be a superuser or the database owner to be able to drop it. You can also check the pg_stat_activity view to see what type of activity is currently taking place against your database, including all idle processes. SELECT ...
PostgreSQL
7,073,773
414
How can I call psql so that it doesn't prompt for a password? This is what I have: psql -Umyuser < myscript.sql However, I couldn't find the argument that passes the password, and so psql always prompts for it.
You may wish to read a summary of the ways to authenticate to PostgreSQL. To answer your question, there are several ways provide a password for password-based authentication: Via the password prompt. Example: psql -h uta.biocommons.org -U foo Password for user foo: In a pgpass file. See libpq-pgpass. Format: <host...
PostgreSQL
6,523,019
413
My docker compose file has three containers, web, nginx, and postgres. Postgres looks like this: postgres: container_name: postgres restart: always image: postgres:latest volumes: - ./database:/var/lib/postgresql ports: - 5432:5432 My goal is to mount a volume which corresponds to a local folder call...
Strangely enough, the solution ended up being to change volumes: - ./postgres-data:/var/lib/postgresql to volumes: - ./postgres-data:/var/lib/postgresql/data
PostgreSQL
41,637,505
412
I want to extract just the date part from a timestamp in PostgreSQL. I need it to be a postgresql DATE type so I can insert it into another table that expects a DATE value. For example, if I have 2011/05/26 09:00:00, I want 2011/05/26 I tried casting, but I only get 2011: timestamp:date cast(timestamp as date) I tried...
You can cast your timestamp to a date by suffixing it with ::date. Here, in psql, is a timestamp: # select '2010-01-01 12:00:00'::timestamp; timestamp --------------------- 2010-01-01 12:00:00 Now we'll cast it to a date: wconrad=# select '2010-01-01 12:00:00'::timestamp::date; date ------------ ...
PostgreSQL
6,133,107
404
I have created a table in postgreSQL. I want to look at the SQL statement used to create the table but cannot figure it out. How do I get the create table SQL statement for an existing table in Postgres via commandline or SQL statement?
pg_dump -t 'schema-name.table-name' --schema-only database-name More info - in the manual.
PostgreSQL
2,593,803
399
A very frequently asked question here is how to do an upsert, which is what MySQL calls INSERT ... ON DUPLICATE UPDATE and the standard supports as part of the MERGE operation. Given that PostgreSQL doesn't support it directly (before pg 9.5), how do you do this? Consider the following: CREATE TABLE testtable ( id ...
9.5 and newer: PostgreSQL 9.5 and newer support INSERT ... ON CONFLICT (key) DO UPDATE (and ON CONFLICT (key) DO NOTHING), i.e. upsert. Comparison with ON DUPLICATE KEY UPDATE. Quick explanation. For usage see the manual - specifically the conflict_action clause in the syntax diagram, and the explanatory text. Unlike t...
PostgreSQL
17,267,417
396
With postgresql 9.3 I can SELECT specific fields of a JSON data type, but how do you modify them using UPDATE? I can't find any examples of this in the postgresql documentation, or anywhere online. I have tried the obvious: postgres=# create table test (data json); CREATE TABLE postgres=# insert into test (data) values...
Update: With PostgreSQL 9.5, there are some jsonb manipulation functionality within PostgreSQL itself (but none for json; casts are required to manipulate json values). Merging 2 (or more) JSON objects (or concatenating arrays): SELECT jsonb '{"a":1}' || jsonb '{"b":2}', -- will yield jsonb '{"a":1,"b":2}' jsonb...
PostgreSQL
18,209,625
390
I would like to set up a table in PostgreSQL such that two columns together must be unique. There can be multiple values of either value, so long as there are not two that share both. For instance: CREATE TABLE someTable ( id int PRIMARY KEY AUTOINCREMENT, col1 int NOT NULL, col2 int NOT NULL ) So, col1 a...
CREATE TABLE someTable ( id serial PRIMARY KEY, col1 int NOT NULL, col2 int NOT NULL, UNIQUE (col1, col2) ) autoincrement is not postgresql. You want a integer primary key generated always as identity (or serial if you use PG 9 or lower. serial was soft-deprecated in PG 10). If col1 and col2 make a un...
PostgreSQL
14,221,775
390
I'm trying to backup/restore a PostgreSQL database as is explained on the Docker website, but the data is not restored. The volumes used by the database image are: VOLUME ["/etc/postgresql", "/var/log/postgresql", "/var/lib/postgresql"] and the CMD is: CMD ["/usr/lib/postgresql/9.3/bin/postgres", "-D", "/var/lib/post...
Backup your databases docker exec -t your-db-container pg_dumpall -c -U postgres > dump_`date +%Y-%m-%d"_"%H_%M_%S`.sql Creates filename like dump_2023-12-25_09_15_26.sql If you want a smaller file size, use gzip: docker exec -t your-db-container pg_dumpall -c -U postgres | gzip > dump_`date +%Y-%m-%d"_"%H_%M_%S`.sql....
PostgreSQL
24,718,706
385
I have been trying to set up a container for a development postgres instance by creating a custom user & database. I am using the official postgres docker image. In the documentation it instructs you to insert a bash script inside of the /docker-entrypoint-initdb.d/ folder to set up the database with any custom paramet...
EDIT - since Jul 23, 2015 The official postgres docker image will run .sql scripts found in the /docker-entrypoint-initdb.d/ folder. So all you need is to create the following sql script: init.sql CREATE USER docker; CREATE DATABASE docker; GRANT ALL PRIVILEGES ON DATABASE docker TO docker; and add it in your Docker...
PostgreSQL
26,598,738
382
I'm looking to update multiple rows in PostgreSQL in one statement. Is there a way to do something like the following? UPDATE table SET column_a = 1 where column_b = '123', column_a = 2 where column_b = '345'
You can also use update ... from syntax and use a mapping table. If you want to update more than one column, it's much more generalizable: update test as t set column_a = c.column_a from (values ('123', 1), ('345', 2) ) as c(column_b, column_a) where c.column_b = t.column_b; You can add as many columns ...
PostgreSQL
18,797,608
380
I need to programmatically insert tens of millions of records into a Postgres database. Presently, I'm executing thousands of insert statements in a single query. Is there a better way to do this, some bulk insert statement I do not know about?
PostgreSQL has a guide on how to best populate a database initially, and they suggest using the COPY command for bulk loading rows. The guide has some other good tips on how to speed up the process, like removing indexes and foreign keys before loading the data (and adding them back afterwards).
PostgreSQL
758,945
368
I have a PostgreSQL database table called "user_links" which currently allows the following duplicate fields: year, user_id, sid, cid The unique constraint is currently the first field called "id", however I am now looking to add a constraint to make sure the year, user_id, sid and cid are all unique but I cannot appl...
The basic idea will be using a nested query with count aggregation: select * from yourTable ou where (select count(*) from yourTable inr where inr.sid = ou.sid) > 1 You can adjust the where clause in the inner query to narrow the search. There is another good solution for that mentioned in the comments, (but not ever...
PostgreSQL
28,156,795
367
After restarting my MacBook Pro I am unable to start the database server: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/tmp/.s.PGSQL.5432"? I checked the logs and the following line appears over and over again: FATAL: database fi...
If you recently upgraded postgres to latest version, you can run the below command to upgrade your postgres data directory retaining all data: brew postgresql-upgrade-database The above command is taken from the output of brew info postgres Note: this won't work for upgrading from 14 to 15 as of recent testing. For po...
PostgreSQL
17,822,974
367
I got a lot of errors with the message : "DatabaseError: current transaction is aborted, commands ignored until end of transaction block" after changed from python-psycopg to python-psycopg2 as Django project's database engine. The code remains the same, just don't know where those errors are from.
This is what postgres does when a query produces an error and you try to run another query without first rolling back the transaction. (You might think of it as a safety feature, to keep you from corrupting your data.) To fix this, you'll want to figure out where in the code that bad query is being executed. It might...
PostgreSQL
2,979,369
364
I'm trying to set a sequence to a specific value. SELECT setval('payments_id_seq'), 21, true; This gives an error: ERROR: function setval(unknown) does not exist Using ALTER SEQUENCE doesn't seem to work either? ALTER SEQUENCE payments_id_seq LASTVALUE 22; How can this be done? Ref: https://www.postgresql.org/docs...
The parentheses are misplaced: SELECT setval('payments_id_seq', 21, true); -- next value will be 22 Otherwise you're calling setval with a single argument, while it requires two or three. This is the same as SELECT setval('payments_id_seq', 21)
PostgreSQL
8,745,051
360
Every time is set up a new SQL table or add a new varchar column to an existing table, I am wondering one thing: what is the best value for the length. So, lets say, you have a column called name of type varchar. So, you have to choose the length. I cannot think of a name > 20 chars, but you will never know. But inste...
No DBMS I know of has any "optimization" that will make a VARCHAR with a 2^n length perform better than one with a max length that is not a power of 2. I think early SQL Server versions actually treated a VARCHAR with length 255 differently than one with a higher maximum length. I don't know if this is still the case. ...
PostgreSQL
8,295,131
359
I have a table and I'd like to pull one row per id with field values concatenated. In my table, for example, I have this: TM67 | 4 | 32556 TM67 | 9 | 98200 TM67 | 72 | 22300 TM99 | 2 | 23009 TM99 | 3 | 11200 And I'd like to output: TM67 | 4,9,72 | 32556,98200,22300 TM99 | 2,3 | 23009,11200 In MySQL I was able ...
Since 9.0 this is even easier: SELECT id, string_agg(some_column, ',') FROM the_table GROUP BY id
PostgreSQL
2,560,946
357
Are timestamp values stored differently in PostgreSQL when the data type is WITH TIME ZONE versus WITHOUT TIME ZONE? Can the differences be illustrated with simple test cases?
The differences are covered at the PostgreSQL documentation for date/time types. Yes, the treatment of TIME or TIMESTAMP differs between one WITH TIME ZONE or WITHOUT TIME ZONE. It doesn't affect how the values are stored; it affects how they are interpreted. The effects of time zones on these data types is covered spe...
PostgreSQL
5,876,218
355
I'm trying to run the following PHP script to do a simple database query: $db_host = "localhost"; $db_name = "showfinder"; $username = "user"; $password = "password"; $dbconn = pg_connect("host=$db_host dbname=$db_name user=$username password=$password") or die('Could not connect: ' . pg_last_error()); $query = 'S...
This error means that you're not referencing the table name correctly. One common reason is that the table is defined with a mixed-case spelling, and you're trying to query it with all lower-case. In other words, the following fails: CREATE TABLE "SF_Bands" ( ... ); SELECT * FROM sf_bands; -- ERROR! Use double-quot...
PostgreSQL
695,289
353
I have the following UPSERT in PostgreSQL 9.5: INSERT INTO chats ("user", "contact", "name") VALUES ($1, $2, $3), ($2, $1, NULL) ON CONFLICT("user", "contact") DO NOTHING RETURNING id; If there are no conflicts it returns something like this: ---------- | id | ---------- 1 | 50 | ...
The currently accepted answer seems ok for a single conflict target, few conflicts, small tuples and no triggers. It avoids concurrency issue 1 (see below) with brute force. The simple solution has its appeal, the side effects may be less important. For all other cases, though, do not update identical rows without need...
PostgreSQL
34,708,509
352
I'm adding a new, "NOT NULL" column to my Postgresql database using the following query (sanitized for the Internet): ALTER TABLE mytable ADD COLUMN mycolumn character varying(50) NOT NULL; Each time I run this query, I receive the following error message: ERROR: column "mycolumn" contains null values I'm stumped....
You have to set a default value. ALTER TABLE mytable ADD COLUMN mycolumn character varying(50) NOT NULL DEFAULT 'foo'; ... some work (set real values as you want)... ALTER TABLE mytable ALTER COLUMN mycolumn DROP DEFAULT;
PostgreSQL
512,451
350
I have a table in PostgreSQL with many columns, and I want to add an auto increment primary key. I tried to create a column called id of type BIGSERIAL but pgadmin responded with an error: ERROR: sequence must have same owner as table it is linked to. Does anyone know how to fix this issue? How do I add or create a...
Try this command: ALTER TABLE your_table ADD COLUMN key_column BIGSERIAL PRIMARY KEY; Try it with the same DB-user as the one you have created the table.
PostgreSQL
7,718,585
348