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 would like to know if there is support for OFFSET in AWS Athena. For mysql the following query is running but in athena it is giving me error. Any example would be helpful.
select * from employee where empSal >3000 LIMIT 300 OFFSET 20
| Athena is basically managed Presto. Since Presto 311 you can use OFFSET m LIMIT n syntax or ANSI SQL equivalent: OFFSET m ROWS FETCH NEXT n ROWS ONLY.
You can read more in Beyond LIMIT, Presto meets OFFSET and TIES.
For older versions (and this includes AWS Athena as of this writing), you can use row_number() window f... | Presto | 51,298,622 | 12 |
I have 3 tables I would like to work on using the date, however one of the tables includes the date in unix epoch format. Here is an example of the 3 fields:
Table1: 2017-02-01T07:58:40.756031Z
Table2: 2017-02-07T10:16:46Z
Table3: 1489236559
I would like to convert the date in table 3 to match the format of table 2 as... | Option 1: date_format
presto> select date_format(from_unixtime(1489236559),'%Y-%m-%dT%H:%i:%sZ');
_col0
----------------------
2017-03-11T12:49:19Z
Option 2: to_iso8601
presto> select to_iso8601(from_unixtime(1489236559));
_col0
--------------------------
2017-03-11T12:49:19.000Z
| Presto | 42,927,726 | 11 |
I am trying to search a column having the data type map(varchar,varchar). Now one way to access the column is to use this structure, name_of_column['key'], which will give the value for that key. But I want to know what are possible keys and then apply group by and other operations based on those keys.
I tried searchi... | Presto offers map_keys function for that:
presto> select map_keys(map(array['alice'], array['has a cat']));
_col0
---------
[alice]
(1 row)
| Presto | 45,096,736 | 11 |
I have a query that produces strings of arrays using they array_agg() function
SELECT
array_agg(message) as sequence
from mytable
group by id
which produces a table that looks like this:
sequence
1 foo foo bar baz bar baz
2 foo bar bar bar baz
3 foo foo foo bar bar baz
but I aim to condense the ... | You can do this in one of two ways:
Remove duplicates from the resulting arrays using the array_distinct function:
WITH mytable(id, message) AS (VALUES
(1, 'foo'), (1, 'foo'), (1, 'bar'), (1, 'bar'), (1, 'baz'), (1, 'baz'),
(2, 'foo'), (2, 'bar'), (2, 'bar'), (2, 'bar'), (2, 'baz'),
(3, 'foo'), (3, 'foo'), (3, ... | Presto | 56,349,907 | 11 |
I suspect the answer is "it depends", but is there any general guidance about what kind of hardware to plan to use for Presto?
Since Presto uses a coordinator and a set of workers, and workers run with the data, I imagine the main issues will be having sufficient RAM for the coordinator, sufficient network bandwidth ... | Most people are running Trino (formerly PrestoSQL) on the Hadoop nodes they already have. At Facebook we typically run Presto on a few nodes within the Hadoop cluster to spread out the network load.
Generally, I'd go with the industry standard ratios for a new cluster: 2 cores and 2-4 gig of memory for each disk, with... | Presto | 19,863,857 | 10 |
I'm using Presto(0.163) to query data and am trying to extract fields from a json.
I have a json like the one given below, which is present in the column 'style_attributes':
"attributes": {
"Brand Fit Name": "Regular Fit",
"Fabric": "Cotton",
"Fit": "Regular",
"Neck or Collar": "Round Neck",
"Occasi... | presto:default> select json_extract_scalar('{"attributes":{"Sleeve Length": "Short Sleeves"}}','$.attributes["Sleeve Length"]');
_col0
---------------
Short Sleeves
or
presto:default> select json_extract_scalar('{"attributes":{"Sleeve Length": "Short Sleeves"}}','$["attributes"]["Sleeve Length"]');
_col0
--... | Presto | 43,271,898 | 10 |
I am working with some course data in a Presto database. The data in the table looks like:
student_id period score completed
1 2016_Q1 3 Y
1 2016_Q3 4 Y
3 2017_Q1 4 Y
4 2018_Q1 2 N
I would like to format the data so that it looks like:
student_id 2018_Q1_... | You can just use conditional aggregation:
select student_id,
max(case when period = '2018_Q1' then score else 0 end) as score_2018q1,
max(case when period = '2018_Q1' then completed then 'N' end) as completed_2018q1,
max(case when period = '2017_Q3' then score else 0 end) as score_2017q3
from t
gro... | Presto | 51,372,566 | 10 |
I'm querying some tables on Athena (Presto SAS) and then downloading the generated CSV file to use locally. Opening the file, I realised the data contains new line characters that doesn't appear on AWS interface, only in the CSV and need to get rid of them. Tried using the function replace(string, search, replace) → va... | The problem was that the underlying table data doesn't actually contains \n anywhere, instead, the actual newline character, which is represented by char(10). I was able to achieve the expected behaviour using the replace function passing it as parameter:
SELECT
p.recvepoch, replace(p.description, chr(10), '\n') AS... | Presto | 56,001,003 | 10 |
SELECT sales_invoice_date,
MONTH( DATE_TRUNC('month',
CASE
WHEN TRIM(sales_invoice_date) = '' THEN
DATE('1999-12-31')
ELSE
DATE_PARSE(sales_invoice_date, '%m/%d/%Y')
... | Athena is currently based on Presto .172, so you should refer to https://trino.io/docs/0.172/functions/datetime.html for available functions on date/time values.
You can get month name with date_format():
date_format(value, '%M')
or similarly format_datetime().
format_datetime(value, 'MMM')
Example:
presto:default> S... | Presto | 59,485,913 | 10 |
I have a very basic group by query in Athena where I would like to use an alias. One can make the example work by putting the same reference in the group by, but that's not really handy when there's complex column modifications going on and logic needs to be copied in two places. Also I did that in the past and now I h... | That is because SQL is evaluated in certain order, like table scan, filter, aggregation, projection, sort. You tried to use the result of projection as input of aggregation. In many cases it could be possible (where projection is trivial, like your case), but it such behaviour is not defined in ANSI SQL (which Presto a... | Presto | 60,142,810 | 10 |
I have the following query:
select id, table1.date1, table2.date2, table1.name
from table1
join table2 using (id)
I want also to have another column with MAX(table1.date1, table2.date2) but I don't find the proper syntax for that. I don't want MAX to go over all rows in table and take MAX() I want it to select max fro... | Use greatest():
select id, t1.date1, t2.date2, t1.name,
greatest(t1.date1, t2.date2)
from table1 t1 join
table2 t2
using (id);
Note that greatest() returns NULL if any argument is NULL. So, if you have NULL values, you will need special care.
| Presto | 61,919,230 | 10 |
I'm looking for a function in Presto to concat two columns with a separator like underline.
| Your are looking here for the array_join function, see docs.
array_join(x, delimiter, null_replacement) → varchar
Concatenates the elements of the given array using the
delimiter and an optional string to replace nulls.
Example:
columns are c1,c2 you can add more of course:
WITH demo_table (c1,c2) AS
(SELECT *... | Presto | 62,868,039 | 10 |
I want to query a column in my table using a LIKE condition and this works fine-
select * from my_table where my_column LIKE '%hello%';
But, how do I query this column with multiple strings in my LIKE condition? Looking for something like-
select * from my_table where my_column LIKE ['%hello%'|'example%'|'%random%'|'%... | Use regexp_like():
select *
from my_table
where regexp_like(my_column, 'hello|example|random|demo');
| Presto | 64,780,028 | 10 |
After upgrading MySQL to 5.7.8-rc
and loging to server I got error:
Table 'performance_schema.session_variables' doesn't exist
I can't find any solution for this. Can you help ?
| I was able to log on to the mysql server after running the command @robregonm suggested:
mysql_upgrade -u root -p --force
A MySQL server restart is required.
| MySQL | 31,967,527 | 333 |
I'm working with map data, and the Latitude/Longitude extends to 8 decimal places. For example:
Latitude 40.71727401
Longitude -74.00898606
I saw in the Google document
which uses:
lat FLOAT( 10, 6 ) NOT NULL,
lng FLOAT( 10, 6 ) NOT NULL
however, their decimal places only go to 6.
Should I use FLOAT(10, 8) or is ... | MySQL supports Spatial data types and Point is a single-value type which can be used. Example:
CREATE TABLE `buildings` (
`coordinate` POINT NOT NULL,
/* Even from v5.7.5 you can define an index for it */
SPATIAL INDEX `SPATIAL` (`coordinate`)
) ENGINE=InnoDB;
/* then for insertion you can */
INSERT INTO `buildi... | MySQL | 12,504,208 | 331 |
I have two tables, both looking like
id name value
===================
1 Joe 22
2 Derk 30
I need to copy the value of value from tableA to tableB based on check name in each table.
Any tips for this UPDATE statement?
| In addition to this answer if you need to change tableB.value according to tableA.value dynamically you can do for example:
UPDATE tableB
INNER JOIN tableA ON tableB.name = tableA.name
SET tableB.value = IF(tableA.value > 0, tableA.value, tableB.value)
WHERE tableA.name = 'Joe'
| MySQL | 11,709,043 | 330 |
This is how my connection is set:
Connection conn = DriverManager.getConnection(url + dbName + "?useUnicode=true&characterEncoding=utf-8", userName, password);
And I'm getting the following error when tyring to add a row to a table:
Incorrect string value: '\xF0\x90\x8D\x83\xF0\x90...' for column 'content' at row 1
I'm... | MySQL's utf8 permits only the Unicode characters that can be represented with 3 bytes in UTF-8. Here you have a character that needs 4 bytes: \xF0\x90\x8D\x83 (U+10343 GOTHIC LETTER SAUIL).
If you have MySQL 5.5 or later you can change the column encoding from utf8 to utf8mb4. This encoding allows storage of characters... | MySQL | 10,957,238 | 329 |
Is there any way to later output the name of the database that is currently selected?
| Just use mysql_query (or mysqli_query, even better, or use PDO, best of all) with:
SELECT DATABASE();
Addendum:
There is much discussion over whether or not FROM DUAL should be included in this or not. On a technical level, it is a holdover from Oracle and can safely be removed. If you are inclined, you can use it as... | MySQL | 8,096,550 | 329 |
I'm building a Django site and I am looking for a search engine.
A few candidates:
Lucene/Lucene with Compass/Solr
Sphinx
Postgresql built-in full text search
MySQl built-in full text search
Selection criteria:
result relevance and ranking
searching and indexing speed
ease of use and ease of integration with Django
... | Good to see someone's chimed in about Lucene - because I've no idea about that.
Sphinx, on the other hand, I know quite well, so let's see if I can be of some help.
Result relevance ranking is the default. You can set up your own sorting should you wish, and give specific fields higher weightings.
Indexing speed is su... | MySQL | 737,275 | 329 |
How do I use the json_encode() function with MySQL query results? Do I need to iterate through the rows or can I just apply it to the entire results object?
| $sth = mysqli_query($conn, "SELECT ...");
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
The function json_encode needs PHP >= 5.2 and the php-json package - as mentioned here
Modern PHP versions support mysqli_fetch_all() function that will get your array in one ... | MySQL | 383,631 | 329 |
In MySQL I am trying to copy a row with an autoincrement column ID=1 and insert the data into same table as a new row with column ID=2.
How can I do this in a single query?
| Use INSERT ... SELECT:
insert into your_table (c1, c2, ...)
select c1, c2, ...
from your_table
where id = 1
where c1, c2, ... are all the columns except id. If you want to explicitly insert with an id of 2 then include that in your INSERT column list and your SELECT:
insert into your_table (id, c1, c2, ...)
select 2, ... | MySQL | 9,156,340 | 328 |
I'm working on getting my database to talk to my Java programs.
Can someone give me a quick and dirty sample program using the JDBC?
I'm getting a rather stupendous error:
Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successful... | So, you have a
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
java.net.ConnectException: Connection refused
I'm quoting from this answer which also contains a step-by-step MySQL+JDBC tutorial:
If you get a SQLException: Connection refused or Connection timed out or a MySQL sp... | MySQL | 2,983,248 | 326 |
I would like to know the command to perform a mysqldump of a database without the prompt for the password.
REASON:
I would like to run a cron job, which takes a mysqldump of the database once everyday. Therefore, I won't be able to insert the password when prompted.
How could I solve this?
| Since you are using Ubuntu, all you need to do is just to add a file in your home directory and it will disable the mysqldump password prompting. This is done by creating the file ~/.my.cnf (permissions need to be 600).
Add this to the .my.cnf file
[mysqldump]
user=mysqluser
password=secret
This lets you connect as a ... | MySQL | 9,293,042 | 325 |
If I have a table
CREATE TABLE users (
id int(10) unsigned NOT NULL auto_increment,
name varchar(255) NOT NULL,
profession varchar(255) NOT NULL,
employer varchar(255) NOT NULL,
PRIMARY KEY (id)
)
and I want to get all unique values of profession field, what would be faster (or recommended):
SELECT DISTINCT... | They are essentially equivalent to each other (in fact this is how some databases implement DISTINCT under the hood).
If one of them is faster, it's going to be DISTINCT. This is because, although the two are the same, a query optimizer would have to catch the fact that your GROUP BY is not taking advantage of any gro... | MySQL | 581,521 | 325 |
I have a simple AJAX call, and the server will return either a JSON string with useful data or an error message string produced by the PHP function mysql_error(). How can I test whether this data is a JSON string or the error message.
It would be nice to use a function called isJSON just like you can use the functio... | Use JSON.parse
function isJson(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
| MySQL | 9,804,777 | 324 |
I'm having a problem where when I try to select the rows that have a NULL for a certain column, it returns an empty set. However, when I look at the table in phpMyAdmin, it says null for most of the rows.
My query looks something like this:
SELECT pid FROM planets WHERE userid = NULL
Empty set every time.
A lot of pla... | SQL NULL's special, and you have to do WHERE field IS NULL, as NULL cannot be equal to anything,
including itself (ie: NULL = NULL is always false).
See Rule 3 https://en.wikipedia.org/wiki/Codd%27s_12_rules
| MySQL | 3,536,670 | 324 |
I'm not sure how password hashing works (will be implementing it later), but need to create database schema now.
I'm thinking of limiting passwords to 4-20 characters, but as I understand after encrypting hash string will be of different length.
So, how to store these passwords in the database?
| Update: Simply using a hash function is not strong enough for storing passwords. You should read the answer from Gilles on this thread for a more detailed explanation.
For passwords, use a key-strengthening hash algorithm like Bcrypt or Argon2i. For example, in PHP, use the password_hash() function, which uses Bcrypt b... | MySQL | 247,304 | 324 |
Is it possible to do a select statement that takes only NOT NULL values?
Right now I am using this:
SELECT * FROM table
And then I have to filter out the null values with a php loop.
Is there a way to do:
SELECT * (that are NOT NULL) FROM table
?
Right now when I select * I get val1,val2,val3,null,val4,val5,null,null... | You should use IS NOT NULL. (The comparison operators = and <> both give UNKNOWN with NULL on either side of the expression.)
SELECT *
FROM table
WHERE YourColumn IS NOT NULL;
Just for completeness I'll mention that in MySQL you can also negate the null safe equality operator but this is not standard SQL.
SELECT *
F... | MySQL | 5,285,448 | 323 |
I have created a table and accidentally put varchar length as 300 instead of 65353. How can I fix that?
An example would be appreciated.
| Have you tried this?
ALTER TABLE <table_name> MODIFY <col_name> VARCHAR(65353);
This will change the col_name's type to VARCHAR(65353)
| MySQL | 1,279,568 | 322 |
Does MySQL index foreign key columns automatically?
| Yes, but only on innodb. Innodb is currently the only shipped table format that has foreign keys implemented.
| MySQL | 304,317 | 322 |
I'm going to run SHA256 on a password + salt, but I don't know how long to make my VARCHAR when setting up the MySQL database. What is a good length?
| A sha256 is 256 bits long -- as its name indicates.
Since sha256 returns a hexadecimal representation, 4 bits are enough to encode each character (instead of 8, like for ASCII), so 256 bits would represent 64 hex characters, therefore you need a varchar(64), or even a char(64), as the length is always the same, not var... | MySQL | 2,240,973 | 321 |
How do I enable the MySQL function that logs each SQL query statement received from clients and the time that query statement has submitted?
Can I do that in phpmyadmin or NaviCat?
How do I analyse the log?
| First, Remember that this logfile can grow very large on a busy server.
For mysql < 5.1.29:
To enable the query log, put this in /etc/my.cnf in the [mysqld] section
log = /path/to/query.log #works for mysql < 5.1.29
Also, to enable it from MySQL console
SET general_log = 1;
See http://dev.mysql.com/doc/refman/5.1/... | MySQL | 6,479,107 | 319 |
I know I can issue an alter table individually to change the table storage from MyISAM to InnoDB.
I am wondering if there is a way to quickly change all of them to InnoDB?
| Run this SQL statement (in the MySQL client, phpMyAdmin, or wherever) to retrieve all the MyISAM tables in your database.
Replace value of the name_of_your_db variable with your database name.
SET @DATABASE_NAME = 'name_of_your_db';
SELECT CONCAT('ALTER TABLE `', table_name, '` ENGINE=InnoDB;') AS sql_statements
FROM... | MySQL | 3,856,435 | 317 |
In MySQL, I have a table, and I want to set the auto_increment value to 5 instead of 1. Is this possible and what query statement does this?
| You can use ALTER TABLE to change the auto_increment initial value:
ALTER TABLE tbl AUTO_INCREMENT = 5;
See the MySQL reference for more details.
| MySQL | 970,597 | 317 |
I am getting the following error when I try to connect to mysql:
Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
Is there a solution for this error? What might be the reason behind it?
| Are you connecting to "localhost" or "127.0.0.1" ? I noticed that when you connect to "localhost" the socket connector is used, but when you connect to "127.0.0.1" the TCP/IP connector is used. You could try using "127.0.0.1" if the socket connector is not enabled/working.
| MySQL | 4,448,467 | 315 |
How do I write a script to install MySQL server on Ubuntu?
sudo apt-get install mysql will install, but it will also ask for a password to be entered in the console.
How do I do this in a non-interactive way? That is, write a script that can provide the password?
#!/bin/bash
sudo apt-get install mysql # To install My... | sudo debconf-set-selections <<< 'mysql-server mysql-server/root_password password your_password'
sudo debconf-set-selections <<< 'mysql-server mysql-server/root_password_again password your_password'
sudo apt-get -y install mysql-server
For specific versions, such as mysql-server-5.6, you'll need to specify the versio... | MySQL | 7,739,645 | 314 |
What does "unsigned" mean in MySQL and when should I use it?
| MySQL says:
All integer types can have an optional
(nonstandard) attribute UNSIGNED.
Unsigned type can be used to permit
only nonnegative numbers in a column
or when you need a larger upper
numeric range for the column. For
example, if an INT column is UNSIGNED,
the size of the column's range is the
sa... | MySQL | 3,895,692 | 314 |
How do I sort a MySQL table by two columns?
What I want are articles sorted by highest ratings first, then most recent date. As an example, this would be a sample output (left # is the rating, then the article title, then the article date)
+================+=============================+==============+
| article_rati... | Default sorting is ascending, you need to add the keyword DESC to both your orders:
ORDER BY article_rating DESC, article_time DESC
| MySQL | 514,943 | 314 |
I want to create a new user in MySQL with the syntax:
create user 'demo'@'localhost' identified by 'password';
But it returns an error:
Your password does not satisfy the current policy requirements.
I have tried many passwords but they don't work. How can I fix this?
| Because of your password. You can see password validate configuration metrics using the following query in MySQL client:
SHOW VARIABLES LIKE 'validate_password%';
The output should be something like that :
+--------------------------------------+-------+
| Variable_name | Value |
+--------------... | MySQL | 43,094,726 | 313 |
I really haven't found normal example of PHP file where MySQL transactions are being used. Can you show me simple example of that?
And one more question. I've already done a lot of programming and didn't use transactions. Can I put a PHP function or something in header.php that if one mysql_query fails, then the other... | The idea I generally use when working with transactions looks like this (semi-pseudo-code):
try {
// First of all, let's begin a transaction
$db->beginTransaction();
// A set of queries; if one fails, an exception should be thrown
$db->query('first query');
$db->query('second query');
$db->... | MySQL | 2,708,237 | 313 |
I have a MySQL database configured with the default collation utf8mb4_general_ci. When I try to insert a row containing an emoji character in the text using the following query
insert into tablename
(column1,column2,column3,column4,column5,column6,column7)
values
('273','3','Hdhdhdh😜😀😊😃hzhzhzzhjzj 我爱你 ❌',49,1,'2... | 1) Database: Change Database default collation as utf8mb4.
2) Table: Change table collation as CHARACTER SET utf8mb4 COLLATE utf8mb4_bin.
Query:
ALTER TABLE Tablename CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin
3) Code:
INSERT INTO tablename (column1, column2, column3, column4, column... | MySQL | 39,463,134 | 312 |
I connect to mysql from my Linux shell. Every now and then I run a SELECT query that is too big. It prints and prints and I already know this is not what I meant. I would like to stop the query.
Hitting Ctrl+C (a couple of times) kills mysql completely and takes me back to shell, so I have to reconnect.
Is it possibl... | mysql> show processlist;
+----+------+-----------+-----+---------+------+---------------------+------------------------------+----------+
| Id | User | Host | db | Command | Time | State | Info | Progress |
+----+------+-----------+-----+---------+------+---------------------... | MySQL | 3,787,651 | 312 |
Does anyone know if there is a function to obtain the server's time zone setting in MySQL?
UPDATE
This doesn't output any valid info:
mysql> SELECT @@global.time_zone, @@session.time_zone;
+--------------------+---------------------+
| @@global.time_zone | @@session.time_zone |
+--------------------+-------------------... | From the manual (section 9.6):
The current values of the global and client-specific time zones can be retrieved like this:
mysql> SELECT @@global.time_zone, @@session.time_zone;
Edit The above returns SYSTEM if MySQL is set to use the system's timezone, which is less than helpful. Since you're using PHP, if the answe... | MySQL | 2,934,258 | 308 |
I want to remove constraints from my table. My query is:
ALTER TABLE `tbl_magazine_issue`
DROP CONSTRAINT `FK_tbl_magazine_issue_mst_users`
But I got an error:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'constraint FK_... | Mysql has a special syntax for dropping foreign key constraints:
ALTER TABLE tbl_magazine_issue
DROP FOREIGN KEY FK_tbl_magazine_issue_mst_users
| MySQL | 14,122,031 | 305 |
I have a column of type "datetime" with values like 2009-10-20 10:00:00
I would like to extract date from datetime and write a query like:
SELECT * FROM
data
WHERE datetime = '2009-10-20'
ORDER BY datetime DESC
Is the following the best way to do it?
SELECT * FROM
data
WHERE datetime BETWEEN('2009-10-20 00:00:00'... | You can use MySQL's DATE() function:
WHERE DATE(datetime) = '2009-10-20'
You could also try this:
WHERE datetime LIKE '2009-10-20%'
See this answer for info on the performance implications of using LIKE.
| MySQL | 1,754,411 | 305 |
I tried to import a large sql file through phpMyAdmin...But it kept showing error
'MySql server has gone away'
What to do?
| As stated here:
Two most common reasons (and fixes) for the MySQL server has gone away
(error 2006) are:
Server timed out and closed the connection. How to fix:
check that wait_timeout variable in your mysqld’s my.cnf configuration file is large enough. On Debian: sudo nano
/etc/mysql/my.cnf, set wait_timeout = ... | MySQL | 12,425,287 | 304 |
table1 is the parent table with a column ID and table2 has a column IDFromTable1.
Why when I put a FK on IDFromTable1 to ID in table1 do I get Foreign key constraint is incorrectly formed error?
(I would like to delete the table2 record if the table1 record gets deleted.)
ALTER TABLE `table2`
ADD CONSTRAINT `FK1` ... | I ran into this same cryptic error. My problem was that the foreign key column and the referencing column were not of the same type or length.
The foreign key column was SMALLINT(5) UNSIGNED
The referenced column was INT(10) UNSIGNED
Once I made them both the same exact type, the foreign key creation worked perfectly.
| MySQL | 8,434,518 | 304 |
I was wondering what the difference between BigInt, MediumInt, and Int are... it would seem obvious that they would allow for larger numbers; however, I can make an Int(20) or a BigInt(20) and that would make seem that it is not necessarily about size.
Some insight would be awesome, just kind of curious. I have been us... | See http://dev.mysql.com/doc/refman/8.0/en/numeric-types.html
INT is a four-byte signed integer.
BIGINT is an eight-byte signed integer.
They each accept no more and no fewer values than can be stored in their respective number of bytes. That means 232 values in an INT and 264 values in a BIGINT.
The 20 in INT(20)... | MySQL | 3,135,804 | 304 |
I'm using a MySQL database.
In which situations should I create a unique key or a primary key?
| Primary Key:
There can only be one primary key constraint in a table
In some DBMS it cannot be NULL - e.g. MySQL adds NOT NULL
Primary Key is a unique key identifier of the record
Unique Key:
Can be more than one unique key in one table
Unique key can have NULL values
It can be a candidate key
Unique key can be NULL... | MySQL | 9,565,996 | 303 |
What MySQL query will do a text search and replace in one particular field in a table?
I.e. search for foo and replace with bar so a record with a field with the value hello foo becomes hello bar.
| Change table_name and field to match your table name and field in question:
UPDATE table_name SET field = REPLACE(field, 'foo', 'bar') WHERE INSTR(field, 'foo') > 0;
REPLACE (string functions)
INSTR (string functions)
| MySQL | 125,230 | 303 |
There are plenty of similar questions to be found on here but I don't think that any answer the question adequately.
I'll continue from the current most popular question and use their example if that's alright.
The task in this instance is to get the latest post for each author in the database.
The example query produc... | Using an ORDER BY in a subquery is not the best solution to this problem.
The best solution to get the max(post_date) by author is to use a subquery to return the max date and then join that to your table on both the post_author and the max date.
The solution should be:
SELECT p1.*
FROM wp_posts p1
INNER JOIN
(
... | MySQL | 14,770,671 | 301 |
Usually I use manual find to replace text in a MySQL database using phpMyAdmin. I'm tired of it now, how can I run a query to find and replace a text with new text in the entire table in phpMyAdmin?
Example: find keyword domain.example, replace with www.domain.example.
| For a single table update
UPDATE `table_name`
SET `field_name` = replace(same_field_name, 'unwanted_text', 'wanted_text')
From multiple tables-
If you want to edit from all tables, best way is to take the dump and then find/replace and upload it back.
| MySQL | 11,839,060 | 299 |
MySQL has an OPTIMIZE TABLE command which can be used to reclaim unused space in a MySQL install. Is there a way (built-in command or common stored procedure) to run this optimization for every table in the database and/or server install, or is this something you'd have to script up yourself?
| You can use mysqlcheck to do this at the command line.
One database:
mysqlcheck -o <db_schema_name>
All databases:
mysqlcheck -o --all-databases
| MySQL | 5,474,662 | 299 |
I am looking for the syntax to add a column to a MySQL database with a default value of 0
Reference
| Try this:
ALTER TABLE table1 ADD COLUMN foo INT DEFAULT 0;
From the documentation that you linked to:
ALTER [ONLINE | OFFLINE] [IGNORE] TABLE tbl_name
alter_specification [, alter_specification] ...
alter_specification:
...
ADD [COLUMN] (col_name column_definition,...)
...
To find the syntax for colu... | MySQL | 3,569,347 | 299 |
I'm trying to figure out what collation I should be using for various types of data. 100% of the content I will be storing is user-submitted.
My understanding is that I should be using UTF-8 General CI (Case-Insensitive) instead of UTF-8 Binary. However, I can't find a clear a distinction between UTF-8 General CI and U... | In general, utf8_general_ci is faster than utf8_unicode_ci, but less correct.
Here is the difference:
For any Unicode character set, operations performed using the _general_ci collation are faster than those for the _unicode_ci collation. For example, comparisons for the utf8_general_ci collation are faster, but slig... | MySQL | 2,344,118 | 297 |
I want to convert a timestamp in MySQL to a date.
I would like to format the user.registration field into the text file as a yyyy-mm-dd.
Here is my SQL:
$sql = requestSQL("SELECT user.email,
info.name,
FROM_UNIXTIME(user.registration),
info.news
... | DATE_FORMAT(FROM_UNIXTIME(`user.registration`), '%e %b %Y') AS 'date_formatted'
| MySQL | 9,251,561 | 296 |
How do I subtract 30 days from the current datetime in mysql?
SELECT * FROM table
WHERE exec_datetime BETWEEN DATEDIFF(NOW() - 30 days) AND NOW();
| SELECT * FROM table
WHERE exec_datetime BETWEEN DATE_SUB(NOW(), INTERVAL 30 DAY) AND NOW();
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add
| MySQL | 10,763,031 | 294 |
The database is latin1_general_ci now and I want to change collation to utf8mb4_general_ci.
Is there any setting in PhpMyAdmin to change collation of database, table, column? Rather than changing one by one?
| Changing for database:
ALTER DATABASE <database_name> CHARACTER SET utf8mb4
COLLATE utf8mb4_unicode_ci;
Note that it will only set a new default, that will be used for new tables created since, but wouldn't change for existing tables.
Changing it per table:
ALTER TABLE <table_name> CONVERT TO CHARACTER SET utf8mb... | MySQL | 1,294,117 | 294 |
Is a MySQL SELECT query case sensitive or case insensitive by default? And if not, what query would I have to send so that I can do something like the following?
SELECT * FROM `table` WHERE `Value` = "iaresavage"
Where in actuality, the real value of Value is IAreSavage.
| They are case insensitive, unless you do a binary comparison.
| MySQL | 3,936,967 | 293 |
I have a query that looks like this:
SELECT article FROM table1 ORDER BY publish_date LIMIT 20
How does ORDER BY work? Will it order all records, then get the first 20, or will it get 20 records and order them by the publish_date field?
If it's the last one, you're not guaranteed to really get the most recent 20 articl... | It will order first, then get the first 20. A database will also process anything in the WHERE clause before ORDER BY.
| MySQL | 4,708,708 | 291 |
My iPhone application connects to my PHP web service to retrieve data from a MySQL database, a request can return up to 500 results.
What is the best way to implement paging and retrieve 20 items at a time?
Let's say I receive the first 20 entries from my database, how can I now request the next 20 entries?
| From the MySQL documentation:
The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants (except when using prepared statements).
With two arguments, the first argument specifies the offset of... | MySQL | 3,799,193 | 291 |
I am trying to find a MySQL query that will find DISTINCT values in a particular field, count the number of occurrences of that value and then order the results by the count.
example db
id name
----- ------
1 Mark
2 Mike
3 Paul
4 Mike
5 Mike
6 John
7 ... | SELECT name,COUNT(*) as count
FROM tablename
GROUP BY name
ORDER BY count DESC;
| MySQL | 1,346,345 | 291 |
In a [member] table, some rows have the same value for the email column.
login_id | email
---------|---------------------
john | john123@hotmail.com
peter | peter456@gmail.com
johnny | john123@hotmail.com
...
Some people used a different login_id but the same email address, no unique constraint was set on thi... | This query will give you a list of email addresses and how many times they're used, with the most used addresses first.
SELECT email,
count(*) AS c
FROM TABLE
GROUP BY email
HAVING c > 1
ORDER BY c DESC
If you want the full rows:
select * from table where email in (
select email from table
group by emai... | MySQL | 1,786,533 | 290 |
I am working on a moderately complex schema in MySQL Workbench, and the single page of the EER diagram is now full up. Does anyone know how to enlarge it to two or more pages?
| On the Model pull-down there is an option Diagram Properties and Size, which allows the size of the diagram to be changed.
| MySQL | 4,933,000 | 289 |
Is there a MySQL function which can be used to convert a Unix timestamp into a human readable date? I have one field where I save Unix times and now I want to add another field for human readable dates.
| Use FROM_UNIXTIME():
SELECT
FROM_UNIXTIME(timestamp)
FROM
your_table;
See also: MySQL documentation on FROM_UNIXTIME().
| MySQL | 6,267,564 | 287 |
In a nutshell
I want to run mysql in a docker container and connect to it from my host. So far, the best I have achieved is:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
More details
I'm using the following Dockerfile:
FROM ubuntu:14.04.3
RUN apt-get update &... | If your Docker MySQL host is running correctly you can connect to it from local machine, but you should specify host, port and protocol like this:
mysql -h localhost -P 3306 --protocol=tcp -u root
Change 3306 to port number you have forwarded from Docker container (in your case it will be 12345).
Because you are runni... | MySQL | 33,001,750 | 286 |
What is main difference between INSERT INTO table VALUES .. and INSERT INTO table SET?
Example:
INSERT INTO table (a, b, c) VALUES (1,2,3)
INSERT INTO table SET a=1, b=2, c=3
And what about performance of these two?
| As far as I can tell, both syntaxes are equivalent. The first is SQL standard, the second is MySQL's extension.
So they should be exactly equivalent performance wise.
http://dev.mysql.com/doc/refman/5.6/en/insert.html says:
INSERT inserts new rows into an existing table. The INSERT ... VALUES and INSERT ... SET forms ... | MySQL | 861,722 | 286 |
I understand that this question has been asked before, but most of the time it is asked in relation to a specific database or table. I cannot find an answer on this site that describes the two engines and their differences without respect to someones specific database.
I want to be able to make more informed decisions... | The main differences between InnoDB and MyISAM ("with respect to designing a table or database" you asked about) are support for "referential integrity" and "transactions".
We choose InnoDB if we need the database to enforce foreign key constraints or support transactions (i.e. changes made by two or more DML operatio... | MySQL | 12,614,541 | 281 |
I have been following a manual to install a software suite on Ubuntu. I have no knowledge of MySQL at all. I have done the following installations on my Ubuntu.
sudo apt-get update
sudo apt-get install mysql-server-5.5
sudo apt-get install mysql-client-5.5
sudo apt-get install mysql-common
sudo apt-get install glade
su... | Note: For MySQL 5.7+, please see the answer from Lahiru to this question. That contains more current information.
For MySQL < 5.7:
The default root password is blank (i.e., an empty string), not root. So you can just log in as:
mysql -u root
You should obviously change your root password after installation:
mysqladmi... | MySQL | 21,944,936 | 278 |
Why do you need to place columns you create yourself (for example select 1 as "number") after HAVING and not WHERE in MySQL?
And are there any downsides instead of doing WHERE 1 (writing the whole definition instead of a column name)?
| All other answers on this question didn't hit upon the key point.
Assume we have a table:
CREATE TABLE `table` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`value` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `value` (`value`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
And have 10 rows with both id and value f... | MySQL | 2,905,292 | 277 |
Do you need to explicitly create an index, or is it implicit when defining the primary key? Is the answer the same for MyISAM and InnoDB?
| The primary key is always indexed. This is the same for MyISAM and InnoDB, and is generally true for all storage engines that at all supports indices.
| MySQL | 1,071,180 | 276 |
I have a WordPress production website.
I've exported the database by the following commands: select database > export > custom > select all tables > select .zip compression > 'Go'
I've downloaded the file which is example.sql.zip but when I upload to my localhost I get this error: phpMyAdmin - Error > Incorrect format ... | This issue is not because of corrupt database but rather the PHP upload size limit. It is suggested to increase the values of the following variables in php.ini:
upload_max_filesize=64M
post_max_size=64M
You may also want to increase the max_exection_time to a longer value for larger databases so it does not timeout w... | MySQL | 50,690,076 | 275 |
The query I'm running is as follows, however I'm getting this error:
#1054 - Unknown column 'guaranteed_postcode' in 'IN/ALL/ANY subquery'
SELECT `users`.`first_name`, `users`.`last_name`, `users`.`email`,
SUBSTRING(`locations`.`raw`,-6,4) AS `guaranteed_postcode`
FROM `users` LEFT OUTER JOIN `locations`
ON `users`.`... | You can only use column aliases in GROUP BY, ORDER BY, or HAVING clauses.
Standard SQL doesn't allow you to
refer to a column alias in a WHERE
clause. This restriction is imposed
because when the WHERE code is
executed, the column value may not yet
be determined.
Copied from MySQL documentation
As pointed in the comm... | MySQL | 942,571 | 274 |
I knew boolean in mysql as tinyint (1).
Today I see a table with defined an integer like tinyint(2), and also others like int(4), int(6) ...
What does the size means in field of type integer and tinyint ?
| The (m) indicates the column display width; applications such as the MySQL client make use of this when showing the query results.
For example:
| v | a | b | c |
+-----+-----+-----+-----+
| 1 | 1 | 1 | 1 |
| 10 | 10 | 10 | 10 |
| 100 | 100 | 100 | 100 |
Here a, b and c are using TINYINT(1), TINYINT... | MySQL | 12,839,927 | 272 |
When doing:
DELETE FROM `jobs` WHERE `job_id` =1 LIMIT 1
It errors:
#1451 - Cannot delete or update a parent row: a foreign key constraint fails
(paymesomething.advertisers, CONSTRAINT advertisers_ibfk_1 FOREIGN KEY
(advertiser_id) REFERENCES jobs (advertiser_id))
Here are my tables:
CREATE TABLE IF NOT EXISTS `ad... | The simple way would be to disable the foreign key check; make the changes then re-enable foreign key check.
SET FOREIGN_KEY_CHECKS=0; -- to disable them
SET FOREIGN_KEY_CHECKS=1; -- to re-enable them
| MySQL | 1,905,470 | 271 |
What's the simplest (and hopefully not too slow) way to calculate the median with MySQL? I've used AVG(x) for finding the mean, but I'm having a hard time finding a simple way of calculating the median. For now, I'm returning all the rows to PHP, doing a sort, and then picking the middle row, but surely there must be s... | In MariaDB / MySQL:
SELECT AVG(dd.val) as median_val
FROM (
SELECT d.val, @rownum:=@rownum+1 as `row_number`, @total_rows:=@rownum
FROM data d, (SELECT @rownum:=0) r
WHERE d.val is NOT NULL
-- put some where clause here
ORDER BY d.val
) as dd
WHERE dd.row_number IN ( FLOOR((@total_rows+1)/2), FLOOR((@total_rows... | MySQL | 1,291,152 | 271 |
I got the following error while trying to alter a column's data type and setting a new default value:
ALTER TABLE foobar_data ALTER COLUMN col VARCHAR(255) NOT NULL SET DEFAULT '{}';
ERROR 1064 (42000): You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the righ... | ALTER TABLE foobar_data MODIFY COLUMN col VARCHAR(255) NOT NULL DEFAULT '{}';
A second possibility which does the same (thanks to juergen_d):
ALTER TABLE foobar_data CHANGE COLUMN col col VARCHAR(255) NOT NULL DEFAULT '{}';
| MySQL | 11,312,433 | 267 |
So I try to import sql file into rds (1G MEM, 1 CPU). The sql file is like 1.4G
mysql -h xxxx.rds.amazonaws.com -u user -ppass --max-allowed-packet=33554432 db < db.sql
It got stuck at:
ERROR 1227 (42000) at line 374: Access denied; you need (at least one of) the SUPER privilege(s) for this operation
The actual sql co... | Either remove the DEFINER=.. statement from your sqldump file, or replace the user values with CURRENT_USER.
The MySQL server provided by RDS does not allow a DEFINER syntax for another user (in my experience).
You can use a sed script to remove them from the file:
sed 's/\sDEFINER=`[^`]*`@`[^`]*`//g' -i oldfile.sql
| MySQL | 44,015,692 | 266 |
Being new to MySQL, I have installed the latest version of the MySQL Workbench (5.2.33). I would like to know how you can create a database with this application. In the Overview tab of the SQL editor there are few "MySQL Schema" displayed, are these schemas the existing databases?
|
Launch MySQL Workbench.
On the left pane of the welcome window, choose a database to connect to under "Open Connection to Start Querying".
The query window will open. On its left pane, there is a section titled "Object Browser", which shows the list of databases. (Side note: The terms "schema" and "database" are synon... | MySQL | 5,515,745 | 266 |
Is it possible to do mysqldump by single SQL query?
I mean to dump the whole database, like phpmyadmin does when you do export to SQL
| not mysqldump, but mysql cli...
mysql -e "select * from myTable" -u myuser -pxxxxxxxxx mydatabase
you can redirect it out to a file if you want :
mysql -e "select * from myTable" -u myuser -pxxxxxxxx mydatabase > mydumpfile.txt
Update:
Original post asked if he could dump from the database by query. What he asked an... | MySQL | 935,556 | 266 |
While starting mysql server 5.7.17 using mysqld_safe, following error occcours.
2017-02-10T17:05:44.870970Z mysqld_safe Logging to '/var/log/mysql/error.log'.
2017-02-10T17:05:44.872874Z mysqld_safe Logging to '/var/log/mysql/error.log'.
2017-02-10T17:05:44.874547Z mysqld_safe Directory '/var/run/mysqld' for UNIX socke... | It seems odd that this directory was not created at install - have you manually changed the path of the socket file in the my.cfg?
Have you tried simply creating this directory yourself, and restarting the service?
mkdir -p /var/run/mysqld
chown mysql:mysql /var/run/mysqld
| MySQL | 42,153,059 | 265 |
Anyone know a quick easy way to migrate a SQLite3 database to MySQL?
| Everyone seems to starts off with a few greps and perl expressions and you sorta kinda get something that works for your particular dataset but you have no idea if it's imported the data correctly or not. I'm seriously surprised nobody's built a solid library that can convert between the two.
Here a list of ALL the dif... | MySQL | 18,671 | 264 |
I'm designing my database schema using MySQL Workbench, which is pretty cool because you can do diagrams and it converts them :P
Anyways, I've decided to use InnoDB because of it's Foreign Key support. One thing I noticed though is that it allows you to set On Update and on Delete options for foreign keys. Can someone ... | Do not hesitate to put constraints on the database. You'll be sure to have a consistent database, and that's one of the good reasons to use a database. Especially if you have several applications requesting it (or just one application but with a direct mode and a batch mode using different sources).
With MySQL you do n... | MySQL | 6,720,050 | 263 |
I would like to write a script which copies my current database sitedb1 to sitedb2 on the same mysql database instance. I know I can dump the sitedb1 to a sql script:
mysqldump -u root -p sitedb1 >~/db_name.sql
and then import it to sitedb2.
Is there an easier way, without dumping the first database to a sql file?
| As the manual says in Copying Databases you can pipe the dump directly into the mysql client:
mysqldump db_name | mysql new_db_name
If you're using MyISAM you could copy the files, but I wouldn't recommend it. It's a bit dodgy.
Integrated from various good other answers
Both mysqldump and mysql commands accept option... | MySQL | 675,289 | 263 |
I've recently taken over an old project that was created 10 years ago. It uses MySQL 5.1.
Among other things, I need to change the default character set from latin1 to utf8.
As an example, I have tables such as this:
CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`first_name` varchar(4... | I wasn't able to do this:
UPDATE users SET created = NULL WHERE created = '0000-00-00 00:00:00'
(on MySQL 5.7.13).
I kept getting the Incorrect datetime value: '0000-00-00 00:00:00' error.
Strangely, this worked: SELECT * FROM users WHERE created = '0000-00-00 00:00:00'. I have no idea why the former fails and the lat... | MySQL | 35,565,128 | 262 |
I need to ALTER my existing database to add a column. Consequently I also want to update the UNIQUE field to encompass that new column. I'm trying to remove the current index but keep getting the error MySQL Cannot drop index needed in a foreign key constraint
CREATE TABLE mytable_a (
ID TINYINT NOT NULL AUTO_... | You have to drop the foreign key. Foreign keys in MySQL automatically create an index on the table (There was a SO Question on the topic).
ALTER TABLE mytable DROP FOREIGN KEY mytable_ibfk_1 ;
| MySQL | 8,482,346 | 262 |
ID FirstName LastName
1 John Doe
2 Bugs Bunny
3 John Johnson
I want to select DISTINCT results from the FirstName column, but I need the corresponding ID and LastName.
The result set needs to show only one John, but with an ID of 1 and a LastName of Doe.
| try this query
SELECT ID, FirstName, LastName FROM table GROUP BY(FirstName)
| MySQL | 5,967,130 | 261 |
I have a table with a unique key for two columns:
CREATE TABLE `xpo`.`user_permanent_gift` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`fb_user_id` INT UNSIGNED NOT NULL ,
`gift_id` INT UNSIGNED NOT NULL ,
`purchase_timestamp` TIMESTAMP NULL DEFAULT now() ,
PRIMARY KEY (`id`) ,
UNIQUE INDEX `user_gift_UNIQUE` (`fb_u... | Yes, use INSERT ... ON DUPLICATE KEY UPDATE id=id (it won't trigger row update even though id is assigned to itself).
If you don't care about errors (conversion errors, foreign key errors) and autoincrement field exhaustion (it's incremented even if the row is not inserted due to duplicate key), then use INSERT IGNORE ... | MySQL | 4,596,390 | 261 |
Are JOIN queries faster than several queries? (You run your main query, and then you run many other SELECTs based on the results from your main query)
I'm asking because JOINing them would complicate A LOT the design of my application
If they are faster, can anyone approximate very roughly by how much? If it's 1.5x I d... | For inner joins, a single query makes sense, since you only get matching rows.
For left joins, multiple queries is much better... look at the following benchmark I did:
Single query with 5 Joins
query: 8.074508 seconds
result size: 2268000
5 queries in a row
combined query time: 0.00262 seconds
result size: 165 (6 + ... | MySQL | 1,067,016 | 261 |
This is a much discussed issue for OSX 10.6 users, but I haven't been able to find a solution that works. Here's my setup:
Python 2.6.1 64bit
Django 1.2.1
MySQL 5.1.47 osx10.6 64bit
I create a virtualenvwrapper with --no-site-packages, then installed Django. When I activate the virtualenv and run python manage.py syncd... | I had the same error and pip install MySQL-python solved it for me.
Alternate installs:
If you don't have pip, easy_install MySQL-python should work.
If your python is managed by a packaging system, you might have to use
that system (e.g. sudo apt-get install ...)
Below, Soli notes that if you receive the following e... | MySQL | 2,952,187 | 260 |
I'm getting a 1022 error regarding duplicate keys on create table command. Having looked at the query, I can't understand where the duplication is taking place. Can anyone else see it?
SQL query:
-- -----------------------------------------------------
-- Table `apptwo`.`usercircle`
-- -------------------------------... | Most likely you already have a constraint with the name iduser or idcategory in your database. Just rename the constraints if so.
Constraints must be unique for the entire database, not just for the specific table you are creating/altering.
To find out where the constraints are currently in use you can use the followin... | MySQL | 18,056,786 | 259 |
I have a large number of rows that I would like to copy, but I need to change one field.
I can select the rows that I want to copy:
select * from Table where Event_ID = "120"
Now I want to copy all those rows and create new rows while setting the Event_ID to 155. How can I accomplish this?
| INSERT INTO Table
( Event_ID
, col2
...
)
SELECT "155"
, col2
...
FROM Table WHERE Event_ID = "120"
Here, the col2, ... represent the remaining columns (the ones other than Event_ID) in your table.
| MySQL | 2,783,150 | 259 |
I have a SQL query where I want to insert multiple rows in single query. so I used something like:
$sql = "INSERT INTO beautiful (name, age)
VALUES
('Helen', 24),
('Katrina', 21),
('Samia', 22),
('Hui Ling', 25),
('Yumie', 29)";
mysql_query( $sql, $conn );
The problem is when I execute this query, I want ... | Beginning with MySQL 8.0.19 you can use an alias for that row (see reference).
INSERT INTO beautiful (name, age)
VALUES
('Helen', 24),
('Katrina', 21),
('Samia', 22),
('Hui Ling', 25),
('Yumie', 29)
AS new
ON DUPLICATE KEY UPDATE
age = new.age
...
For earlier versions use the keywo... | MySQL | 2,714,587 | 259 |
I'm currently creating a Login form and have this code:
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
try
{
using (OdbcConnection connect = new OdbcConnection(connectionString))
{
connect.Open();
OdbcCommand cmd = new OdbcCommand("SELECT u... | Make sure that your config file (web.config if web, or app.config if windows) in your project starts as:
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings"
type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Cultur... | MySQL | 6,436,157 | 258 |
I have an SQL table called "posts" that looks like this:
id | category
-----------------------
1 | 3
2 | 1
3 | 4
4 | 2
5 | 1
6 | 1
7 | 2
Each category number corresponds to a category. How would I go about counting the number of times each category appears on a post all in one SQL query?
As an example, such a q... | SELECT
category,
COUNT(*) AS `num`
FROM
posts
GROUP BY
category
| MySQL | 7,053,902 | 257 |
Currently I am having the following MySQL table: Employees (empID, empName, department);
I want to change the table to the following: Employees (empID, department, empName);
How can this be done using ALTER statements?
Note: I want to change only column positions.
| If empName is a VARCHAR(50) column:
ALTER TABLE Employees MODIFY COLUMN empName VARCHAR(50) AFTER department;
EDIT
Per the comments, you can also do this:
ALTER TABLE Employees CHANGE COLUMN empName empName VARCHAR(50) AFTER department;
Note that the repetition of empName is deliberate. You have to tell MySQL that yo... | MySQL | 6,805,426 | 257 |
I installed MySQL via MacPorts. What is the command I need to stop the server (I need to test how my application behave when MySQL is dead)?
| There are different cases depending on whether you installed MySQL with the official binary installer, using MacPorts, or using Homebrew:
Homebrew
brew services start mysql
brew services stop mysql
brew services restart mysql
MacPorts
sudo port load mysql57-server
sudo port unload mysql57-server
Note: this is persist... | MySQL | 100,948 | 256 |
Is there a fast way of getting all column names from all tables in MySQL, without having to list all the tables?
| select column_name from information_schema.columns
where table_schema = 'your_db'
order by table_name,ordinal_position
| MySQL | 5,648,420 | 255 |
I am getting this error in wordpress phpMyadmin
#145 - Table './DB_NAME/wp_posts' is marked as crashed and should be repaired
When I login to phpMyadmin, it says wp_posts is "in use"
My website is currently down because of this.
I googled this problem, but I don't see the "repair" button on phpMyadmin. Please let me ... | Here is where the repair button is:
| MySQL | 4,357,270 | 254 |
I have following data in my table "devices"
affiliate_name affiliate_location model ip os_type os_version
cs1 inter Dell 10.125.103.25 Linux Fedora
cs2 inter Dell 10.125.103.26 Linux Fedora
cs3 inter ... | convert the NULL values with empty string by wrapping it in COALESCE
SELECT CONCAT(COALESCE(`affiliate_name`,''),'-',COALESCE(`model`,''),'-',COALESCE(`ip`,''),'-',COALESCE(`os_type`,''),'-',COALESCE(`os_version`,'')) AS device_name
FROM devices
| MySQL | 15,741,314 | 254 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.