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 |
|---|---|---|---|---|
I'm trying to delete orphan entries in a mysql table.
I have 2 tables like this:
Table files:
id
....
1
....
2
....
7
....
9
....
table blob:
fileid
....
1
....
2
....
3
....
4
....
4
....
4
....
9
....
The fileid and id columns can be used to join the tables together.
I want to de... | Using LEFT JOIN/IS NULL:
DELETE b FROM BLOB b
LEFT JOIN FILES f ON f.id = b.fileid
WHERE f.id IS NULL
Using NOT EXISTS:
DELETE FROM BLOB
WHERE NOT EXISTS(SELECT NULL
FROM FILES f
WHERE f.id = fileid)
Using NOT IN:
DELETE FROM BLOB
WHERE fileid NOT IN (SELECT f.id
... | MySQL | 3,384,127 | 219 |
I'm trying to finish this query; my tag field is set to UNIQUE and I simply want the database to ignore any duplicate tag.
INSERT INTO table_tags (tag) VALUES ('tag_a'),('tab_b'),('tag_c')
ON DUPLICATE KEY IGNORE '*the offending tag and carry on*'
or even this would be acceptable
INSERT INTO table_tags (tag) VALUES (... | Would suggest NOT using INSERT IGNORE as it ignores ALL errors (ie its a sloppy global ignore).
Instead, since in your example tag is the unique key, use:
INSERT INTO table_tags (tag) VALUES ('tag_a'),('tab_b'),('tag_c')
ON DUPLICATE KEY UPDATE tag=tag;
on duplicate key produces:
Query OK, 0 rows affected (0.07 sec)
... | MySQL | 2,366,813 | 219 |
Is it possible to somehow get structure of MySQL database, or just some table with simple query?
Or is there another way, how can I do it?
| I think that what you're after is DESCRIBE
DESCRIBE table;
You can also use SHOW TABLES
SHOW TABLES;
to get a list of the tables in your database.
| MySQL | 898,688 | 219 |
I need to delete all rows from a table but when I add a new row, I want the primary key ID, which has an auto increment, to start again from 0 respectively from 1.
| Do not delete, use truncate:
Truncate table XXX
The table handler does not remember the last used AUTO_INCREMENT value, but starts counting from the beginning. This is true even for MyISAM and InnoDB, which normally do not reuse sequence values.
Source.
| MySQL | 12,651,867 | 218 |
How can I make a copy values from one column to another?
I have:
Database name: list
-------------------
number | test
-------------------
123456 | somedata
123486 | somedata1
232344 | 34
I want to have:
Database name: list
----------------
number | test
----------------
123456 | 123456
123486 | 123486
232344 | 2323... | Short answer for the code in question is:
UPDATE `table` SET test=number
Here table is the table name and it's surrounded by grave accent (aka back-ticks `) as this is MySQL convention to escape keywords (and TABLE is a keyword in that case).
BEWARE!
This is pretty dangerous query which will wipe everything in column... | MySQL | 9,001,939 | 218 |
How to calculate the difference between two dates, in the format YYYY-MM-DD hh: mm: ss and to get the result in seconds or milliseconds?
| SELECT TIMEDIFF('2007-12-31 10:02:00','2007-12-30 12:01:01');
-- result: 22:00:59, the difference in HH:MM:SS format
SELECT TIMESTAMPDIFF(SECOND,'2007-12-30 12:01:01','2007-12-31 10:02:00');
-- result: 79259 the difference in seconds
So, you can use TIMESTAMPDIFF for your purpose.
| MySQL | 4,759,248 | 218 |
What is the equivalent of varchar(max) in MySQL?
| The max length of a varchar is subject to the max row size in MySQL, which is 64KB (not counting BLOBs):
VARCHAR(65535)
However, note that the limit is lower if you use a multi-byte character set:
VARCHAR(21844) CHARACTER SET utf8
Here are some examples:
The maximum row size is 65535, but a varchar also includes a b... | MySQL | 332,798 | 218 |
In the footer of my page, I would like to add something like "last updated the xx/xx/200x" with this date being the last time a certain mySQL table has been updated.
What is the best way to do that? Is there a function to retrieve the last updated date? Should I access to the database every time I need this value?
| In later versions of MySQL you can use the information_schema database to tell you when another table was updated:
SELECT UPDATE_TIME
FROM information_schema.tables
WHERE TABLE_SCHEMA = 'dbname'
AND TABLE_NAME = 'tabname'
This does of course mean opening a connection to the database.
An alternative option would... | MySQL | 307,438 | 218 |
I want to find an SQL query to find rows where field1 does not contain $x. How can I do this?
| What kind of field is this? The IN operator cannot be used with a single field, but is meant to be used in subqueries or with predefined lists:
-- subquery
SELECT a FROM x WHERE x.b NOT IN (SELECT b FROM y);
-- predefined list
SELECT a FROM x WHERE x.b NOT IN (1, 2, 3, 6);
If you are searching a string, go for the LIK... | MySQL | 232,935 | 218 |
When I execute this command in MySQL:
SET FOREIGN_KEY_CHECKS=0;
Does it affect the whole engine or it is only my current transaction?
| It is session-based, when set the way you did in your question.
https://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html
According to this, FOREIGN_KEY_CHECKS is "Both" for scope. This means it can be set for session:
SET FOREIGN_KEY_CHECKS=0;
or globally:
SET GLOBAL FOREIGN_KEY_CHECKS=0;
| MySQL | 8,538,636 | 217 |
Error message on MySql:
Illegal mix of collations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT) for operation '='
I have gone through several other posts and was not able to solve this problem.
The part affected is something similar to this:
CREATE TABLE users (
userID INT UNSIGNED NOT NULL AUTO_INCREM... | The default collation for stored procedure parameters is utf8_general_ci and you can't mix collations, so you have four options:
Option 1: add COLLATE to your input variable:
SET @rUsername = ‘aname’ COLLATE utf8_unicode_ci; -- COLLATE added
CALL updateProductUsers(@rUsername, @rProductID, @rPerm);
Option 2: add COLLA... | MySQL | 11,770,074 | 216 |
Is there a measurable performance difference between using INT vs. VARCHAR as a primary key in MySQL? I'd like to use VARCHAR as the primary key for reference lists (think US States, Country Codes) and a coworker won't budge on the INT AUTO_INCREMENT as a primary key for all tables.
My argument, as detailed here, is t... | I was a bit annoyed by the lack of benchmarks for this online, so I ran a test myself.
Note though that I don't do it on a regular basic, so please check my setup and steps for any factors that could have influenced the results unintentionally, and post your concerns in comments.
The setup was as follows:
Intel® Core... | MySQL | 332,300 | 216 |
I have two columns in table users namely registerDate and lastVisitDate which consist of datetime data type. I would like to do the following.
Set registerDate defaults value to MySQL NOW()
Set lastVisitDate default value to 0000-00-00 00:00:00 Instead of null which it uses by default.
Because the table already exist... | As of MySQL 5.6.5, you can use the DATETIME type with a dynamic default value:
CREATE TABLE foo (
creation_time DATETIME DEFAULT CURRENT_TIMESTAMP,
modification_time DATETIME ON UPDATE CURRENT_TIMESTAMP
)
Or even combine both rules:
modification_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT... | MySQL | 5,818,423 | 215 |
I am wondering if there is any difference with regards to performance between the following
SELECT ... FROM ... WHERE someFIELD IN(1,2,3,4)
SELECT ... FROM ... WHERE someFIELD between 0 AND 5
SELECT ... FROM ... WHERE someFIELD = 1 OR someFIELD = 2 OR someFIELD = 3 ...
or will MySQL optimize the SQL in the same way... | I needed to know this for sure, so I benchmarked both methods. I consistenly found IN to be much faster than using OR.
Do not believe people who give their "opinion", science is all about testing and evidence.
I ran a loop of 1000x the equivalent queries (for consistency, I used sql_no_cache):
IN: 2.34969592094s
OR: 5.... | MySQL | 782,915 | 215 |
I am using prepared statements to execute mysql database queries. And I want to implement a search functionality based on a keyword of sorts.
For that I need to use LIKE keyword, that much I know. And I have also used prepared statements before, but I do not know how to use it with LIKE because from the following code... | You need to set it in the value itself, not in the prepared statement SQL string.
So, this should do for a prefix-match:
notes = notes
.replace("!", "!!")
.replace("%", "!%")
.replace("_", "!_")
.replace("[", "![");
PreparedStatement pstmt = con.prepareStatement(
"SELECT * FROM analysis WHERE n... | MySQL | 8,247,970 | 214 |
What is the upper limit of records for MySQL database table. I'm wondering about autoincrement field. What would happen if I add milions of records? How to handle this kind of situations?
Thx!
| The greatest value of an integer has little to do with the maximum number of rows you can store in a table.
It's true that if you use an int or bigint as your primary key, you can only have as many rows as the number of unique values in the data type of your primary key, but you don't have to make your primary key an i... | MySQL | 2,716,232 | 214 |
with the following statement:
mysqldump --complete-insert --lock-all-tables --no-create-db
--no-create-info --extended-insert --password=XXX -u XXX
--dump-date yyy > yyy_dataOnly.sql
I get INSERT statements like the following:
INSERT INTO `table` VALUES (1,'something'),(2,'anything'),(3,'everything');
What I need i... | Use:
mysqldump --extended-insert=FALSE
Be aware that multiple inserts will be slower than one big insert.
| MySQL | 12,439,353 | 213 |
I am working on a project where i need to create a database with 300 tables for each user who wants to see the demo application. it was working fine but today when i was testing with a new user to see a demo it showed me this error message
1030 Got error 28 from storage engine
After spending some time googling i foun... | Mysql error "28 from storage engine" - means "not enough disk space".
To show disc space use command below.
myServer# df -h
Results must be like this.
Filesystem Size Used Avail Capacity Mounted on
/dev/vdisk 13G 13G 46M 100% /
devfs 1.0k 1.0k 0B 100% /dev
| MySQL | 10,631,387 | 213 |
I cant get my mysql to start on os x 10.7. It is located in /usr/local/mysql/bin/mysql
I get command not found when I type mysql --version in the terminal.
I tried this can't access mysql from command line mac but still get command not found. I tried installing mysql with the dmg and i have tried to install it throu... | This is the problem with your $PATH:
/usr/local//usr/local/mysql/bin/private/var/mysql/private/var/mysql/bin.
$PATH is where the shell searches for command files. Folders to search in need to be separated with a colon. And so you want /usr/local/mysql/bin/ in your path but instead it searches in /usr/local//usr/local... | MySQL | 10,577,374 | 212 |
Possible Duplicate:
Why would someone use WHERE 1=1 AND <conditions> in a SQL clause?
I saw some people use a statement to query a table in a MySQL database like the following:
select * from car_table where 1=1 and value="TOYOTA"
But what does 1=1 mean here?
| It's usually when folks build up SQL statements.
When you add and value = "Toyota" you don't have to worry about whether there is a condition before or just WHERE. The optimiser should ignore it
No magic, just practical
Example Code:
commandText = "select * from car_table where 1=1";
if (modelYear <> 0) commandTe... | MySQL | 8,149,142 | 212 |
We're using Doctrine, a PHP ORM. I am creating a query like this:
$q = Doctrine_Query::create()->select('id')->from('MyTable');
and then in the function I'm adding in various where clauses and things as appropriate, like this
$q->where('normalisedname = ? OR name = ?', array($string, $originalString));
Later on, befo... | Doctrine is not sending a "real SQL query" to the database server : it is actually using prepared statements, which means :
Sending the statement, for it to be prepared (this is what is returned by $query->getSql())
And, then, sending the parameters (returned by $query->getParameters())
and executing the prepared stat... | MySQL | 2,095,394 | 212 |
Which is the valid syntax of this query in MySQL?
SELECT * FROM courses WHERE (now() + 2 hours) > start_time
note: start_time is a field of courses table
| SELECT *
FROM courses
WHERE DATE_ADD(NOW(), INTERVAL 2 HOUR) > start_time
See Date and Time Functions for other date/time manipulation.
| MySQL | 589,652 | 212 |
While importing the database in mysql, I have got following error:
1418 (HY000) at line 10185: This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled (you might want to use the less safe log_bin_trust_function_creators variable)
I don't know which things i ... | There are two ways to fix this:
Execute the following in the MySQL console:
SET GLOBAL log_bin_trust_function_creators = 1;
Add the following to the mysql.ini configuration file:
log_bin_trust_function_creators = 1;
The setting relaxes the checking for non-deterministic functions. Non-deterministic functions are fun... | MySQL | 26,015,160 | 211 |
I want to move away from PHP a little and learn Python. In order to do web development with Python I'll need a framework to help with templating and other things.
I have a non-production server that I use to test all of web development stuff on. It is a Debian 7.1 LAMP stack that runs MariaDB instead of the common MyS... | MySQL support is simple to add. In your DATABASES dictionary, you will have an entry like this:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'DB_NAME',
'USER': 'DB_USER',
'PASSWORD': 'DB_PASSWORD',
'HOST': 'localhost', # Or an IP Address that yo... | MySQL | 19,189,813 | 211 |
In linux I could find the mysql installation directory with the command which mysql. But I could not find any in windows. I tried echo %path% and it resulted many paths along with path to mysql bin.
I wanted to find the mysql data directory from command line in windows for use in batch program. I would also like to fi... | You can issue the following query from the command line:
mysql -uUSER -p -e 'SHOW VARIABLES WHERE Variable_Name LIKE "%dir"'
Output (on Linux):
+---------------------------+----------------------------+
| Variable_name | Value |
+---------------------------+----------------------------... | MySQL | 17,968,287 | 211 |
I have table name called "Person" with following column names
P_Id(int),
LastName(varchar),
FirstName (varchar).
I forgot to give NOT NULL Constraint to P_Id.
Now I tried with following query to add NOT NULL Constraint to existing column called P_Id,
1. ALTER TABLE Person MODIFY (P_Id NOT NULL);
2. ALTER TABLE Per... | Just use an ALTER TABLE... MODIFY... query and add NOT NULL into your existing column definition. For example:
ALTER TABLE Person MODIFY P_Id INT(11) NOT NULL;
A word of caution: you need to specify the full column definition again when using a MODIFY query. If your column has, for example, a DEFAULT value, or a colum... | MySQL | 6,305,225 | 211 |
CREATE TABLE foo SELECT * FROM bar
copies the table foo and duplicates it as a new table called bar.
How can I copy the schema of foo to a new table called bar without copying over the data as well?
| Try
CREATE TABLE foo LIKE bar;
so the keys and indexes are copied over as, well.
Documentation
| MySQL | 1,834,472 | 211 |
Recently my server CPU has been going very high.
CPU load averages 13.91 (1 min) 11.72 (5 mins) 8.01 (15 mins) and my site has only had a slight increase in traffic.
After running a top command, I saw MySQL was using 160% CPU!
Recently I've been optimizing tables and I've switched to persistent connections. Could this... | First I'd say you probably want to turn off persistent connections as they almost always do more harm than good.
Secondly I'd say you want to double check your MySQL users, just to make sure it's not possible for anyone to be connecting from a remote server. This is also a major security thing to check.
Thirdly I'd say... | MySQL | 1,282,232 | 211 |
I am trying to post on an API with some query params.
This is working on PostMan / Insomnia when I am trying to by passing mail and firstname as query parameters :
http://localhost:8000/api/mails/users/sendVerificationMail?mail=lol%40lol.com&firstname=myFirstName
However, when I am trying to do it with my react nativ... | axios signature for post is axios.post(url[, data[, config]]). So you want to send params object within the third argument:
.post(`/mails/users/sendVerificationMail`, null, { params: {
mail,
firstname
}})
.then(response => response.status)
.catch(err => console.warn(err));
This will POST an empty body with the two... | MySQL | 53,501,185 | 210 |
Here's how I do it:
Table names are lower case, use underscores to separate words, and are singular (e.g. foo, foo_bar, etc.
I generally (not always) have an auto increment PK. I use the following convention: tablename_id (e.g. foo_id, foo_bar_id, etc.).
When a table contains a column that is a foreign key, I just cop... | I would say that first and foremost: be consistent.
I reckon you are almost there with the conventions that you have outlined in your question. A couple of comments though:
Points 1 and 2 are good I reckon.
Point 3 - sadly this is not always possible. Think about how you would cope with a single table foo_bar that has ... | MySQL | 7,899,200 | 210 |
I have 1-many number of records that need to be entered into a table. What is the best way to do this in a query? Should I just make a loop and insert one record per iteration? Or is there a better way?
| From the MySQL manual
INSERT statements that use VALUES
syntax can insert multiple rows. To do
this, include multiple lists of column
values, each enclosed within
parentheses and separated by commas.
Example:
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
| MySQL | 5,526,917 | 210 |
I'm looking at MySQL procedures and functions. What is the real difference?
They seem to be similar, but a function has more limitations.
I'm likely wrong, but it seems a procedure can do everything and more than a function can. Why/when would I use a procedure vs a function?
| The most general difference between procedures and functions is that they are invoked differently and for different purposes:
A procedure does not return a value. Instead, it is invoked with a CALL statement to perform an operation such as modifying a table or processing retrieved records.
A function is invoked withi... | MySQL | 3,744,209 | 210 |
It seems that I may have inadvertently loaded the password validation plugin in MySQL 5.7. This plugin seems to force all passwords to comply to certain rules.
I would like to turn this off.
I've tried changing the validate_password_length variable as suggested here to no avail.
mysql> SET GLOBAL validate_password_leng... | Here is what I do to remove the validate password plugin:
Login to the mysql server as root mysql -h localhost -u root -p
Run the following sql command: uninstall plugin validate_password;
If last line doesn't work (new mysql release), you should execute UNINSTALL COMPONENT 'file://component_validate_password';
I wo... | MySQL | 36,301,100 | 209 |
I'm trying to run WordPress in my Windows desktop and it needs MySQL.
I install everything with Web Platform Installer which is provided by Microsoft. I never set a root password for MySQL and in the final step of installing WordPress, it asks for a MySQL server password.
What is the default password for root (if there... | for this kind of error; you just have to set new password to the root user as an admin. follow the steps as follows:
[root ~]# mysql -u root
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password:NO)
Stop the service/daemon of mysql running
[root ~]# service mysql stop
mysql stop/waiting
... | MySQL | 2,995,054 | 209 |
I was wondering if there is a way to do this purely in sql:
q1 = SELECT campaign_id, from_number, received_msg, date_received
FROM `received_txts` WHERE `campaign_id` = '8';
INSERT INTO action_2_members (campaign_id, mobile, vote, vote_date)
VALUES(q1.campaign_id, q1.from_number, q1.received_msg, q1.date_... | INSERT INTO action_2_members (campaign_id, mobile, vote, vote_date)
SELECT campaign_id, from_number, received_msg, date_received
FROM `received_txts`
WHERE `campaign_id` = '8'
| MySQL | 4,241,621 | 208 |
I'm a bit confused on how to order by date formats.
For the format YYYY-MM-DD you would do this: ...ORDER BY date DESC...
How would you order by DD/MM/YYYY?
This isn't working:
SELECT * FROM $table ORDER BY DATE_FORMAT(Date, '%Y%m%d') DESC LIMIT 14
| Guessing you probably just want to format the output date? then this is what you are after
SELECT *, DATE_FORMAT(date,'%d/%m/%Y') AS niceDate
FROM table
ORDER BY date DESC
LIMIT 0,14
Or do you actually want to sort by Day before Month before Year?
| MySQL | 10,637,581 | 207 |
The 'id' field of my table auto increases when I insert a row. I want to insert a row and then get that ID.
I would do it just as I said it, but is there a way I can do it without worrying about the time between inserting the row and getting the id?
I know I can query the database for the row that matches the informati... | $link = mysqli_connect('127.0.0.1', 'my_user', 'my_pass', 'my_db');
mysqli_query($link, "INSERT INTO mytable (1, 2, 3, 'blah')");
$id = mysqli_insert_id($link);
See mysqli_insert_id().
Whatever you do, don't insert and then do a "SELECT MAX(id) FROM mytable". Like you say, it's a race condition and there's no need. my... | MySQL | 897,356 | 207 |
I want to install the MySQL client for the command line, not a GUI. I have searched over the web but only found instructions on installing the MySQL server.
| install MySQLWorkbench, then
export PATH=$PATH:/Applications/MySQLWorkbench.app/Contents/MacOS
| MySQL | 30,990,488 | 206 |
I have two tables in MySQL. Table Person has the following columns:
id
name
fruits
The fruits column may hold null or an array of strings like ('apple', 'orange', 'banana'), or ('strawberry'), etc. The second table is Table Fruit and has the following three columns:
fruit_name
color
price
apple
red
2
... | The proper way to do this is to use multiple tables and JOIN them in your queries.
For example:
CREATE TABLE person (
`id` INT NOT NULL PRIMARY KEY,
`name` VARCHAR(50)
);
CREATE TABLE fruits (
`fruit_name` VARCHAR(20) NOT NULL PRIMARY KEY,
`color` VARCHAR(20),
`price` INT
);
CREATE TABLE person_fruit (
`person_id` IN... | MySQL | 17,371,639 | 206 |
Does anyone know how to convert JS dateTime to MySQL datetime? Also is there a way to add a specific number of minutes to JS datetime and then pass it to MySQL datetime?
|
var date;
date = new Date();
date = date.getUTCFullYear() + '-' +
('00' + (date.getUTCMonth()+1)).slice(-2) + '-' +
('00' + date.getUTCDate()).slice(-2) + ' ' +
('00' + date.getUTCHours()).slice(-2) + ':' +
('00' + date.getUTCMinutes()).slice(-2) + ':' +
('00' + date.getUTCSeconds()).slice(-2);
... | MySQL | 5,129,624 | 206 |
I've searched around but didn't find if it's possible.
I've this MySQL query:
INSERT INTO table (id,a,b,c,d,e,f,g) VALUES (1,2,3,4,5,6,7,8)
Field id has a "unique index", so there can't be two of them. Now if the same id is already present in the database, I'd like to update it. But do I really have to specify all the... | The UPDATE statement is given so that older fields can be updated to new value. If your older values are the same as your new ones, why would you need to update it in any case?
For eg. if your columns a to g are already set as 2 to 8; there would be no need to re-update it.
Alternatively, you can use:
INSERT INTO table... | MySQL | 14,383,503 | 205 |
Here is what I want to do:
current table:
+----+-------------+
| id | data |
+----+-------------+
| 1 | max |
| 2 | linda |
| 3 | sam |
| 4 | henry |
+----+-------------+
Mystery Query ( something like "UPDATE table SET data = CONCAT(data, 'a')" )
resulting ta... | That's pretty much all you need:
mysql> select * from t;
+------+-------+
| id | data |
+------+-------+
| 1 | max |
| 2 | linda |
| 3 | sam |
| 4 | henry |
+------+-------+
4 rows in set (0.02 sec)
mysql> update t set data=concat(data, 'a');
Query OK, 4 rows affected (0.01 sec)
Rows matched: 4 Cha... | MySQL | 4,128,335 | 205 |
Can I run a select statement and get the row number if the items are sorted?
I have a table like this:
mysql> describe orders;
+-------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------------------+... | Take a look at this.
Change your query to:
SET @rank=0;
SELECT @rank:=@rank+1 AS rank, itemID, COUNT(*) as ordercount
FROM orders
GROUP BY itemID
ORDER BY ordercount DESC;
SELECT @rank;
The last select is your count.
| MySQL | 2,520,357 | 205 |
After noticing an application tended to discard random emails due to incorrect string value errors, I went though and switched many text columns to use the utf8 column charset and the default column collate (utf8_general_ci) so that it would accept them. This fixed most of the errors, and made the application stop get... | UPDATE to the below answer:
The time the question was asked, "UTF8" in MySQL meant utf8mb3. In the meantime, utf8mb4 was added, but to my knowledge MySQLs "UTF8" was not switched to mean utf8mb4.
That means, you'd need to specifically put "utf8mb4", if you mean it (and you should use utf8mb4)
I'll keep this here instea... | MySQL | 1,168,036 | 205 |
I would like to know how can I output a number with 2 decimal places, without rounding the original number.
For example:
2229,999 -> 2229,99
I already tried:
FORMAT(2229.999, 2)
CONVERT(2229.999, DECIMAL(4,2))
| When formatting number to 2 decimal places you have two options TRUNCATE and ROUND. You are looking for TRUNCATE function.
Examples:
Without rounding:
TRUNCATE(0.166, 2)
-- will be evaluated to 0.16
TRUNCATE(0.164, 2)
-- will be evaluated to 0.16
docs: https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.ht... | MySQL | 11,190,668 | 204 |
In short: Is there any way to sort the values in a GROUP_CONCAT statement?
Query:
GROUP_CONCAT((SELECT GROUP_CONCAT(parent.name SEPARATOR " » ")
FROM test_competence AS node, test_competence AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt
AND node.id = l.competence
AND parent.id != 1
ORDER BY ... | Sure, see http://dev.mysql.com/doc/refman/...tions.html#function_group-concat:
SELECT student_name,
GROUP_CONCAT(DISTINCT test_score ORDER BY test_score DESC SEPARATOR ' ')
FROM student
GROUP BY student_name;
| MySQL | 995,373 | 204 |
I have table - config.
Schema:
config_name | config_value
And I would like to update multiple records in one query. I try like that:
UPDATE config
SET t1.config_value = 'value'
, t2.config_value = 'value2'
WHERE t1.config_name = 'name1'
AND t2.config_name = 'name2';
but that query is wrong :(
Can you help me?... | Try either multi-table update syntax
UPDATE config t1 JOIN config t2
ON t1.config_name = 'name1' AND t2.config_name = 'name2'
SET t1.config_value = 'value',
t2.config_value = 'value2';
Here is a SQLFiddle demo
or conditional update
UPDATE config
SET config_value = CASE config_name
... | MySQL | 20,255,138 | 203 |
I am storing the last login time in MySQL in, datetime-type filed. When users logs in, I want to get the difference between the last login time and the current time (which I get using NOW()).
How can I calculate it?
| USE TIMESTAMPDIFF MySQL function. For example, you can use:
SELECT TIMESTAMPDIFF(SECOND, '2012-06-06 13:13:55', '2012-06-06 15:20:18')
In your case, the third parameter of TIMSTAMPDIFF function would be the current login time (NOW()). Second parameter would be the last login time, which is already in the database.
| MySQL | 10,907,750 | 203 |
I have a database called nitm. I haven't created any tables there. But I have a SQL file which contains all the necessary data for the database. The file is nitm.sql which is in C:\ drive. This file has size of about 103 MB. I am using wamp server.
I have used the following syntax in MySQL console to import the file:
m... | From the mysql console:
mysql> use DATABASE_NAME;
mysql> source path/to/file.sql;
make sure there is no slash before path if you are referring to a relative path... it took me a while to realize that! lol
| MySQL | 5,152,921 | 203 |
I am planning to do a class project and was going through few technologies where I can automate or set the flow of data between systems and found that there are couple of them i.e. Apache NiFi and StreamSets ( to my knowledge ). What I couldn't understand is the difference between them and use-cases where they can be u... | Suraj,
Great question.
My response is as a member of the open source Apache NiFi project management committee and as someone who is passionate about the dataflow management domain.
I've been involved in the NiFi project since it was started in 2006. My knowledge of Streamsets is relatively limited so I'll let them spe... | StreamSets | 36,899,612 | 43 |
I was reading articles related to Kafka and StreamSets and my understanding was
Kafka acts as a broker between Producer system and subscriber. Producer push the data into Kafka cluster, subscriber pull the data from Kafka
StreamsSets is a technology to move data from one source to another through a pipeline
Now, bel... | StreamSets is a graphical tool that contains components that allow for data movement, which happen to include Kafka producers and consumers, but you're not required to use them.
They're complementary, and by using Kafka, you can allow for back-pressure in streaming systems or have non-StreamSets producers/consumers int... | StreamSets | 56,416,005 | 10 |
DELETE B.*
FROM m_productprice B
INNER JOIN m_product C ON B.m_product_id = C.m_product_id
WHERE C.upc = '7094' AND B.m_pricelist_version_id = '1000020'
i am getting the following error PostgreSQL 8.2.11
ERROR: syntax error at or near "B"
LINE 1: DELETE B.* from m_productprice B INNER JOIN m_product C ... | DELETE
FROM m_productprice B
USING m_product C
WHERE B.m_product_id = C.m_product_id AND
C.upc = '7094' AND
B.m_pricelist_version_id='1000020';
or
DELETE
FROM m_productprice
WHERE m_pricelist_version_id='1000020' AND
m_product_id IN (SELECT m_product_id
... | PostgreSQL | 11,753,904 | 320 |
In MS SQL-Server, I can do:
SELECT ISNULL(Field,'Empty') from Table
But in PostgreSQL I get a syntax error. How do I emulate the ISNULL() functionality ?
| SELECT CASE WHEN field IS NULL THEN 'Empty' ELSE field END AS field_alias
Or more idiomatic:
SELECT coalesce(field, 'Empty') AS field_alias
| PostgreSQL | 2,214,525 | 318 |
Where can I find a detailed manual about PostgreSQL naming conventions? (table names vs. camel case, sequences, primary keys, constraints, indexes, etc...)
| Regarding tables names, case, etc, the prevalent convention is:
SQL keywords: UPPER CASE
identifiers (names of databases, tables, columns, etc): lower_case_with_underscores
For example:
UPDATE my_table SET name = 5;
This is not written in stone, but the bit about identifiers in lower case is highly recommended, IMO.... | PostgreSQL | 2,878,248 | 316 |
Whenever I try to drop database I get the following error:
ERROR: database "pilot" is being accessed by other users
DETAIL: There is 1 other session using the database.
When I use:
SELECT pg_terminate_backend(pg_stat_activity.pid)
FROM pg_stat_activity
WHERE pg_stat_activity.datname = 'TARGET_DB';
I terminated the ... | Postgres 13+
Use WITH (force)
See https://stackoverflow.com/a/68982312/398670 instead
Postgres 12 and older
You can prevent future connections with:
REVOKE CONNECT ON DATABASE thedb FROM public;
(and possibly other users/roles; see \l+ in psql)
You can then terminate all connections to this db except your own:
SELECT ... | PostgreSQL | 17,449,420 | 313 |
Upon restarting my Mac I got the dreaded Postgres error:
psql: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
The reason this happened is because my macbook froze completely due to an unrelated... | WARNING: If you delete postmaster.pid without making sure there are really no postgres processes running you, could permanently corrupt your database. (PostgreSQL should delete it automatically if the postmaster has exited.).
SOLUTION: This fixed the issue--I deleted this file, and then everything worked!
/usr/local/va... | PostgreSQL | 13,573,204 | 311 |
Using Postgres 9.0, I need a way to test if a value exists in a given array. So far I came up with something like this:
select '{1,2,3}'::int[] @> (ARRAY[]::int[] || value_variable::int)
But I keep thinking there should be a simpler way to this, I just can't see it. This seems better:
select '{1,2,3}'::int[] @> ARRAY[... | Simpler with the ANY construct:
SELECT value_variable = ANY ('{1,2,3}'::int[])
The right operand of ANY (between parentheses) can either be a set (result of a subquery, for instance) or an array. There are several ways to use it:
SQLAlchemy: how to filter on PgArray column types?
IN vs ANY operator in PostgreSQL
Imp... | PostgreSQL | 11,231,544 | 309 |
I'm sure this is a duplicate question in the sense that the answer is out there somewhere, but I haven't been able to find the answer after Googling for 10 minutes, so I'd appeal to the editors not to close it on the basis that it might well be useful for other people.
I'm using Postgres 9.5. This is my table:
... | This should work:
select * from mytable where 'Journal'=ANY(pub_types);
i.e. the syntax is <value> = ANY ( <array> ). Also notice that string literals in postresql are written with single quotes.
| PostgreSQL | 39,643,454 | 308 |
I have a database schema named: nyummy and a table named cimory:
create table nyummy.cimory (
id numeric(10,0) not null,
name character varying(60) not null,
city character varying(50) not null,
CONSTRAINT cimory_pkey PRIMARY KEY (id)
);
I want to export the cimory table's data as insert SQL script file. Howev... | Create a table with the set you want to export and then use the command line utility pg_dump to export to a file:
create table export_table as
select id, name, city
from nyummy.cimory
where city = 'tokyo'
$ pg_dump --table=export_table --data-only --column-inserts my_database > data.sql
--column-inserts will dump as... | PostgreSQL | 12,815,496 | 301 |
I have a bunch of rows that I need to insert into table, but these inserts are always done in batches. So I want to check if a single row from the batch exists in the table because then I know they all were inserted.
So its not a primary key check, but shouldn't matter too much. I would like to only check single row so... | Use the EXISTS keyword for TRUE / FALSE return:
SELECT EXISTS(SELECT 1 FROM contact WHERE id=12)
| PostgreSQL | 7,471,625 | 301 |
I have a table with existing data. Is there a way to add a primary key without deleting and re-creating the table?
| (Updated - Thanks to the people who commented)
Modern Versions of PostgreSQL
Suppose you have a table named test1, to which you want to add an auto-incrementing, primary-key id (surrogate) column. The following command should be sufficient in recent versions of PostgreSQL:
ALTER TABLE test1 ADD COLUMN id SERIAL PRIM... | PostgreSQL | 2,944,499 | 301 |
I either forgot or mistyped (during the installation) the password to the default user of PostgreSQL. I can't seem to be able to run it, and I get the following error:
psql: FATAL: password authentication failed for user "hisham"
hisham-agil: hisham$ psql
Is there a way to reset the password or how do I create a new ... |
Find the file pg_hba.conf. It may be located, for example, in /etc/postgresql-9.1/pg_hba.conf.
cd /etc/postgresql-9.1/
Back it up
cp pg_hba.conf pg_hba.conf-backup
Place the following line (as either the first uncommented line, or as the only one):
For all occurrence of below (local and host) , except replication
s... | PostgreSQL | 10,845,998 | 300 |
I've recently been playing around with Docker and QGIS and have installed a container following the instructions in this tutorial.
Everything works great, although I am unable to connect to a localhost postgres database that contains all my GIS data. I figure this is because my postgres database is not configured to ac... | TL;DR
Use 172.17.0.0/16 as IP address range, not 172.17.0.0/32.
Don't use localhost to connect to the PostgreSQL database on your host, but the host's IP instead. To keep the container portable, start the container with the --add-host=database:<host-ip> flag and use database as hostname for connecting to PostgreSQL.
M... | PostgreSQL | 31,249,112 | 299 |
I am testing Postgres insertion performance. I have a table with one column with number as its data type. There is an index on it as well. I filled the database up using this query:
insert into aNumber (id) values (564),(43536),(34560) ...
I inserted 4 million rows very quickly 10,000 at a time with the query above. A... | See populate a database in the PostgreSQL manual, depesz's excellent-as-usual article on the topic, and this SO question.
(Note that this answer is about bulk-loading data into an existing DB or to create a new one. If you're interested DB restore performance with pg_restore or psql execution of pg_dump output, much of... | PostgreSQL | 12,206,600 | 299 |
I have a table in PostgreSQL where the schema looks like this:
CREATE TABLE "foo_table" (
"id" serial NOT NULL PRIMARY KEY,
"permalink" varchar(200) NOT NULL,
"text" varchar(512) NOT NULL,
"timestamp" timestamp with time zone NOT NULL
)
Now I want to make the permalink unique across the table by ALTER-... | I figured it out from the PostgreSQL docs, the exact syntax is:
ALTER TABLE the_table ADD CONSTRAINT constraint_name UNIQUE (thecolumn);
Thanks Fred.
| PostgreSQL | 469,471 | 298 |
Entering the following command into a PostgreSQL interactive terminal results in an error:
ALTER TABLE tbl_name ALTER COLUMN col_name varchar (11);
What is the correct command to alter the data type of a column?
| See documentation here: http://www.postgresql.org/docs/current/interactive/sql-altertable.html
ALTER TABLE tbl_name ALTER COLUMN col_name TYPE varchar (11);
| PostgreSQL | 7,162,903 | 297 |
In postgresql, how do I replace all instances of a string within a database column?
Say I want to replace all instances of cat with dog, for example.
What's the best way to do this?
| You want to use postgresql's replace function:
replace(string text, from text, to text)
for instance :
UPDATE <table> SET <field> = replace(<field>, 'cat', 'dog')
Be aware, though, that this will be a string-to-string replacement, so 'category' will become 'dogegory'. the regexp_replace function may help you define a... | PostgreSQL | 5,060,526 | 296 |
What is the best way to list all of the tables within PostgreSQL's information_schema?
To clarify: I am working with an empty DB (I have not added any of my own tables), but I want to see every table in the information_schema structure.
| You should be able to just run select * from information_schema.tables to get a listing of every table being managed by Postgres for a particular database.
You can also add a where table_schema = 'information_schema' to see just the tables in the information schema.
| PostgreSQL | 2,276,644 | 292 |
Is there a way to create a backup of a single table within a database using postgres? And how? Does this also work with the pg_dump command?
| Use --table to tell pg_dump what table it has to backup:
pg_dump --host localhost --port 5432 --username postgres --format plain --verbose --file "<abstract_file_path>" --table public.tablename dbname
| PostgreSQL | 3,682,866 | 288 |
How do I create crosstab queries in PostgreSQL? For example I have the following table:
Section Status Count
A Active 1
A Inactive 2
B Active 4
B Inactive 5
I would like the query to return the following crosstab:
Section Active Inactive
A 1 2
B ... | Install the additional module tablefunc once per database, which provides the function crosstab(). Since Postgres 9.1 you can use CREATE EXTENSION for that:
CREATE EXTENSION IF NOT EXISTS tablefunc;
Improved test case
CREATE TABLE tbl (
section text
, status text
, ct integer -- "count" is a reserved... | PostgreSQL | 3,002,499 | 282 |
I would like to get the columns that an index is on in PostgreSQL.
In MySQL you can use SHOW INDEXES FOR table and look at the Column_name column.
mysql> show indexes from foos;
+-------+------------+---------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+... | Create some test data...
create table test (a int, b int, c int, constraint pk_test primary key(a, b));
create table test2 (a int, b int, c int, constraint uk_test2 unique (b, c));
create table test3 (a int, b int, c int, constraint uk_test3b unique (b), constraint uk_test3c unique (c),constraint uk_test3ab unique (a, ... | PostgreSQL | 2,204,058 | 282 |
I do not know the service's name, but would like to stop the service by checking its status.
For example, if I want to check if the PostgreSQL service is running or not, but I don't know the service's name, then how could I check its status?
I know the command to check the status if the service name is known.
| I don't have an Ubuntu box, but on Red Hat Linux you can see all running services by running the following command:
service --status-all
On the list the + indicates the service is running, - indicates service is not running, ? indicates the service state cannot be determined.
| PostgreSQL | 18,721,149 | 280 |
I have a column of the TIMESTAMP WITHOUT TIME ZONE type and would like to have that default to the current time in UTC. Getting the current time in UTC is easy:
postgres=# select now() at time zone 'utc';
timezone
----------------------------
2013-05-17 12:52:51.337466
(1 row)
As is using the curr... | A function is not even needed. Just put parentheses around the default expression:
create temporary table test(
id int,
ts1 timestamp default (now() at time zone 'utc')
-- alternative syntax
ts2 timestamp default (timezone('utc', now())),
);
NOTE: The SQL standard requires that writing just timestamp... | PostgreSQL | 16,609,724 | 278 |
Is this proper postgresql syntax to add a column to a table with a default value of false
ALTER TABLE users
ADD "priv_user" BIT
ALTER priv_user SET DEFAULT '0'
Thanks!
| ALTER TABLE users
ADD COLUMN "priv_user" BOOLEAN DEFAULT FALSE;
you can also directly specify NOT NULL
ALTER TABLE users
ADD COLUMN "priv_user" BOOLEAN NOT NULL DEFAULT FALSE;
UPDATE: following is only true for versions before postgresql 11.
As Craig mentioned on filled tables it is more efficient to split it int... | PostgreSQL | 11,938,621 | 278 |
I have the following table:
tickername | tickerbbname | tickertype
------------+---------------+------------
USDZAR | USDZAR Curncy | C
EURCZK | EURCZK Curncy | C
EURPLN | EURPLN Curncy | C
USDBRL | USDBRL Curncy | C
USDTRY | USDTRY Curncy | C
EURHUF | EURHUF Curncy | C
USDRUB | USD... | psql's inline help:
\h ALTER TABLE
Also documented in the postgres docs (an excellent resource, plus easy to read, too).
ALTER TABLE tablename ADD CONSTRAINT constraintname UNIQUE (columns);
| PostgreSQL | 1,194,438 | 277 |
Trying to create this example table structure in Postgres 9.1:
CREATE TABLE foo (
name VARCHAR(256) PRIMARY KEY
);
CREATE TABLE bar (
pkey SERIAL PRIMARY KEY,
foo_fk VARCHAR(256) NOT NULL REFERENCES foo(name),
name VARCHAR(256) NOT NULL,
UNIQUE (foo_fk,name)
);
CREATE T... | It's because the name column on the bar table does not have the UNIQUE constraint.
So imagine you have 2 rows on the bar table that contain the name 'ams' and you insert a row on baz with 'ams' on bar_fk, which row on bar would it be referring since there are two rows matching?
| PostgreSQL | 11,966,420 | 274 |
As I can understand documentation the following definitions are equivalent:
create table foo (
id serial primary key,
code integer,
label text,
constraint foo_uq unique (code, label));
create table foo (
id serial primary key,
code integer,
label text);
create unique index foo_idx on foo us... | I had some doubts about this basic but important issue, so I decided to learn by example.
Let's create test table master with two columns, con_id with unique constraint and ind_id indexed by unique index.
create table master (
con_id integer unique,
ind_id integer
);
create unique index master_unique_idx on mas... | PostgreSQL | 23,542,794 | 271 |
Is there an easy way to see the code used to create a view using the PostgreSQL command-line client?
Something like the SHOW CREATE VIEW from MySQL.
| Kept having to return here to look up pg_get_viewdef (how to remember that!!), so searched for a more memorable command... and got it:
\d+ viewname
You can see similar sorts of commands by typing \? at the pgsql command line.
Bonus tip: The emacs command sql-postgres makes pgsql a lot more pleasant (edit, copy, paste,... | PostgreSQL | 14,634,322 | 271 |
I need to take the first N rows for each group, ordered by custom column.
Given the following table:
db=# SELECT * FROM xxx;
id | section_id | name
----+------------+------
1 | 1 | A
2 | 1 | B
3 | 1 | C
4 | 1 | D
5 | 2 | E
6 | 2 | F
7 | 3 | G... | New solution (PostgreSQL 8.4)
SELECT
*
FROM (
SELECT
ROW_NUMBER() OVER (PARTITION BY section_id ORDER BY name) AS r,
t.*
FROM
xxx t) x
WHERE
x.r <= 2;
| PostgreSQL | 1,124,603 | 270 |
I'm getting the following error when running a query on a PostgreSQL db in standby mode. The query that causes the error works fine for 1 month but when you query for more than 1 month an error results.
ERROR: canceling statement due to conflict with recovery
Detail: User query might have needed to see row versions tha... | No need to touch hot_standby_feedback. As others have mentioned, setting it to on can bloat master. Imagine opening a transaction on a slave and not closing it.
Instead, set max_standby_archive_delay and max_standby_streaming_delay to sane values:
# /etc/postgresql/10/main/postgresql.conf on a slave
max_standby_archive... | PostgreSQL | 14,592,436 | 269 |
I am new to message brokers like RabbitMQ which we can use to create tasks / message queues for a scheduling system like Celery.
Now, here is the question:
I can create a table in PostgreSQL which can be appended with new tasks and consumed by the consumer program like Celery.
Why on earth would I want to setup a whol... | Rabbit's queues reside in memory and will therefore be much faster than implementing this in a database. A (good)dedicated message queue should also provide essential queuing related features such as throttling/flow control, and the ability to choose different routing algorithms, to name a couple(rabbit provides these ... | PostgreSQL | 13,005,410 | 268 |
I need to know the number of rows in a table to calculate a percentage. If the total count is greater than some predefined constant, I will use the constant value. Otherwise, I will use the actual number of rows.
I can use SELECT count(*) FROM table. But if my constant value is 500,000 and I have 5,000,000,000 rows in ... | Counting rows in big tables is known to be slow in PostgreSQL. The MVCC model requires a full count of live rows for a precise number. There are workarounds to speed this up dramatically if the count does not have to be exact like it seems to be in your case.
(Remember that even an "exact" count is potentially dead on ... | PostgreSQL | 7,943,233 | 267 |
I have a db table say, persons in Postgres handed down by another team that has a column name say, "first_Name". Now am trying to use PG commander to query this table on this column-name.
select * from persons where first_Name="xyz";
And it just returns
ERROR: column "first_Name" does not exist
Not sure if I am doi... | Identifiers (including column names) that are not double-quoted are folded to lower case in PostgreSQL. Identifiers created with double quotes retain upper case letters (and/or syntax violations) and have to be double-quoted for the rest of their life:
"first_Name" -- upper-case "N" preserved
"1st_Name"... | PostgreSQL | 20,878,932 | 265 |
I have a table to store information about my rabbits. It looks like this:
create table rabbits (rabbit_id bigserial primary key, info json not null);
insert into rabbits (info) values
('{"name":"Henry", "food":["lettuce","carrots"]}'),
('{"name":"Herald","food":["carrots","zucchini"]}'),
('{"name":"Helen", "food"... | As of PostgreSQL 9.4, you can use the ? operator:
select info->>'name' from rabbits where (info->'food')::jsonb ? 'carrots';
You can even index the ? query on the "food" key if you switch to the jsonb type instead:
alter table rabbits alter info type jsonb using info::jsonb;
create index on rabbits using gin ((info->'... | PostgreSQL | 19,925,641 | 265 |
I am looking for some docs and/or examples for the new JSON functions in PostgreSQL 9.2.
Specifically, given a series of JSON records:
[
{name: "Toby", occupation: "Software Engineer"},
{name: "Zaphod", occupation: "Galactic President"}
]
How would I write the SQL to find a record by name?
In vanilla SQL:
SELECT ... | Postgres 9.2
I quote Andrew Dunstan on the pgsql-hackers list:
At some stage there will possibly be some json-processing (as opposed
to json-producing) functions, but not in 9.2.
Doesn't prevent him from providing an example implementation in PLV8 that should solve your problem. (Link is dead now, see modern PLV8 ins... | PostgreSQL | 10,560,394 | 264 |
I am using Datagrip for Postgresql. I have a table with a date field in timestamp format (ex: 2016-11-01 00:00:00). I want to be able to:
apply a mathematical operator to subtract 1 day
filter it based on a time window of today-130 days
display it without the hh/mm/ss part of the stamp (2016-10-31)
Current startin... | Use the INTERVAL type to it. E.g:
--yesterday
SELECT NOW() - INTERVAL '1 DAY';
--Unrelated: PostgreSQL also supports some interesting shortcuts:
SELECT
'yesterday'::TIMESTAMP,
'tomorrow'::TIMESTAMP,
'allballs'::TIME AS aka_midnight;
You can do the following then:
SELECT
org_id,
count(accounts)... | PostgreSQL | 46,079,791 | 263 |
When I try to test any app with command (I noticed it when I tried to deploy myproject using fabric, which uses this command):
python manage.py test appname
I get this error:
Creating test database for alias 'default'...
Got an error creating the test database: permission denied to create database
Type 'yes' if you w... | When Django runs the test suite, it creates a new database, in your case test_finance. The postgres user with username django does not have permission to create a database, hence the error message.
When you run migrate or syncdb, Django does not try to create the finance database, so you don't get any errors.
You can a... | PostgreSQL | 14,186,055 | 263 |
Hello I want to delete all data in my postgresql tables, but not the table itself.
How could I do this?
| Use the TRUNCATE TABLE command.
| PostgreSQL | 13,223,820 | 263 |
How do I convert an integer to string as part of a PostgreSQL query?
So, for example, I need:
SELECT * FROM table WHERE <some integer> = 'string of numbers'
where <some integer> can be anywhere from 1 to 15 digits long.
| Because the number can be up to 15 digits, you'll need to cast to an 64 bit (8-byte) integer. Try this:
SELECT * FROM table
WHERE myint = mytext::int8
The :: cast operator is historical but convenient. Postgres also conforms to the SQL standard syntax
myint = cast ( mytext as int8)
If you have literal text you want ... | PostgreSQL | 13,809,547 | 262 |
For pagination purposes, I need a run a query with the LIMIT and OFFSET clauses. But I also need a count of the number of rows that would be returned by that query without the LIMIT and OFFSET clauses.
I want to run:
SELECT * FROM table WHERE /* whatever */ ORDER BY col1 LIMIT ? OFFSET ?
And:
SELECT COUNT(*) FROM tabl... | Yes. With a simple window function.
Add a column with the total count
SELECT *, count(*) OVER() AS full_count
FROM tbl
WHERE /* whatever */
ORDER BY col1
OFFSET ?
LIMIT ?
Be aware that the cost will be substantially higher than without the total number. Postgres has to actually count all qualifying rows either way... | PostgreSQL | 28,888,375 | 260 |
Could you tell me how to check what indexes are created for some table in postgresql ?
| The view pg_indexes provides access to useful information about each index in the database, e.g.:
select *
from pg_indexes
where tablename = 'test'
The pg_index system view contains more detailed (internal) parameters, in particular, whether the index is a primary key or whether it is unique. Example:
select
c.re... | PostgreSQL | 37,329,561 | 259 |
I would like to generate an entity-relationship diagram (ERD) from an existing PostgreSQL database.
What is the recommended approach to do this?
Are there any built-in tools to do it? Or third-party alternatives?
| You can use DBeaver Community to do this.
It's really easy... on the left just open one of your Databases:
Click on Schemas -> Public -> Tables
On Tables right click, and look for "View Diagram"
It also allows you to print your ER diagram and export as an image (png, gif, bmp formats) or as a file in GraphML format. ... | PostgreSQL | 3,474,389 | 259 |
I've got two postgresql tables:
table name column names
----------- ------------------------
login_log ip | etc.
ip_location ip | location | hostname | etc.
I want to get every IP address from login_log which doesn't have a row in ip_location.
I tried this query but it throws a syntax error.
SELECT lo... | There are basically 4 techniques for this task, all of them standard SQL.
NOT EXISTS
Often fastest in Postgres.
SELECT ip
FROM login_log l
WHERE NOT EXISTS (
SELECT -- SELECT list mostly irrelevant; can just be empty in Postgres
FROM ip_location
WHERE ip = l.ip
);
Also consider:
What is easier to... | PostgreSQL | 19,363,481 | 258 |
I have PSQL running, and am trying to get a perl application connecting to the database. Is there a command to find the current port and host that the database is running on?
| SELECT *
FROM pg_settings
WHERE name = 'port';
| PostgreSQL | 5,598,517 | 258 |
I have a simple SQL query in PostgreSQL 8.3 that grabs a bunch of comments. I provide a sorted list of values to the IN construct in the WHERE clause:
SELECT * FROM comments WHERE (comments.id IN (1,3,2,4));
This returns comments in an arbitrary order which in my happens to be ids like 1,2,3,4.
I want the resulting ro... | You can do it quite easily with (introduced in PostgreSQL 8.2) VALUES (), ().
Syntax will be like this:
select c.*
from comments c
join (
values
(1,1),
(3,2),
(2,3),
(4,4)
) as x (id, ordering) on c.id = x.id
order by x.ordering
| PostgreSQL | 866,465 | 257 |
I would like to have PostgreSQL return the result of a query as one JSON array. Given
create table t (a int primary key, b text);
insert into t values (1, 'value1');
insert into t values (2, 'value2');
insert into t values (3, 'value3');
I would like something similar to
[{"a":1,"b":"value1"},{"a":2,"b":"value2"},{"a... | TL;DR
SELECT json_agg(t) FROM t
for a JSON array of objects, and
SELECT
json_build_object(
'a', json_agg(t.a),
'b', json_agg(t.b)
)
FROM t
for a JSON object of arrays.
List of objects
This section describes how to generate a JSON array of objects, with each row being converted to a single obj... | PostgreSQL | 24,006,291 | 256 |
In PostgreSQL 8 is it possible to add ON DELETE CASCADES to the both foreign keys in the following table without dropping the latter?
# \d scores
Table "public.scores"
Column | Type | Modifiers
---------+-----------------------+-----------
id | character varying(32) |
gid | integer... | I'm pretty sure you can't simply add on delete cascade to an existing foreign key constraint. You have to drop the constraint first, then add the correct version. In standard SQL, I believe the easiest way to do this is to
start a transaction,
drop the foreign key,
add a foreign key with on delete cascade, and finall... | PostgreSQL | 10,356,484 | 256 |
Very simple example - one table, one index, one query:
CREATE TABLE book
(
id bigserial NOT NULL,
"year" integer,
-- other columns...
);
CREATE INDEX book_year_idx ON book (year)
EXPLAIN
SELECT *
FROM book b
WHERE b.year > 2009
gives me:
Seq Scan on book b (cost=0.00..25663.80 rows=105425 width=622)
F... | If the SELECT returns more than approximately 5-10% of all rows in the table, a sequential scan is much faster than an index scan.
This is because an index scan requires several IO operations for each row (look up the row in the index, then retrieve the row from the heap). Whereas a sequential scan only requires a si... | PostgreSQL | 5,203,755 | 256 |
How do I find the maximum (or minimum) of two integers in Postgres/SQL? One of the integers is not a column value.
I will give an example scenario:
I would like to subtract an integer from a column (in all rows), but the result should not be less than zero. So, to begin with, I have:
UPDATE my_table
SET my_column = my_... | Have a look at GREATEST and LEAST.
UPDATE my_table
SET my_column = GREATEST(my_column - 10, 0);
| PostgreSQL | 2,936,348 | 256 |
I'm coming to Postgres from Oracle and looking for a way to find the table and index size in terms of bytes/MB/GB/etc, or even better the size for all tables. In Oracle I had a nasty long query that looked at user_lobs and user_segments to give back an answer.
I assume in Postgres there's something I can use in the in... | Try the Database Object Size Functions. An example:
SELECT pg_size_pretty(pg_total_relation_size('"<schema>"."<table>"'));
For all tables, something along the lines of:
SELECT
table_schema || '.' || table_name AS table_full_name,
pg_size_pretty(pg_total_relation_size('"' || table_schema || '"."' || table_name ... | PostgreSQL | 2,596,624 | 255 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.