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 have tried to use Mongoose to send the list of all users as follows: server.get('/usersList', function(req, res) { var users = {}; User.find({}, function (err, user) { users[user._id] = user; }); res.send(users); }); Of course, res.send(users); is going to send {}, which is not what I want....
Well, if you really want to return a mapping from _id to user, you could always do: server.get('/usersList', function(req, res) { User.find({}, function(err, users) { var userMap = {}; users.forEach(function(user) { userMap[user._id] = user; }); res.send(userMap); }); }); find() returns a...
MongoDB
14,103,615
126
I'm thinking of creating a multi-tenant app using MongoDB. I don't have any guesses in terms of how many tenants I'd have yet, but I would like to be able to scale into the thousands. I can think of three strategies: All tenants in the same collection, using tenant-specific fields for security 1 Collection per tenant ...
I have the same problem to solve and also considering variants. As I have years of experience creating SaaS multi-tenant applicatios I also was going to select the second option based on my previous experience with the relational databases. While making my research I found this article on mongodb support site (way bac...
MongoDB
2,748,825
126
The data type of the field is String. I would like to fetch the data where character length of field name is greater than 40. I tried these queries but returning error. 1. db.usercollection.find( {$where: "(this.name.length > 40)"} ).limit(2); output :error: { "$err" : "TypeError: Cannot read property 'length' of...
For MongoDB 3.6 and newer: The $expr operator allows the use of aggregation expressions within the query language, thus you can leverage the use of $strLenCP operator to check the length of the string as follows: db.usercollection.find({ name: { $exists: true }, $expr: { $gt: [{ $strLenCP: '$name' }, 40] } })...
MongoDB
29,577,713
125
I can use the SQL Like Operator using pymongo, db.test.find({'c':{'$regex':'ttt'}}) But how can I use Not Like Operator? I tried db.test.find({'c':{'$not':{'$regex':'ttt'}}) but got error: OperationFailure: $not cannot have a regex
From the docs: The $not operator does not support operations with the $regex operator. Instead use // or in your driver interfaces, use your language’s regular expression capability to create regular expression objects. Consider the following example which uses the pattern match expression //: db.inventory.find( { it...
MongoDB
20,175,122
125
Suppose I have two collections/schemas. One is the Users Schema with username and password fields, then, I have a Blogs Schema that has a reference to the Users Schema in the author field. If I use Mongoose to do something like Blogs.findOne({...}).populate("user").exec() I will have the Blog document and the user pop...
You can change the default behavior at the schema definition level using the select attribute of the field: password: { type: String, select: false } Then you can pull it in as needed in find and populate calls via field selection as '+password'. For example: Users.findOne({_id: id}).select('+password').exec(...);
MongoDB
12,096,262
124
I'm using the MEAN stack and when I try to start the server using npm start, I get an exception saying that: schema hasn't been registered for model 'Post'. Use mongoose.model(name, schema) Here is my code inside /models/Posts.js: var mongoose = require('mongoose'); var PostSchema = new mongoose.Schema({ title: S...
It's not an issue with model export. I had the same issue. The real issue is that require statements for the models var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/news'); require('./models/Posts'); require('./models/Comments'); were below the routes dependencies. Simply move the mongoDB dep...
MongoDB
26,818,071
123
When using MongoDB's $in clause, does the order of the returned documents always correspond to the order of the array argument?
As noted, the order of the arguments in the array of an $in clause does not reflect the order of how the documents are retrieved. That of course will be the natural order or by the selected index order as shown. If you need to preserve this order, then you basically have two options. So let's say that you were matching...
MongoDB
22,797,768
123
I am new(ish) to the whole javascript full stack applications, and completely new to Angular, so I was hoping somebody can put the record straight for me here. Why would I need to use a templating framework like Jade or Handlebars when writing client side apps using AngularJS. I should say that I have never used any of...
I use Jade to generate templates consumed by AngularJS because I hate writing plain HTML. It looks something like: .control-group( ng-form name='emailGroup' ng-class='{"ng-error": emailGroup.$invalid}' ) label.control-label Email .controls input( type='email' ng-model='user.email' requir...
MongoDB
18,174,856
122
I know there are three different, popular types of non-sql databases. Key/Value: Redis, Tokyo Cabinet, Memcached ColumnFamily: Cassandra, HBase Document: MongoDB, CouchDB I have read long blogs about it without understanding so much. I know relational databases and get the hang around document-based databases like Mo...
The main differences are the data model and the querying capabilities. Key-value stores The first type is very simple and probably doesn't need any further explanation. Data model: more than key-value stores Although there is some debate on the correct name for databases such as Cassandra, I'd like to call them column-...
MongoDB
3,554,169
121
To start the container, I am typing the following command: sudo docker run -i -t -p 28000:27017 mongo:latest /usr/bin/mongod --smallfiles But I want to open the shell in this container to type the mongo commands. What command should I run to do the same?
You can run the interactive mongo shell by running the following command: docker run -it -p 28000:27017 --name mongoContainer mongo:latest mongosh Otherwise, if your container is already running, you can use the exec command: docker exec -it mongoContainer mongosh
MongoDB
32,944,729
121
I use NodeJS to insert documents in MongoDB. Using collection.insert I can insert a document into database like in this code: // ... collection.insert(objectToInsert, function(err){ if (err) return; // Object inserted successfully. var objectId; // = ??? }); // ... How can I get the _id of inserted object? Is...
A shorter way than using second parameter for the callback of collection.insert would be using objectToInsert._id that returns the _id (inside of the callback function, supposing it was a successful operation). The Mongo driver for NodeJS appends the _id field to the original object reference, so it's easy to get the i...
MongoDB
14,481,521
121
is possible in mongo db to select collection's documents like in SQL : SELECT * FROM collection WHERE _id IN (1,2,3,4); or if i have a _id array i must select one by one and then recompose the array/object of results?
Easy :) db.collection.find( { _id : { $in : [1,2,3,4] } } ); taken from: https://www.mongodb.com/docs/manual/reference/operator/query/in/#mongodb-query-op.-in
MongoDB
7,713,363
121
I have application using nodejs and mongodb. I have used mongoose for ODM. Now i want to log all the queries that mongoose fire during the whole application. How to log these?
You can enable debug mode like so: mongoose.set('debug', true); or add your own debug callback: mongoose.set('debug', function (coll, method, query, doc [, options]) { //do your thing }); This will log all executed collection methods and their arguments to the console.
MongoDB
18,762,264
120
I have a lot of mongodb documents in a collection of the form: { .... "URL":"www.abc.com/helloWorldt/..." ..... } I want to replace helloWorldt with helloWorld to get: { .... "URL":"www.abc.com/helloWorld/..." ..... } How can I achieve this for all documents in my collection?
db.media.find({mediaContainer:"ContainerS3"}).forEach(function(e,i) { e.url=e.url.replace("//a.n.com","//b.n.com"); db.media.save(e); });
MongoDB
12,589,792
120
Would you recommend using a datetime or a timestamp field, and why (using MySQL)? I'm working with PHP on the server side.
Timestamps in MySQL are generally used to track changes to records, and are often updated every time the record is changed. If you want to store a specific value you should use a datetime field. If you meant that you want to decide between using a UNIX timestamp or a native MySQL datetime field, go with the native DATE...
MySQL
409,286
3,180
I have a .sql file with an export from phpMyAdmin. I want to import it into a different server using the command line. I have a Windows Server 2008 R2 installation. I placed the .sql file on the C drive, and I tried this command database_name < file.sql It is not working. I get syntax errors. How can I import this fi...
Try: mysql -u username -p database_name < file.sql Check MySQL Options. Note 1: It is better to use the full path of the SQL file file.sql. Note 2: Use -R and --triggers with mysqldump to keep the routines and triggers of the original database. They are not copied by default. Note 3 You may have to create the (empty) ...
MySQL
17,666,249
2,785
If user input is inserted without modification into an SQL query, then the application becomes vulnerable to SQL injection, like in the following example: $unsafe_variable = $_POST['user_input']; mysql_query("INSERT INTO `table` (`column`) VALUES ('$unsafe_variable')"); That's because the user can input something li...
The correct way to avoid SQL injection attacks, no matter which database you use, is to separate the data from SQL, so that data stays data and will never be interpreted as commands by the SQL parser. It is possible to create an SQL statement with correctly formatted data parts, but if you don't fully understand the de...
MySQL
60,174
2,769
What are the technical reasons for why one shouldn't use mysql_* functions? (e.g. mysql_query(), mysql_connect() or mysql_real_escape_string())? Why should I use something else even if they work on my site? If they don't work on my site, why do I get errors like Warning: mysql_connect(): No such file or directory
The MySQL extension: Is not under active development Is officially deprecated as of PHP 5.5 (released June 2013). Has been removed entirely as of PHP 7.0 (released December 2015) This means that as of 31 Dec 2018 it does not exist in any supported version of PHP. If you are using a version of PHP which supports it, ...
MySQL
12,859,942
2,722
I am trying to install version 1.2.2 of MySQL_python, using a fresh virtualenv created with the --no-site-packages option. The current version shown in PyPi is 1.2.3. Is there a way to install the older version? I have tried: pip install MySQL_python==1.2.2 However, when installed, it still shows MySQL_python-1.2.3-py...
TL;DR: Update as of 2022-12-28: pip install --force-reinstall -v For example: pip install --force-reinstall -v "MySQL_python==1.2.2" What these options mean: --force-reinstall is an option to reinstall all packages even if they are already up-to-date. -v is for verbose. You can combine for even more verbosity (i.e. -v...
MySQL
5,226,311
1,977
I have this table for documents (simplified version here): id rev content 1 1 ... 2 1 ... 1 2 ... 1 3 ... How do I select one row per id and only the greatest rev? With the above data, the result should contain two rows: [1, 3, ...] and [2, 1, ..]. I'm using MySQL. Currently I use checks in the while ...
At first glance... All you need is a GROUP BY clause with the MAX aggregate function: SELECT id, MAX(rev) FROM YourTable GROUP BY id It's never that simple, is it? I just noticed you need the content column as well. This is a very common question in SQL: find the whole data for the row with some max value in a column ...
MySQL
7,745,609
1,660
How can I reset the AUTO_INCREMENT of a field? I want it to start counting from 1 again.
You can reset the counter with: ALTER TABLE tablename AUTO_INCREMENT = 1 InnoDB For InnoDB you cannot set the auto_increment value lower or equal to the highest current index. (quote from ViralPatel): Note that you cannot reset the counter to a value less than or equal to any that have already been used. For MyISAM, ...
MySQL
8,923,114
1,640
Using MySQL, I can do something like: SELECT hobbies FROM peoples_hobbies WHERE person_id = 5; My Output: shopping fishing coding but instead I just want 1 row, 1 col: Expected Output: shopping, fishing, coding The reason is that I'm selecting multiple values from multiple tables, and after all the joins I've got a ...
You can use GROUP_CONCAT: SELECT person_id, GROUP_CONCAT(hobbies SEPARATOR ', ') FROM peoples_hobbies GROUP BY person_id; As Ludwig stated in his comment, you can add the DISTINCT operator to avoid duplicates: SELECT person_id, GROUP_CONCAT(DISTINCT hobbies SEPARATOR ', ') FROM peoples_hobbies GROUP BY person_id...
MySQL
276,927
1,488
Is there an easy way to run a MySQL query from the Linux command line and output the results in CSV format? Here's what I'm doing now: mysql -u uid -ppwd -D dbname << EOQ | sed -e 's/ /,/g' | tee list.csv select id, concat("\"",name,"\"") as name from students EOQ It gets messy when there are a lot of columns t...
From Save MySQL query results into a text or CSV file: SELECT order_id,product_name,qty FROM orders WHERE foo = 'bar' INTO OUTFILE '/var/lib/mysql-files/orders.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n'; Note: That syntax may need to be reordered to SELECT order_id,product_name,qty INTO OUT...
MySQL
356,578
1,437
I'm using the MySQL command-line utility and can navigate through a database. Now I need to see a list of user accounts. How can I do this? I'm using MySQL version 5.4.1.
Use this query: SELECT User FROM mysql.user; Which will output a table like this: +-------+ | User | +-------+ | root | +-------+ | user2 | +-------+ As Matthew Scharley points out in the comments on this answer, you can group by the User column if you'd only like to see unique usernames.
MySQL
1,135,245
1,417
Since MySQL doesn't seem to have any 'boolean' data type, which data type do you 'abuse' for storing true/false information in MySQL? Especially in the context of writing and reading from/to a PHP script. Over time I have used and seen several approaches: tinyint, varchar fields containing the values 0/1, varchar fiel...
For MySQL 5.0.3 and higher, you can use BIT. The manual says: As of MySQL 5.0.3, the BIT data type is used to store bit-field values. A type of BIT(M) enables storage of M-bit values. M can range from 1 to 64. Otherwise, according to the MySQL manual you can use BOOL or BOOLEAN, which are at the moment aliases of tin...
MySQL
289,727
1,398
I'm setting up a new server and want to support UTF-8 fully in my web application. I have tried this in the past on existing servers and always seem to end up having to fall back to ISO-8859-1. Where exactly do I need to set the encoding/charsets? I'm aware that I need to configure Apache, MySQL, and PHP to do this — ...
Data Storage: Specify the utf8mb4 character set on all tables and text columns in your database. This makes MySQL physically store and retrieve values encoded natively in UTF-8. Note that MySQL will implicitly use utf8mb4 encoding if a utf8mb4_* collation is specified (without any explicit character set). In older ...
MySQL
279,170
1,358
There is a table messages that contains data as shown below: Id Name Other_Columns ------------------------- 1 A A_data_1 2 A A_data_2 3 A A_data_3 4 B B_data_1 5 B B_data_2 6 C C_data_1 If I run a query select * from messages group by name, I will get the resu...
MySQL 8.0 now supports windowing functions, like almost all popular SQL implementations. With this standard syntax, we can write greatest-n-per-group queries: WITH ranked_messages AS ( SELECT m.*, ROW_NUMBER() OVER (PARTITION BY name ORDER BY id DESC) AS rn FROM messages AS m ) SELECT * FROM ranked_messages WHERE r...
MySQL
1,313,120
1,334
Between utf8_general_ci and utf8_unicode_ci, are there any differences in terms of performance?
For those people still arriving at this question in 2020 or later, there are newer options that may be better than both of these. For example, utf8_unicode_520_ci. All these collations are for the UTF-8 character encoding. The differences are in how text is sorted and compared. _unicode_ci and _general_ci are two dif...
MySQL
766,809
1,334
I want to update the column visited to give it the value 1. I tried this command in the SQL editor inside MySQL workbench: UPDATE tablename SET columnname=1; But I get an error that says: You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column To disable safe mode, toggle...
It looks like your MySql session has the safe-updates option set. This means that you can't update or delete records without specifying a key (ex. primary key) in the where clause. Try: SET SQL_SAFE_UPDATES = 0; Or you can modify your query to follow the rule (use primary key in where clause).
MySQL
11,448,068
1,210
I want to add a row to a database table, but if a row exists with the same unique key I want to update the row. For example: INSERT INTO table_name (ID, NAME, AGE) VALUES(1, "A", 19); Let’s say the unique key is ID, and in my Database, there is a row with ID = 1. In that case, I want to update that row with these valu...
Use INSERT ... ON DUPLICATE KEY UPDATE QUERY: INSERT INTO table (id, name, age) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE name="A", age=19
MySQL
4,205,181
1,169
I can run this query to get the sizes of all tables in a MySQL database: show table status from myDatabaseName; I would like some help in understanding the results. I am looking for tables with the largest sizes. Which column should I look at?
You can use this query to show the size of a table (although you need to substitute the variables first): SELECT table_name AS `Table`, round(((data_length + index_length) / 1024 / 1024), 2) `Size in MB` FROM information_schema.TABLES WHERE table_schema = "$DB_NAME" AND table_name = "$TABLE_NAME"; or t...
MySQL
9,620,198
1,163
How do I quickly rename a MySQL database (change its schema name)? Usually I just dump a database and re-import it with a new name. This is not an option for very big databases. Apparently RENAME {DATABASE | SCHEMA} db_name TO new_db_name; does bad things, exists only in a handful of versions, and is a bad idea overall...
For InnoDB, the following seems to work: create the new empty database, then rename each table in turn into the new database: RENAME TABLE old_db.table TO new_db.table; You will need to adjust the permissions after that. For scripting in a shell, you can use either of the following: mysql -u username -ppassword old_db...
MySQL
67,093
1,156
I am an old-school MySQL user and have always preferred JOIN over sub-query. But nowadays everyone uses sub-query, and I hate it; I don't know why. I lack the theoretical knowledge to judge for myself if there is any difference. Is a sub-query as good as a JOIN and therefore is there nothing to worry about?
Sub-queries are the logically correct way to solve problems of the form, "Get facts from A, conditional on facts from B". In such instances, it makes more logical sense to stick B in a sub-query than to do a join. It is also safer, in a practical sense, since you don't have to be cautious about getting duplicated facts...
MySQL
2,577,174
1,123
For simplicity, assume all relevant fields are NOT NULL. You can do: SELECT table1.this, table2.that, table2.somethingelse FROM table1, table2 WHERE table1.foreignkey = table2.primarykey AND (some other conditions) Or else: SELECT table1.this, table2.that, table2.somethingelse FROM table1 INNER...
INNER JOIN is ANSI syntax that you should use. It is generally considered more readable, especially when you join lots of tables. It can also be easily replaced with an OUTER JOIN whenever a need arises. The WHERE syntax is more relational model oriented. A result of two tables JOINed is a cartesian product of the tabl...
MySQL
1,018,822
1,120
I started by googling and found the article How to write INSERT if NOT EXISTS queries in standard SQL which talks about mutex tables. I have a table with ~14 million records. If I want to add more data in the same format, is there a way to ensure the record I want to insert does not already exist without using a pair o...
Use INSERT IGNORE INTO table. There's also INSERT … ON DUPLICATE KEY UPDATE syntax, and you can find explanations in 13.2.6.2 INSERT ... ON DUPLICATE KEY UPDATE Statement. Post from bogdan.org.ua according to Google's webcache: 18th October 2007 To start: as of the latest MySQL, syntax presented in the title is not p...
MySQL
1,361,340
1,095
I have a table: table votes ( id, user, email, address, primary key(id), ); How can I make the columns user, email, address unique - i.e., ensure that there isn't any pair of rows that has identical values for all three columns?
To add a unique constraint, you need to use two components: ALTER TABLE - to change the table schema and, ADD UNIQUE - to add the unique constraint. You then can define your new unique key with the format 'name'('column1', 'column2'...) So for your particular issue, you could use this command: ALTER TABLE `votes` ADD U...
MySQL
635,937
1,049
I have 2-3 different column names that I want to look up in the entire database and list out all tables which have those columns. Is there any easy script?
To get all tables with columns columnA or ColumnB in the database YourDatabase: SELECT DISTINCT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME IN ('columnA','ColumnB') AND TABLE_SCHEMA='YourDatabase';
MySQL
193,780
1,048
How do you set a default value for a MySQL Datetime column? In SQL Server it's getdate(). What is the equivalant for MySQL? I'm using MySQL 5.x if that is a factor.
IMPORTANT EDIT: It is now possible to achieve this with DATETIME fields since MySQL 5.6.5, take a look at the other post below... Previous versions can't do that with DATETIME... But you can do it with TIMESTAMP: mysql> create table test (str varchar(32), ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP); Query OK, 0 rows affect...
MySQL
168,736
1,041
I am trying to select data from a MySQL table, but I get one of the following error messages: mysql_fetch_array() expects parameter 1 to be resource, boolean given This is my code: $username = $_POST['username']; $password = $_POST['password']; $result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username...
A query may fail for various reasons in which case both the mysql_* and the mysqli extension will return false from their respective query functions/methods. You need to test for that error condition and handle it accordingly. mysql_ extension: NOTE The mysql_ functions are deprecated and have been removed in php vers...
MySQL
2,973,202
1,005
While executing an INSERT statement with many rows, I want to skip duplicate entries that would otherwise cause failure. After some research, my options appear to be the use of either: ON DUPLICATE KEY UPDATE which implies an unnecessary update at some cost, or INSERT IGNORE implies an invitation for other kinds of fa...
I would recommend using INSERT...ON DUPLICATE KEY UPDATE. If you use INSERT IGNORE, then the row won't actually be inserted if it results in a duplicate key. But the statement won't generate an error. It generates a warning instead. These cases include: Inserting a duplicate key in columns with PRIMARY KEY or UNIQU...
MySQL
548,541
959
Per the MySQL docs, there are four TEXT types: TINYTEXT TEXT MEDIUMTEXT LONGTEXT What is the maximum length that I can store in a column of each data type assuming the character encoding is UTF-8?
From the documentation (MySQL 8) : Type | Maximum length -----------+------------------------------------- TINYTEXT | 255 (2 8−1) bytes TEXT | 65,535 (216−1) bytes = 64 KiB MEDIUMTEXT | 16,777,215 (224−1) bytes = 16 MiB LONGTEXT | 4,294,967,295 (232−1) bytes = 4 GiB Note that the ...
MySQL
13,932,750
951
I have a table with a varchar column, and I would like to find all the records that have duplicate values in this column. What is the best query I can use to find the duplicates?
Do a SELECT with a GROUP BY clause. Let's say name is the column you want to find duplicates in: SELECT name, COUNT(*) c FROM table GROUP BY name HAVING c > 1; This will return a result with the name value in the first column, and a count of how many times that value appears in the second.
MySQL
688,549
948
I've got a messages table in MySQL which records messages between users. Apart from the typical ids and message types (all integer types) I need to save the actual message text as either VARCHAR or TEXT. I'm setting a front-end limit of 3000 characters which means the messages would never be inserted into the db as lon...
TEXT and BLOB may by stored off the table with the table just having a pointer to the location of the actual storage. Where it is stored depends on lots of things like data size, columns size, row_format, and MySQL version. VARCHAR is stored inline with the table. VARCHAR is faster when the size is reasonable, the tr...
MySQL
2,023,481
914
I have a table of player performance: CREATE TABLE TopTen ( id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT, home INT UNSIGNED NOT NULL, `datetime`DATETIME NOT NULL, player VARCHAR(6) NOT NULL, resource INT NOT NULL ); What query will return the rows for each distinct home holding its maximum value of datetime? I...
You are so close! All you need to do is select BOTH the home and its max date time, then join back to the topten table on BOTH fields: SELECT tt.* FROM topten tt INNER JOIN (SELECT home, MAX(datetime) AS MaxDateTime FROM topten GROUP BY home) groupedtt ON tt.home = groupedtt.home AND tt.datetime = groupe...
MySQL
612,231
912
I want to do a full outer join in MySQL. Is this possible? Is a full outer join supported by MySQL?
You don't have full joins in MySQL, but you can sure emulate them. For a code sample transcribed from this Stack Overflow question you have: With two tables t1, t2: SELECT * FROM t1 LEFT JOIN t2 ON t1.id = t2.id UNION SELECT * FROM t1 RIGHT JOIN t2 ON t1.id = t2.id The query above works for special cases where a full...
MySQL
4,796,872
883
I accidentally enabled ONLY_FULL_GROUP_BY mode like this: SET sql_mode = 'ONLY_FULL_GROUP_BY'; How do I disable it?
Solution 1: Remove ONLY_FULL_GROUP_BY from mysql console mysql > SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY','')); you can read more here Be aware that this setting is NOT persistent across restarts, then use mysql > SET PERSIST sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY','')); So...
MySQL
23,921,117
882
This should be dead simple, but I cannot get it to work for the life of me. I'm just trying to connect remotely to my MySQL server. Connecting as: mysql -u root -h localhost -p works fine, but trying: mysql -u root -h 'any ip address here' -p fails with the error: ERROR 1130 (00000): Host 'xxx.xx.xxx.xxx' is no...
Possibly a security precaution. You could try adding a new administrator account: mysql> CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass'; mysql> GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost' -> WITH GRANT OPTION; mysql> CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass'; mysql> GRANT ALL PRIVILEGE...
MySQL
1,559,955
881
Why doesn't a TRUNCATE on mygroup work? Even though I have ON DELETE CASCADE SET I get: ERROR 1701 (42000): Cannot truncate a table referenced in a foreign key constraint (mytest.instance, CONSTRAINT instance_ibfk_1 FOREIGN KEY (GroupID) REFERENCES mytest.mygroup (ID)) drop database mytest; create database mytest; us...
Yes you can: SET FOREIGN_KEY_CHECKS = 0; TRUNCATE table1; TRUNCATE table2; SET FOREIGN_KEY_CHECKS = 1; With these statements, you risk letting in rows into your tables that do not adhere to the FOREIGN KEY constraints.
MySQL
5,452,760
865
I have a table story_category in my database with corrupt entries. The next query returns the corrupt entries: SELECT * FROM story_category WHERE category_id NOT IN ( SELECT DISTINCT category.id FROM category INNER JOIN story_category ON category_id=category.id); I tried to delete them executing: D...
Update: This answer covers the general error classification. For a more specific answer about how to best handle the OP's exact query, please see other answers to this question In MySQL, you can't modify the same table which you use in the SELECT part. This behaviour is documented at: http://dev.mysql.com/doc/refman/5....
MySQL
45,494
839
Is it possible to temporarily disable constraints in MySQL? I have two Django models, each with a foreign key to the other one. Deleting instances of a model returns an error because of the foreign key constraint: cursor.execute("DELETE FROM myapp_item WHERE n = %s", n) transaction.commit_unless_managed() #a foreign k...
Try DISABLE KEYS or SET FOREIGN_KEY_CHECKS=0; Make sure to SET FOREIGN_KEY_CHECKS=1; after.
MySQL
15,501,673
837
How to get size of a mysql database? Suppose the target database is called "v3".
Run this query and you'll probably get what you're looking for: SELECT table_schema "DB Name", ROUND(SUM(data_length + index_length) / 1024 / 1024, 1) "DB Size in MB" FROM information_schema.tables GROUP BY table_schema; This query comes from the mysql forums, where there are more comprehensive instructions...
MySQL
1,733,507
815
Is it possible to make a simple query to count how many records I have in a determined period of time like a year, month, or day, having a TIMESTAMP field, like: SELECT COUNT(id) FROM stats WHERE record_date.YEAR = 2009 GROUP BY record_date.YEAR Or even: SELECT COUNT(id) FROM stats GROUP BY record_date.YEAR, record_d...
GROUP BY YEAR(record_date), MONTH(record_date) Check out the date and time functions in MySQL.
MySQL
508,791
800
Is there a collation type which is officially recommended by MySQL, for a general website where you aren't 100% sure of what will be entered? I understand that all the encodings should be the same, such as MySQL, Apache, the HTML and anything inside PHP. In the past I have set PHP to output in "UTF-8", but which collat...
The main difference is sorting accuracy (when comparing characters in the language) and performance. The only special one is utf8_bin which is for comparing characters in binary format. utf8_general_ci is somewhat faster than utf8_unicode_ci, but less accurate (for sorting). The specific language utf8 encoding (such as...
MySQL
367,711
796
In MySQL, how do I get a list of all foreign key constraints pointing to a particular table? a particular column? This is the same thing as this Oracle question, but for MySQL.
For a Table: SELECT TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME, REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = (SELECT DATABASE()) AND REFERENCED_TABLE_NAME = '<table>' \G For a Column: SELECT TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME, REFEREN...
MySQL
201,621
796
I am trying to learn the best way to write queries. I also understand the importance of being consistent. Until now, I have randomly used single quotes, double quotes, and backticks without any real thought. Example: $query = 'INSERT INTO table (id, col1, col2) VALUES (NULL, val1, val2)'; Also, in the above example, c...
Backticks are to be used for table and column identifiers, but are only necessary when the identifier is a MySQL reserved keyword, or when the identifier contains whitespace characters or characters beyond a limited set (see below) It is often recommended to avoid using reserved keywords as column or table identifiers ...
MySQL
11,321,491
794
Is there an SQL injection possibility even when using mysql_real_escape_string() function? Consider this sample situation. SQL is constructed in PHP like this: $login = mysql_real_escape_string(GetFromPost('login')); $password = mysql_real_escape_string(GetFromPost('password')); $sql = "SELECT * FROM table WHERE login...
The short answer is yes, yes there is a way to get around mysql_real_escape_string(). #For Very OBSCURE EDGE CASES!!! The long answer isn't so easy. It's based off an attack demonstrated here. The Attack So, let's start off by showing the attack... mysql_query('SET NAMES gbk'); $var = mysql_real_escape_string("\xbf\x27...
MySQL
5,741,187
788
I can't make a simple connection to the server for some reason. I install the newest MySQL Community 8.0 database along with Node.JS with default settings. This is my node.js code var mysql = require('mysql'); var con = mysql.createConnection({ host: "localhost", user: "root", password: "...
Execute the following query in MYSQL Workbench ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password'; Where root as your user localhost as your URL and password as your password Then run this query to refresh privileges: flush privileges; Try connecting using node after you do so. If that do...
MySQL
50,093,144
781
SELECT id, amount FROM report I need amount to be amount if report.type='P' and -amount if report.type='N'. How do I add this to the above query?
SELECT id, IF(type = 'P', amount, amount * -1) as amount FROM report See https://dev.mysql.com/doc/refman/8.0/en/flow-control-functions.html. Additionally, you could handle when the condition is null. In the case of a null amount: SELECT id, IF(type = 'P', IFNULL(amount,0), IFNULL(amount,0) * -1) as am...
MySQL
5,951,157
765
I want to pull out duplicate records in a MySQL Database. This can be done with: SELECT address, count(id) as cnt FROM list GROUP BY address HAVING cnt > 1 Which results in: 100 MAIN ST 2 I would like to pull it so that it shows each row that is a duplicate. Something like: JIM JONES 100 MAIN ST JOHN SMI...
The key is to rewrite this query so that it can be used as a subquery. SELECT firstname, lastname, list.address FROM list INNER JOIN (SELECT address FROM list GROUP BY address HAVING COUNT(id) > 1) dup ON list.address = dup.address;
MySQL
854,128
743
I want to change the data type of multiple columns from float to int. What is the simplest way to do this? There is no data to worry about, yet.
http://dev.mysql.com/doc/refman/5.1/en/alter-table.html ALTER TABLE tablename MODIFY columnname INTEGER; This will change the datatype of given column Depending on how many columns you wish to modify it might be best to generate a script, or use some kind of mysql client GUI
MySQL
1,356,866
690
I need to check (from the same table) if there is an association between two events based on date-time. One set of data will contain the ending date-time of certain events and the other set of data will contain the starting date-time for other events. If the first event completes before the second event then I would li...
You can actually do this one of two ways: MySQL update join syntax: UPDATE tableA a INNER JOIN tableB b ON a.name_a = b.name_b SET validation_check = if(start_dts > end_dts, 'VALID', '') -- where clause can go here ANSI SQL syntax: UPDATE tableA SET validation_check = (SELECT if(start_DTS > end_DTS, 'VALID', '') ...
MySQL
1,262,786
690
Is there a way to restrict certain tables from the mysqldump command? For example, I'd use the following syntax to dump only table1 and table2: mysqldump -u username -p database table1 table2 > database.sql But is there a similar way to dump all the tables except table1 and table2? I haven't found anything in the mysq...
You can use the --ignore-table option. So you could do mysqldump -u USERNAME -pPASSWORD DATABASE --ignore-table=DATABASE.table1 > database.sql There is no whitespace after -p (this is not a typo). To ignore multiple tables, use this option multiple times, this is documented to work since at least version 5.0. If you w...
MySQL
425,158
682
I am connecting MySQL - 8.0 with MySQL Workbench and getting the below error: Authentication plugin 'caching_sha2_password' cannot be loaded: dlopen(/usr/local/mysql/lib/plugin/caching_sha2_password.so, 2): image not found I have tried with other client tool as well. Any solution for this?
You can change the encryption of the password like this. ALTER USER 'yourusername'@'localhost' IDENTIFIED WITH mysql_native_password BY 'youpassword';
MySQL
49,194,719
681
I'm using a MySql database with a Java program, now I want to give the program to somebody else. How to export the MySQL database structure without the data in it, just the structure?
You can do with the --no-data option with mysqldump command mysqldump -h yourhostnameorIP -u root -p --no-data dbname > schema.sql
MySQL
6,175,473
676
I was given a MySQL database file that I need to restore as a database on my Windows Server 2008 machine. I tried using MySQL Administrator, but I got the following error: The selected file was generated by mysqldump and cannot be restored by this application. How do I get this working?
If the database you want to restore doesn't already exist, you need to create it first. On the command-line, if you're in the same directory that contains the dumped file, use these commands (with appropriate substitutions): C:\> mysql -u root -p mysql> create database mydb; mysql> use mydb; mysql> source db_backup.du...
MySQL
105,776
675
When I executed the following command: ALTER TABLE `mytable` ADD UNIQUE ( `column1` , `column2` ); I got this error message: #1071 - Specified key was too long; max key length is 767 bytes Information about column1 and column2: column1 varchar(20) utf8_general_ci column2 varchar(500) utf8_general_ci I think varchar...
767 bytes in MySQL version 5.6 (and prior versions), is the stated prefix limitation for InnoDB tables. It's 1,000 bytes long for MyISAM tables. This limit has been increased to 3072 bytes In MySQL version 5.7 (and upwards). You also have to be aware that if you set an index on a big char or varchar field which is utf8...
MySQL
1,814,532
672
I have a column containing urls (id, url): http://www.example.com/articles/updates/43 http://www.example.com/articles/updates/866 http://www.example.com/articles/updates/323 http://www.example.com/articles/updates/seo-url http://www.example.com/articles/updates/4?something=test I'd like to change the word "updates" to...
UPDATE your_table SET your_field = REPLACE(your_field, 'articles/updates/', 'articles/news/') WHERE your_field LIKE '%articles/updates/%' Now rows that were like http://www.example.com/articles/updates/43 will be http://www.example.com/articles/news/43 http://www.electrictoolbox.com/mysql-find-replace-text/
MySQL
5,956,993
651
What is the size of column of int(11) in mysql in bytes? And Maximum value that can be stored in this columns?
An INT will always be 4 bytes no matter what length is specified. TINYINT = 1 byte (8 bit) SMALLINT = 2 bytes (16 bit) MEDIUMINT = 3 bytes (24 bit) INT = 4 bytes (32 bit) BIGINT = 8 bytes (64 bit). The length just specifies how many characters to pad when selecting data with the mysql command line client. 12345 store...
MySQL
5,634,104
640
What command returns the current version of a MySQL database?
Try this function - SELECT VERSION(); -> '5.7.22-standard' VERSION() Or for more details use : SHOW VARIABLES LIKE "%version%"; +-------------------------+------------------------------------------+ | Variable_name | Value | +-------------------------+----------------------...
MySQL
8,987,679
628
How can I trace MySQL queries on my Linux server as they happen? For example I'd love to set up some sort of listener, then request a web page and view all of the queries the engine executed, or just view all of the queries being run on a production server. How can I do this?
You can log every query to a log file really easily: mysql> SHOW VARIABLES LIKE "general_log%"; +------------------+----------------------------+ | Variable_name | Value | +------------------+----------------------------+ | general_log | OFF | | general_log_file | /v...
MySQL
568,564
621
I have a table with ~500k rows; varchar(255) UTF8 column filename contains a file name; I'm trying to strip out various strange characters out of the filename - thought I'd use a character class: [^a-zA-Z0-9()_ .\-] Now, is there a function in MySQL that lets you replace through a regular expression? I'm looking for a ...
If you are using MariaDB or MySQL 8.0, they have a function REGEXP_REPLACE(col, regexp, replace) See MariaDB docs and PCRE Regular expression enhancements Note that you can use regexp grouping as well (I found that very useful): SELECT REGEXP_REPLACE("stackoverflow", "(stack)(over)(flow)", '\\2 - \\1 - \\3') returns ...
MySQL
986,826
616
I'm setting up a new server and keep running into this problem. When I try to log into the MySQL database with the root user, I get the error: ERROR 1698 (28000): Access denied for user 'root'@'localhost' It doesn't matter if I connect through the terminal (SSH), through phpMyAdmin or a MySQL client, e.g., Navicat. T...
On some systems, like Ubuntu, MySQL is using the Unix auth_socket plugin by default. Basically it means that: db_users using it, will be "authenticated" by the system user credentials. You can see if your root user is set up like this by doing the following: sudo mysql -u root # I had to use "sudo" since it was a new i...
MySQL
39,281,594
614
Here is the script to create my tables: CREATE TABLE clients ( client_i INT(11), PRIMARY KEY (client_id) ); CREATE TABLE projects ( project_id INT(11) UNSIGNED, client_id INT(11) UNSIGNED, PRIMARY KEY (project_id) ); CREATE TABLE posts ( post_id INT(11) UNSIGNED, project_id INT(11) UNSIGNED, PR...
You just need to specify that you want to delete the entries from the posts table: DELETE posts FROM posts INNER JOIN projects ON projects.project_id = posts.project_id WHERE projects.client_id = :client_id EDIT: For more information you can see this alternative answer
MySQL
652,770
605
How do I see if my database has any indexes on it? How about for a specific table?
To see the index for a specific table use SHOW INDEX: SHOW INDEX FROM yourtable; To see indexes for all tables within a specific schema you can use the STATISTICS table from INFORMATION_SCHEMA: SELECT DISTINCT TABLE_NAME, INDEX_NAME FROM INFORMATION_SCHEMA.STATISTICS WHERE TABLE_SCHEMA = 'your_schema'; Remov...
MySQL
5,213,339
604
How to declare a variable in mysql, so that my second query can use it? I would like to write something like: SET start = 1; SET finish = 10; SELECT * FROM places WHERE place BETWEEN start AND finish;
There are mainly three types of variables in MySQL: User-defined variables (prefixed with @): You can access any user-defined variable without declaring it or initializing it. If you refer to a variable that has not been initialized, it has a value of NULL and a type of string. SELECT @var_any_var_name You can initi...
MySQL
11,754,781
592
I am using MySQL in localhost as a "query tool" for performing statistics in R, that is, everytime I run a R script, I create a new database (A), create a new table (B), import the data into B, submit a query to get what I need, and then I drop B and drop A. It's working fine for me, but I realize that the ibdata file ...
That ibdata1 isn't shrinking is a particularly annoying feature of MySQL. The ibdata1 file can't actually be shrunk unless you delete all databases, remove the files and reload a dump. But you can configure MySQL so that each table, including its indexes, is stored as a separate file. In that way ibdata1 will not grow ...
MySQL
3,456,159
581
Is there a nice easy way to drop all tables from a MySQL database, ignoring any foreign key constraints that may be in there?
I found the generated set of drop statements useful, and recommend these tweaks: Limit the generated drops to your database like this: SELECT concat('DROP TABLE IF EXISTS `', table_name, '`;') FROM information_schema.tables WHERE table_schema = 'MyDatabaseName'; Note 1: This does not execute the DROP statements, it ...
MySQL
3,476,765
573
Is it possible to create a temporary (session only) table from a select statement without using a create table statement and specifying each column type? I know derived tables are capable of this, but those are super-temporary (statement-only) and I want to re-use. It would save time if I did not have to write up a cre...
CREATE TEMPORARY TABLE IF NOT EXISTS table2 AS (SELECT * FROM table1) From the manual found at http://dev.mysql.com/doc/refman/5.7/en/create-table.html You can use the TEMPORARY keyword when creating a table. A TEMPORARY table is visible only to the current session, and is dropped automatically when the session is cl...
MySQL
5,859,391
571
By default, mysqldump takes the backup of an entire database. I need to backup a single table in MySQL. Is it possible? How do I restore it?
Dump and restore a single table from .sql Dump mysqldump db_name table_name > table_name.sql Dumping from a remote database mysqldump -u <db_username> -h <db_host> -p db_name table_name > table_name.sql For further reference: http://www.abbeyworkshop.com/howto/lamp/MySQL_Export_Backup/index.html Restore mysql -u <us...
MySQL
6,682,916
559
Consider: ./mysqladmin -u root -p** '_redacted_' Output (including typing the password): Enter password: mysqladmin: connect to server at 'localhost' failed error: 'Access denied for user 'root'@'localhost' (using password: YES)' How can I fix this?
All solutions I found were much more complex than necessary and none worked for me. Here is the solution that solved my problem. There isn't any need to restart mysqld or start it with special privileges. sudo mysql -- for MySQL ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'root'; -- for Mar...
MySQL
41,645,309
557
How can I best write a query that selects 10 rows randomly from a total of 600k?
A great post handling several cases, from simple, to gaps, to non-uniform with gaps. http://jan.kneschke.de/projects/mysql/order-by-rand/ For most general case, here is how you do it: SELECT name FROM random AS r1 JOIN (SELECT CEIL(RAND() * (SELECT MAX(id) FROM rand...
MySQL
4,329,396
556
Is there any query/way to show the last queries executed on ALL servers?
For those blessed with MySQL >= 5.1.12, you can control this option globally at runtime: Execute SET GLOBAL log_output = 'TABLE'; Execute SET GLOBAL general_log = 'ON'; Take a look at the table mysql.general_log If you prefer to output to a file instead of a table: SET GLOBAL log_output = "FILE"; the default. SET GL...
MySQL
650,238
553
In another question I posted someone told me that there is a difference between: @variable and: variable in MySQL. He also mentioned how MSSQL has batch scope and MySQL has session scope. Can someone elaborate on this for me?
MySQL has a concept of user-defined variables. They are loosely typed variables that may be initialized somewhere in a session and keep their value until the session ends. They are prepended with an @ sign, like this: @var You can initialize this variable with a SET statement or inside a query: SET @var = 1 SELECT @va...
MySQL
1,009,954
551
I am learning MySQL and tried using a LOAD DATA clause. When I used it as below: LOAD DATA INFILE "text.txt" INTO table mytable; I got the following error: The MySQL server is running with the --secure-file-priv option so it cannot execute this statement How do I tackle this error? I have checked another question on...
It's working as intended. Your MySQL server has been started with --secure-file-priv option which limits from which directories you can load files using LOAD DATA INFILE. Use SHOW VARIABLES LIKE "secure_file_priv"; to see the directory that has been configured. You have two options: Move your file to the directory spe...
MySQL
32,737,478
550
When I open XAMPP and click the start MySQL button, it gives me an error. I had started it just before, but now it isn't working. 12:19:12 PM [mysql] Attempting to start MySQL app... 12:19:12 PM [mysql] Status change detected: running 12:19:13 PM [mysql] Status change detected: stopped 12:19:13 PM [mysql] Error: My...
Important: do not delete the ibdata1 file. You could destroy all your databases. Instead, first try using the MySQL backup folder which is included with XAMPP. So do next steps: Rename folder mysql/data to mysql/data_old Make a copy of mysql/backup folder and name it as mysql/data Copy all your database folders from m...
MySQL
18,022,809
544
First let me mention that I've gone through many suggested questions and found no relevent answer. Here is what I'm doing. I'm connected to my Amazon EC2 instance. I can login with MySQL root with this command: mysql -u root -p Then I created a new user bill with host % CREATE USER 'bill'@'%' IDENTIFIED BY 'passpass'...
You probably have an anonymous user ''@'localhost' or ''@'127.0.0.1'. As per the manual: When multiple matches are possible, the server must determine which of them to use. It resolves this issue as follows: (...) When a client attempts to connect, the server looks through the rows [of table mysql.user] in sorted ord...
MySQL
10,299,148
542
How can I convert entire MySQL database character-set to UTF-8 and collation to UTF-8?
Use the ALTER DATABASE and ALTER TABLE commands. ALTER DATABASE databasename CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; ALTER TABLE tablename CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; Or if you're still on MySQL 5.5.2 or older which didn't support 4-byte UTF-8, use utf8 instead of utf8mb4: AL...
MySQL
6,115,612
542
I'm creating a form for sending private messages and want to set the maxlength value of a textarea appropriate to the max length of a text field in my MySQL database table. How many characters can a type text field store? If a lot, would I be able to specify length in the database text type field as I would with varcha...
See for maximum numbers: http://dev.mysql.com/doc/refman/5.0/en/storage-requirements.html TINYBLOB, TINYTEXT L + 1 bytes, where L < 2^8 (255 Bytes) BLOB, TEXT L + 2 bytes, where L < 2^16 (64 Kilobytes) MEDIUMBLOB, MEDIUMTEXT L + 3 bytes, where L < 2^24 (16 Megabytes) LONGBLOB, LONGTEXT ...
MySQL
6,766,781
540
I am having some problems when trying to install mysql2 gem for Rails. When I try to install it by running bundle install or gem install mysql2 it gives me the following error: Error installing mysql2: ERROR: Failed to build gem native extension. How can I fix this and successfully install mysql2?
On Ubuntu/Debian and other distributions using aptitude: sudo apt-get install libmysql-ruby libmysqlclient-dev Package libmysql-ruby has been phased out and replaced by ruby-mysql. This is where I found the solution. If the above command doesn't work because libmysql-ruby cannot be found, the following should be suffi...
MySQL
3,608,287
535
We offer a platform for video- and audio-clips, photos and vector-grafics. We started with MySQL as the database backend and recently included MongoDB for storing all meta-information of the files, because MongoDB better fits the requirements. For example: photos may have Exif information, videos may have audio-tracks ...
In NoSQL: If Only It Was That Easy, the author writes about MongoDB: MongoDB is not a key/value store, it’s quite a bit more. It’s definitely not a RDBMS either. I haven’t used MongoDB in production, but I have used it a little building a test app and it is a very cool piece of kit. It seems to be very performant and ...
MySQL
1,476,295
531
MySQL 5.0.45 What is the syntax to alter a table to allow a column to be null, alternately what's wrong with this: ALTER mytable MODIFY mycolumn varchar(255) null; I interpreted the manual as just run the above and it would recreate the column, this time allowing null. The server is telling me I have syntactical erro...
You want the following: ALTER TABLE mytable MODIFY mycolumn VARCHAR(255); Columns are nullable by default. As long as the column is not declared UNIQUE or NOT NULL, there shouldn't be any problems.
MySQL
212,939
529
What is the difference between utf8mb4 and utf8 charsets in MySQL? I already know about ASCII, UTF-8, UTF-16 and UTF-32 encodings; but I'm curious to know whats the difference of utf8mb4 group of encodings with other encoding types defined in MySQL Server. Are there any special benefits/proposes of using utf8mb4 rather...
UTF-8 is a variable-length encoding. In the case of UTF-8, this means that storing one code point requires one to four bytes. However, MySQL's encoding called "utf8" (alias of "utf8mb3") only stores a maximum of three bytes per code point. So the character set "utf8"/"utf8mb3" cannot store all Unicode code points: it o...
MySQL
30,074,492
522
I have a table with a primary key that is a varchar(255). Some cases have arisen where 255 characters isn't enough. I tried changing the field to a text, but I get the following error: BLOB/TEXT column 'message_id' used in key specification without a key length how can I fix this? edit: I should also point out this ta...
The error happens because MySQL can index only the first N chars of a BLOB or TEXT column. So The error mainly happens when there is a field/column type of TEXT or BLOB or those belong to TEXT or BLOB types such as TINYBLOB, MEDIUMBLOB, LONGBLOB, TINYTEXT, MEDIUMTEXT, and LONGTEXT that you try to make a primary key or ...
MySQL
1,827,063
521
I want to copy a live production database into my local development database. Is there a way to do this without locking the production database? I'm currently using: mysqldump -u root --password=xxx -h xxx my_db1 | mysql -u root --password=xxx -h localhost my_db1 But it's locking each table as it runs.
Does the --lock-tables=false option work? According to the man page, if you are dumping InnoDB tables you can use the --single-transaction option: --lock-tables, -l Lock all tables before dumping them. The tables are locked with READ LOCAL to allow concurrent inserts in the case of MyISAM tables. For transactional tab...
MySQL
104,612
520
How can I see the list of the stored procedures or stored functions in mysql command line like SHOW TABLES; or SHOW DATABASES; commands.
SHOW PROCEDURE STATUS; SHOW FUNCTION STATUS;
MySQL
733,349
518
Is there a MySQL command to locate the my.cnf configuration file, similar to how PHP's phpinfo() locates its php.ini?
There is no internal MySQL command to trace this, it's a little too abstract. The file might be in 5 (or more?) locations, and they would all be valid because they load cascading. /etc/my.cnf /etc/mysql/my.cnf $MYSQL_HOME/my.cnf [datadir]/my.cnf ~/.my.cnf Those are the default locations MySQL looks at. If it finds ...
MySQL
2,482,234
514
I try to connect MySQL database with Java using connector 8.0.11. Everything seems to be OK, but I get this exception: Exception in thread "main" java.sql.SQLNonTransientConnectionException: Public Key Retrieval is not allowed at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:108) at ...
You should add client option to your mysql-connector allowPublicKeyRetrieval=true to allow the client to automatically request the public key from the server. Note that allowPublicKeyRetrieval=True could allow a malicious proxy to perform a MITM attack to get the plaintext password, so it is False by default and must b...
MySQL
50,379,839
510
I have upgraded my system and have installed MySql 5.7.9 with php for a web application I am working on. I have a query that is dynamically created, and when run in older versions of MySQL it works fine. Since upgrading to 5.7 I get this error: Expression #1 of SELECT list is not in GROUP BY clause and contains non-a...
I would just add group_id to the GROUP BY. When SELECTing a column that is not part of the GROUP BY there could be multiple values for that column within the groups, but there will only be space for a single value in the results. So, the database usually needs to be told exactly how to make those multiple values into ...
MySQL
34,115,174
509
I am running this query on MySQL SELECT ID FROM ( SELECT ID, msisdn FROM ( SELECT * FROM TT2 ) ); and it is giving this error: Every derived table must have its own alias. What's causing this error?
Every derived table (AKA sub-query) must indeed have an alias. I.e. each query in brackets must be given an alias (AS whatever), which can the be used to refer to it in the rest of the outer query. SELECT ID FROM ( SELECT ID, msisdn FROM ( SELECT * FROM TT2 ) AS T ) AS T In your case, of course, the en...
MySQL
1,888,779
507
I'm just getting started learning SQLite. It would be nice to be able to see the details for a table, like MySQL's DESCRIBE [table]. PRAGMA table_info [table] isn't good enough, as it only has basic information (for example, it doesn't show if a column is a field of some sort or not). Does SQLite have a way to do this?...
The SQLite command line utility has a .schema TABLENAME command that shows you the create statements.
MySQL
3,330,435
504