question
stringlengths
11
28.2k
answer
stringlengths
26
27.7k
tag
stringclasses
130 values
question_id
int64
935
78.4M
score
int64
10
5.49k
How can I find the count of all the keys that has a matching pattern. For example, there are two keys abc:random-text-1 and abc:random-text-2 . The common pattern here isabc: . So, here the count is 2. How can I do this in redis?
From here: eval "return #redis.pcall('keys', 'abc:*')" 0 It's not O(1), but at least the count is done on the server side.
Redis
20,418,529
107
I am using redis and trying to open CLI of redis using this: $redis-cli -h 127.0.0.1 -p 6379 -a mysupersecretpassword and getting and error : (error) NOAUTH Authentication required why so ?
My solution is put the password in single quotes like: $redis-cli -h 127.0.0.1 -p 6379 -a 'thisizmy!PASS'
Redis
35,745,481
104
In many Redis tutorials (such as this one), data is stored in a set, but with multiple values combined together in a string (i.e. a user account might be stored in the set as two entries, "user:1000:username" and "user:1000:password"). However, Redis also has hashes. It seems that it would make more sense to have a "us...
Redis hashes are good for storing more complex data, like you suggest in your question. I use them for exactly that - to store objects with multiple attributes that need to be cached (specifically, inventory data for a particular product on an e-commerce site). Sure, I could use a concatenated string - but that adds un...
Redis
13,557,075
102
I've been trying to get a high level understanding of what MurmurHash does. I've read a basic description but have yet to find a good explanation of when to use it and why. I know its very fast but want to know a bit more. I asked a related question about how I could fit a UUID into a Redis bitset, and someone suggest...
Murmur is a family of good general purpose hashing functions, suitable for non-cryptographic usage. As stated by Austin Appleby, MurmurHash provides the following benefits: simple (in term of number of generated assembly instructions). good distribution (passing chi-squared tests for practically all keysets & bucket s...
Redis
11,899,616
102
I'm writing an event-driven publish/subscribe application with NodeJS and Redis. I need an example of how to notify web clients when the data values in Redis change.
OLD only use a reference Dependencies uses express, socket.io, node_redis and last but not least the sample code from media fire. Install node.js+npm(as non root) First you should(if you have not done this yet) install node.js+npm in 30 seconds (the right way because you should NOT run npm as root): echo 'export PATH=$...
Redis
4,441,798
102
Can anyone give example use cases of when you would benefit from using Redis and MongoDB in conjunction with each other?
Redis and MongoDB can be used together with good results. A company well-known for running MongoDB and Redis (along with MySQL and Sphinx) is Craiglist. See this presentation from Jeremy Zawodny. MongoDB is interesting for persistent, document oriented, data indexed in various ways. Redis is more interesting for volati...
Redis
10,696,463
101
I created a Visual Studio (Community 2019) project with C# using ServiceStack.Redis. Since it is C#, I use Windows 10 (there is a Redis version for Windows but it is really old and as I know, it is unofficial so I am afraid that might be the problem). Here is an excerpt from my code: public class PeopleStorage: IDispos...
Could not load file or assembly System.Runtime.CompilerServices.Unsafe It seems that you have installed System.Runtime.CompilerServices.Unsafe nuget package 4.5.3 version. And it corresponds to System.Runtime.CompilerServices.Unsafe.dll assembly version 4.0.4.1. Suggestion 1) Please try to register System.Runtime.Com...
Redis
62,764,744
101
Suppose you have a LIST datatype in Redis. How do you delete all its entries? I've tried this already: LTRIM key 0 0 LTRIM key -1 0 Both of those leave the first element. This will leave all the elements: LTRIM key 0 -1 I don't see a separate command to completely empty a list.
Delete the key, and that will clear all items. Not having the list at all is similar to not having any items in it. Redis will not throw any exceptions when you try to access a non-existent key. DEL key Here's some console logs. redis> KEYS * (empty list or set) redis> LPUSH names John (integer) 1 redis> LPUSH names ...
Redis
9,828,160
101
I'm learning how to use Redis for a project of mine. One thing I haven't got my head around is what exactly the colons are used for in the names of keys. I have seen names of key such as these: users:bob color:blue item:bag Does the colon separate keys into categories and make finding the keys faster? If so can you us...
The colons have been in earlier redis versions as a concept for storing namespaced data. In early versions redis supported only strings, if you wanted to store the email and the age of 'bob' you had to store it all as a string, so colons were used: SET user:bob:email bob@example.com SET user:bob:age 31 They had no spe...
Redis
3,554,888
101
I am using redis for session support in nodejs app. I have installed redis server and it works when I run redis-server, but when I close terminal redis stops and does not work. How do I keep redis server running after closing the terminal?
And, if you'd like a quick option, run: redis-server --daemonize yes.
Redis
14,816,892
100
I am new with redis and I didn't figured out how to create and change to another redis database. How do I do this?
By default there are 16 databases (indexed from 0 to 15) and you can navigate between them using select command. Number of databases can be changed in redis config file with databases setting. By default, it selects the database 0. To select a specified one, use redis-cli -n 2 (selects db 2)
Redis
13,386,053
97
I have simple redis list key => "supplier_id" Now all I want it retrieve all value of list without actually iterating over or popping the value from list Example to retrieve all the value from a list Now I have iterate over redis length element = [] 0.upto(redis.llen("supplier_id")-1) do |index| element << redis.lin...
To retrieve all the items of a list with Redis, you do not need to iterate and fetch each individual items. It would be really inefficient. You just have to use the LRANGE command to retrieve all the items in one shot. elements = redis.lrange( "supplier_id", 0, -1 ) will return all the items of the list without alteri...
Redis
10,703,019
96
The hmset function can set the value of each field, but I found that if the value itself is a complex structured object, the value return from hget is a serialized string, not the original object e.g images= [{'type':'big', 'url':'....'}, {'type':'big', 'url':'....'}, {'type':'big', 'url':'....'}] redis =...
Actually, you can store python objects in redis using the built-in module pickle. Here is example. import pickle import redis r = redis.StrictRedis(host='localhost', port=6379, db=0) obj = ExampleObject() pickled_object = pickle.dumps(obj) r.set('some_key', pickled_object) unpacked_object = pickle.loads(r.get('some_ke...
Redis
15,219,858
95
Hi I'm trying to retrieve the function/method of one struct but I'm using an interface as parameter and using this interface I'm trying to access the function of the struct. To demonstrate what I want below is my code // Here I'm trying to use "GetValue" a function of RedisConnection but since "c" is an interface it do...
To answer the question directly, i.e., to cast an interface into a concrete type, you do: v = i.(T) where i is the interface and T is the concrete type. It will panic if the underlying type is not T. To have a safe cast, you use: v, ok = i.(T) and if the underlying type is not T, ok is set to false, otherwise true. N...
Redis
50,939,497
94
I see lots of people struggling with this, sort of feel like maybe there is a bug in the redis container image, and others seem to be chasing a similar problem. I'm using the standard redis image on DockerHub. (https://github.com/dockerfile/redis) running it like this: docker run -it -p 6379:6379 redis bash Once I'm i...
The problem is with your bind, You should set the following: bind 0.0.0.0 This will set redis to bind to all interfaces available, in a containerized environment with one interface, (eth0) and a loopback (lo) redis will bind to both of the above. You should consider adding security measures via other directives in con...
Redis
41,371,402
93
I have a Sorted set and want to get all members of set. How to identify a max/min score for command : zrange key min max ?
You're in luck, as zrange does not take scores, but indices. 0 is the first index, and -1 will be interpreted as the last index: zrange key 0 -1 To get a range by score, you would call zrangebyscore instead -- where -inf and +inf can be used to denote negative and positive infinity, respectively, as Didier Spezia note...
Redis
11,504,154
93
In my application im using redis database.I have gone through their documentation but i couldn't find the difference between HSET and HMSET.
HSET used to be able to set only one key-value pair. And if you needed to set several at once, you would have to use HMSET (M for multi). That was changed a few years ago, to allow both commands to accept multiple pairs. And now HMSET is redundant. From official documentation: As per Redis 4.0.0, HMSET is considered d...
Redis
15,264,480
92
I'm using memcached for some caching in my Rails 3 app through the simple Rails.cache interface and now I'd like to do some background job processing with redis and resque. I think they're different enough to warrant using both. On heroku though, there are separate fees to use both memcached and redis. Does it make sen...
Assuming that migrating from memcached to redis for the caching you already do is easy enough, I'd go with redis only to keep things simple. In redis persistence is optional, so you can use it much like memcached if that is what you want. You may even find that making your cache persistent is useful to avoid lots of c...
Redis
4,188,620
92
I'm reading the Redis documentation on persistence here - https://redis.io/topics/persistence - and am wondering what the acronyms AOF and RDB stand for. Thanks! :)
AOF stands for Append Only File. It's the change-log style persistent format. RDB is for Redis Database File. It's the snapshot style persistence format.
Redis
45,040,666
91
Is it possible in Redis to set TTL (time to live) not for a specific key, but for a member for a set? I am using a structure for tags proposed by Redis documentation - the data are simple key-value pairs, and the tags are sets containing keys corresponding to each tag, e.g. > SETEX id:id_1 100 'Lorem ipsum' OK > SADD t...
No, this isn’t possible (and not planned either). The recommended approach is to use an ordered set with score set to timestamp and then manually removing expired keys. To query for non-expired keys, you can use ZRANGEBYSCORE $now +inf, to delete expired keys, ZREMRANGEBYSCORE -inf $now will do the trick. In my applica...
Redis
17,060,672
91
Redis can do everything that Memcached provides (LRU cache, item expiry, and now clustering in version 3.x+, currently in beta) or by tools like twemproxy. The performance is similar too. Morever, Redis adds persistence due to which you need not do cache warming in case of a server restart. Reference to some old answer...
The main reason I see today as an use-case for memcached over Redis is the superior memory efficiency you should be able to get with plain HTML fragments caching (or similar applications). If you need to store different fields of your objects in different memcached keys, then Redis hashes are going to be more memory ef...
Redis
23,601,622
90
Maybe I'm just blind, but I don't see an explicit set command in Redis for emptying an existing set (without emptying the entire database). For the time being, I'm doing a set difference on the set with itself and storing it back into itself: redis> SMEMBERS metasyn 1) "foo" 2) "bar" redis> SDIFFSTORE metasyn metasyn m...
You could delete the set altogether with DEL. DEL metasyn From redis console, redis> SMEMBERS metasyn 1) "foo" 2) "bar" redis> DEL metasyn (integer) 1 redis> SMEMBERS metasyn (empty list or set)
Redis
6,301,399
90
I've been looking at Redis. It looks very interesting. But from a practical perspective, in what cases would it be better to use Redis over MySQL?
Ignoring the whole NoSQL vs SQL debate, I think the best approach is to combine them. In other words, use MySQL for for some parts of the system (complex lookups, transactions) and redis for others (performance, counters etc). In my experience, performance issues related to scalability (lots of users...) eventually f...
Redis
3,966,689
89
Does anyone know what the maximum value size you can store in redis? I want to use redis as a message queue with celery to store some small documents that need to be processed by a worker on another server, and I want to make sure the documents aren't going to be too big. I found one page with a reference to 1GB, but w...
All string values are limited to 512 MiB. This is the size limit you probably care most about. EDIT: Because keys in Redis are strings, the maximum key size is 512 MiB. The maximum number of keys is 2^32 - 1 = 4,294,967,295. Values, on the other hand, can vary in size depending on their type. For aggregate data types...
Redis
5,606,106
86
My overall question is: Using Redis for PubSub, what happens to messages when publishers push messages into a channel faster than subscribers are able to read them? For example, let's say I have: A simple publisher publishing messages at the rate of 2 msg/sec. A simple subscriber reading messages at the rate of 1 msg...
The tests are valid, but the conclusions are partially wrong. Redis does not queue anything on pub/sub channels. On the contrary, it tends to read the item from the publisher socket, and write the item in all the subscriber sockets, ideally in the same iteration of the event loop. Nothing is kept in Redis data structur...
Redis
27,745,842
85
I have a long text file of redis commands that I need to execute using the redis command line interface: e.g. DEL 9012012 DEL 1212 DEL 12214314 etc. I can't seem to figure out a way to enter the commands faster than one at a time. There are several hundred thousands lines, so I don't want to just pile them all into o...
the following code works for me with redis 2.4.7 on mac ./redis-cli < temp.redisCmds Does that satisfy your requirements? Or are you looking to see if there's a way to programmatically do it faster?
Redis
10,822,877
84
Have Redis setup with ruby on ubuntu server, but can't figure out how to access its log file. Tutorial says it should be here: /var/log/redis_6379.log But can't even find the /var/ folder
Found it with: sudo tail /var/log/redis/redis-server.log -n 100 So if the setup was more standard that should be: sudo tail /var/log/redis_6379.log -n 100 This outputs the last 100 lines of the file. Where your log file is located is in your configs that you can access with: redis-cli CONFIG GET * The log file may n...
Redis
16,337,107
83
I have downloaded redis-2.6.16.tar.gz file and i installed sucessfully. After installed i run src/redis-server it worked fine. But i don't want manually run src/redis-server everytime, rather i want redis-server running as background process continuously. So far after installed i did following tasks: 1. vim redis.conf ...
Since Redis 2.6 it is possible to pass Redis configuration parameters using the command line directly. This is very useful for testing purposes. redis-server --daemonize yes Check if the process started or not: ps aux | grep redis-server
Redis
24,221,449
80
I am trying to build a small site with the server push functionality on Flask micro-web framework, but I did not know if there is a framework to work with directly. I used Juggernaut, but it seems to be not working with redis-py in current version, and Juggernaut has been deprecated recently. Does anyone has a suggest...
Have a look at Server-Sent Events. Server-Sent Events is a browser API that lets you keep open a socket to your server, subscribing to a stream of updates. For more Information read Alex MacCaw (Author of Juggernaut) post on why he kills juggernaut and why the simpler Server-Sent Events are in manny cases the better t...
Redis
12,232,304
80
My rough understanding is that Redis is better if you need the in-memory key-value store feature, however I am not sure how that has anything to do with distributing tasks? Does that mean we should use Redis as a message broker IF we are already using it for something else?
I've used both recently (2017-2018), and they are both super stable with Celery 4. So your choice can be based on the details of your hosting setup. If you must use Celery version 2 or version 3, go with RabbitMQ. Otherwise... If you are using Redis for any other reason, go with Redis If you are hosting at AWS, go wi...
Redis
43,264,838
77
What possible reasons can Sidekiq prevent from processing jobs in the queue? The queue is full. The log file sidekiq.log indicates no activity at all. Thus the queue is full but the log is empty, and Sidekiq does not seem to process items. There seem to no worker processing jobs. Restarting Redis or flush it with FLUSH...
The reason was in our case: Sidekiq may look for the wrong queue. By default Sidekiq uses a queue named "default". We used two different queue names, and defined them in config/sidekiq.yml # configuration file for Sidekiq :queues: - queue_name_1 - queue_name_2 The problem is that this config file is not automatica...
Redis
16,835,963
77
Suppose I do this in redis at 13:30 20 Feb 2020, > set foo "bar spam" OK I want to get time of creation of foo. Is there something like > gettime foo 13:30 20 Feb 2020 ?
Redis doesn't store this information. You could use a separate key: MULTI SET foo "bar spam" SET foo:time "13:30 20 Feb 2020" EXEC GET foo:time
Redis
9,917,331
76
When we use a transaction in Redis, it basically pipelines all the commands within the transaction. And when EXEC is fired, then all the commands are executed together, thus always maintaining the atomicity of multiple commands. Isn't this same as pipelining? How are pipelining and transaction different? Also, why do...
Pipelining is primarily a network optimization. It essentially means the client buffers up a bunch of commands and ships them to the server in one go. The commands are not guaranteed to be executed in a transaction. The benefit here is saving network round trip time for every command. Redis is single threaded so an in...
Redis
29,327,544
74
For lists I can do the operation: LLEN KeyName and it will return the size of a list in Redis. What is the equivalent command for sets? I can't seem to find this in any documentation.
You are looking for the SCARD command: SCARD key Returns the set cardinality (number of elements) of the set stored at Return value Integer reply: the cardinality (number of elements) of the set, or 0 if key does not exist. Time complexity: O(1) You can view all of the set commands on the documentation webpage.
Redis
21,792,227
74
I want to use Redis as a database, not a cache. From my (limited) understanding, Redis is an in-memory datastore. What are the risks of using Redis, and how can I mitigate them?
You can use Redis as an authoritative store in a number of different ways: Turn on AOF (Append-only File store) see AOF docs. This will keep a log of all Redis commands made against your dataset in real-time. Run Redis using Master-Slave replication see replication docs. This will allow you to provide high-availabilit...
Redis
4,718,832
73
I'm using an ORM called Ohm in Ruby that works on top of Redis and am curious to find out how the data is actually stored. I was wondering if there is way to list all the keys/values in a Redis db. Update: A note for others trying this out using redis-cli, use this: $ redis-cli keys * (press * followed by Ctrl-D) ... (...
You can explore the Redis dataset using the redis-cli tool included in the Redis distribution. Just start the tool without arguments, then type commands to explore the dataset. For instance KEYS will list all the keys matching a glob-style pattern, for instance with: keys * you'll see all the keys available. Then you ...
Redis
3,798,874
73
Tearing my hair out with this one... has anyone managed to scale Socket.IO to multiple "worker" processes spawned by Node.js's cluster module? Lets say I have the following on four worker processes (pseudo): // on the server var express = require('express'); var server = express(); var socket = require('socket.io'); va...
Edit: In Socket.IO 1.0+, rather than setting a store with multiple Redis clients, a simpler Redis adapter module can now be used. var io = require('socket.io')(3000); var redis = require('socket.io-redis'); io.adapter(redis({ host: 'localhost', port: 6379 })); The example shown below would look more like this: var clu...
Redis
18,310,635
72
Here is the thing - I want to store native JS (node.js) objects (flash sockets references) in redis under a certain key. When I do that with simple client.set() it's stored as a string. When I try to get value I get [object Object] - just a string. Any chance to get this working? Here's my code: addSocket : function(...
Since the socket is of type Object, you need to convert the object to a string before storing and when retrieving the socket, need to convert it back to an object. You can use JSON.stringify(socket) to convert to a string and JSON.parse(socketstr) to convert back to an object. Edit: Since the release of version 2...
Redis
8,694,871
72
I'm using the regular redis package in order to connect my Python code to my Redis server. As part of my code I check if a string object is existed in my Redis server keys. string = 'abcde' if string in redis.keys(): do something.. For some reasons, redis.keys() returns a list with bytes objects, such as [b'abcde'],...
You can configure the Redis client to automatically convert responses from bytes to strings using the decode_responses argument to the StrictRedis constructor: r = redis.StrictRedis('localhost', 6379, charset="utf-8", decode_responses=True) Make sure you are consistent with the charset option between clients. Note You...
Redis
44,026,515
70
Lets say I have a hash of a hash e.g. $data = { 'harry' : { 'age' : 25, 'weight' : 75, }, 'sally' : { 'age' : 25, 'weight' : 75, } } What would the 'usual' way to store such a data structure (or would you not?) Would you be able to directly get a value (e.g. get harry...
What would the 'usual' way to store such a data structure (or would you not?) For example harry and sally would be stored each in separate hashes where fields would represent their properties like age and weight. Then set structure would hold all the members (harry, sally, ...) which you have stored in redis. Woul...
Redis
8,810,036
70
My Redis container is defined as a standard image in my docker_compose.yml: redis: image: redis ports: - "6379" I guess it's using standard settings like binding to Redis at localhost. I need to bind it to 0.0.0.0, is there any way to add a local redis.conf file to change the binding and let docker-compose u...
Yes. Mount the config into the image with a volume and modify the command to call it e.g: redis: image: redis command: redis-server /usr/local/etc/redis/redis.conf volumes: - ./redis.conf:/usr/local/etc/redis/redis.conf ports: - "6379" Alternatively, create a new image based on the redis image with y...
Redis
30,547,274
69
I'm writing a django management command to handle some of our redis caching. Basically, I need to choose all keys, that confirm to a certain pattern (for example: "prefix:*") and delete them. I know I can use the cli to do that: redis-cli KEYS "prefix:*" | xargs redis-cli DEL But I need to do this from within the app....
Use SCAN iterators: https://pypi.python.org/pypi/redis for key in r.scan_iter("prefix:*"): r.delete(key)
Redis
21,975,228
69
I find the configure in this, it just said the command to use the specify configure: ./redis-server <path>/redis.conf But,I have no idea about how to write the configure. So I have find the default configure in this. But, I still don't understand how to set max memory. Does it just add this line in configure? maxmemor...
Yes - to set the memory limit just uncomment the maxmemory line in the .conf file. The default is 0, which means unlimited (until the operating system runs out of RAM and kills the process - I recommend to always set maxmemory to a sane value). Updated: as @Eric Uldall mentioned in the comments, a CONFIG SET maxmemory ...
Redis
33,115,325
67
I store my data in redis. I store in one raw it guid, createday, and it size. So I define the following: var dbclient1 = db.createClient(); dbclient1.hmset("doc:3743-da23-dcdf-3213", "date", "2015-09-06 00:00:01", "size", "203") dbclient1.zadd("cache", 32131, "37463-da23-dcdf-3213") I wish to view all my files in my d...
HGETALL returns all fields and values of the hash stored at key, you can't specify a mask: http://redis.io/commands/hgetall You can call KEYS doc:* to get a list of all keys matching your criteria and then get all values in a loop. However, an important note per docs: Warning: consider KEYS as a command that should on...
Redis
30,728,973
65
From what I understand a virtual machine falls into two categories either "system virtual machine" or a "process virtual machine". It's kind of fuzzy to me where BEAM lies. Is there another kind of virtual machine I am not aware of?
The Erlang VM runs as one OS process. By default it runs one OS thread per core to achieve maximum utilisation of the machine. The number of threads and on which cores they run can be set when the VM is started. Erlang processes are implemented entirely by the Erlang VM and have no connection to either OS processes or ...
Beam
16,779,162
131
What are some fundamental Feature/Architectural difference between the BEAM and JVM? Yes I know: one was originally built around java and the other built around erlang I understand the JVM (somewhat) and want to compare their structures For example I know that the JVM has one Global GC and BEAM has one per process
First of all, Beam is a register machine, not a stack machine. Like the WAM for Prolog, it uses "X-registers" which are normal registers (implemented as an array in C), and "Y-registers" which are names for slots in the local function activation record (the "call frame") on the stack. There are no stack manipulation in...
Beam
2,276,370
22
I’ve begun studying Erlang and find the BEAM runtime environment fascinating. It’s commonly stated that in Erlang, processes belong to the language rather than the OS (meaning the runtime, meaning BEAM in this case). These are the lightweight, “green processes” that Erlang is getting famous for. It’s further stated (on...
Following @user425720's advice, I asked my question on the erlang-questions LISTSERV. It's also available as a Google Group. Kresten Krab Thorup of Trifork answered me almost at once. My thanks to go out to Kreston. Here is his answer. (Parentheticals and emphasis are mine.) Here is AFAIK, the basic scenario: Erlang...
Beam
3,663,823
18
I have a temporary situation where beam files compiled on one node are executed on another node. Are the beam files portable? How close do the versions of the Erlang distributions need to be?
Beam files are portable across nodes, as they are bytecode that is interpreted by the Erlang VM, in the same way that Java works. The exception is if they're compiled for native optimization (+native), in which case they're obviously not very portable, other than possibly between windows machines. (edit two years later...
Beam
2,255,658
15
What do the letters B. E. A. and M. stand for? I recall seeing an explanation of the acronym "BEAM", but I have not managed to find it again. It comes up in error codes: ➜ gentoo iex Erlang/OTP 17 [erts-6.4.1] [source] [64-bit] [smp:8:8] [async-threads:10] [kernel-poll:false] Interactive Elixir (1.0.4) - press Ctr...
It stands for "Bogdan/Björn's Erlang Abstract Machine" - it is just the name of the VM, much like JVM (Java Virtual Machine). Almost everyone uses "the new BEAM", where BEAM stands for Bogdan/Björn's Erlang Abstract Machine. This is the virtual machine supported in the commercial release. http://www.erlang.org/faq/im...
Beam
30,670,087
14
I know that Erlang has arbitrary size integers, but is there a max limit on one of the standard implementations? If so, what?
Erlang uses bignum arithmetic, and Integers in Erlang are limited by available memory on the machine. Virtually, there is no limit on how large an Integer can be in Erlang. Take a look on this document: http://erlang.org/doc/efficiency_guide/advanced.html It has more detailed explanations regarding limits.
Beam
39,268,564
12
I've found that Elixir programs can run C code either via NIFs (native implemented functions) or via OS-level ports. Having read those and similar links, I'm not a hundred percent clear on when to use one or the other method (or something else entirely?), and feel it would be good to have a direct comparison available,...
What are ports? Ports are basically separate programs which are run separately from the Erlang VM. The Erlang VM communicates with the running port over standard input/output, and the resulting port lives behind an Erlang process that owns it and can facilitate communication between the port and the rest of your Erlan...
Beam
42,035,912
11
I have a form on a website which has a lot of different fields. Some of the fields are optional while some are mandatory. In my DB I have a table which holds all these values, is it better practice to insert a NULL value or an empty string into the DB columns where the user didn't put any data?
By using NULL you can distinguish between "put no data" and "put empty data". Some more differences: A LENGTH of NULL is NULL, a LENGTH of an empty string is 0. NULLs are sorted before the empty strings. COUNT(message) will count empty strings but not NULLs You can search for an empty string using a bound variable but...
MySQL
1,267,999
244
I currently have just under a million locations in a mysql database all with longitude and latitude information. I am trying to find the distance between one point and many other points via a query. It's not as fast as I want it to be especially with 100+ hits a second. Is there a faster query or possibly a faster sy...
Create your points using Point values of Geometry data types in MyISAM table. As of Mysql 5.7.5, InnoDB tables now also support SPATIAL indices. Create a SPATIAL index on these points Use MBRContains() to find the values: SELECT * FROM table WHERE MBRContains(LineFromText(CONCAT( '(' ...
MySQL
1,006,654
243
I’m trying to modify a table to make its primary key column AUTO_INCREMENT after the fact. I have tried the following SQL, but got a syntax error notification. ALTER TABLE document ALTER COLUMN document_id AUTO_INCREMENT Am I doing something wrong or is this not possible? +--------------------+ | VERSION() ...
ALTER TABLE document MODIFY COLUMN document_id INT auto_increment
MySQL
2,169,080
242
I have seen many queries with something as follows: SELECT 1 FROM table What does this 1 mean, how will it be executed, and what will it return? Also, in what type of scenarios can this be used?
select 1 from table will return the constant 1 for every row of the table. It's useful when you want to cheaply determine if record matches your where clause and/or join.
MySQL
7,171,041
241
I execute an INSERT INTO statement cursor.execute("INSERT INTO mytable(height) VALUES(%s)",(height)) and I want to get the primary key. My table has 2 columns: id primary, auto increment height this is the other column. How do I get the "id", after I just inserted this?
Use cursor.lastrowid to get the last row ID inserted on the cursor object, or connection.insert_id() to get the ID from the last insert on that connection.
MySQL
2,548,493
240
I installed mySQL on my Mac. Beside starting the SQL server with mySQL.prefPane tool installed in System Preferences, I want to know the instructions to start from command-line. I do as follows: After su root I start the mySQL server by command-line, but it produces an error as below: sh-3.2# /usr/local/mysql/bin/my...
Simply: mysql.server start mysql.server stop mysql.server restart
MySQL
7,927,854
238
I'm looking to be able to run a single query on a remote server in a scripted task. For example, intuitively, I would imagine it would go something like: mysql -uroot -p -hslavedb.mydomain.com mydb_production "select * from users;"
mysql -u <user> -p -e 'select * from schema.table' (Note the use of single quotes rather than double quotes, to avoid the shell expanding the * into filenames)
MySQL
1,602,904
238
How do I drop all tables in Windows MySQL, using command prompt? The reason I want to do this is that our user has access to the database drops, but no access to re-creating the database itself, for this reason we must drop the tables manually. Is there a way to drop all the tables at once? Bear in mind that most of th...
You can generate statement like this: DROP TABLE t1, t2, t3, ... and then use prepared statements to execute it: SET FOREIGN_KEY_CHECKS = 0; SET @tables = NULL; SELECT GROUP_CONCAT('`', table_schema, '`.`', table_name, '`') INTO @tables FROM information_schema.tables WHERE table_schema = 'database_name'; -- speci...
MySQL
12,403,662
237
I've a table like: +-----------+-------+------------+ | client_id | views | percentage | +-----------+-------+------------+ | 1 | 6 | 20 | | 1 | 4 | 55 | | 1 | 9 | 56 | | 1 | 2 | 67 | | 1 | 7 | 80 | | 1 | 5 |...
You can use ORDER BY inside the GROUP_CONCAT function in this way: SELECT li.client_id, group_concat(li.views ORDER BY li.views ASC) AS views, group_concat(li.percentage ORDER BY li.views ASC) AS percentage FROM li GROUP BY client_id
MySQL
8,631,210
237
How do I change the MySQL root password and username in ubuntu server? Do I need to stop the mysql service before setting any changes? I have a phpmyadmin setup as well, will phpmyadmin get updated automatically?
Set / change / reset the MySQL root password on Ubuntu Linux. Enter the following lines in your terminal. Stop the MySQL Server: sudo /etc/init.d/mysql stop (In some cases, if /var/run/mysqld doesn't exist, you have to create it at first: sudo mkdir -v /var/run/mysqld && sudo chown mysql /var/run/mysqld Start the mysq...
MySQL
16,556,497
236
I'm trying to follow along this tutorial to enable remote access to MySQL. The problem is, where should my.cnf file be located? I'm using Mac OS X Lion.
This thread on the MySQL forum says: By default, the OS X installation does not use a my.cnf, and MySQL just uses the default values. To set up your own my.cnf, you could just create a file straight in /etc. OS X provides example configuration files at /usr/local/mysql/support-files/. And if you can't find them there...
MySQL
10,757,169
236
Having a table with a column like: mydate DATETIME ... I have a query such as: SELECT SUM(foo), mydate FROM a_table GROUP BY a_table.mydate; This will group by the full datetime, including hours and minutes. I wish to make the group by, only by the date YYYY/MM/DD not by the YYYY/MM/DD/HH/mm. How to do this?
Cast the datetime to a date, then GROUP BY using this syntax: SELECT SUM(foo), DATE(mydate) FROM a_table GROUP BY DATE(a_table.mydate); Or you can GROUP BY the alias as @orlandu63 suggested: SELECT SUM(foo), DATE(mydate) DateOnly FROM a_table GROUP BY DateOnly; Though I don't think it'll make any difference to perfor...
MySQL
366,603
235
I have a table called provider. I have three columns called person, place, thing. There can be duplicate persons, duplicate places, and duplicate things, but there can never be a dupicate person-place-thing combination. How would I ALTER TABLE to add a composite primary key for this table in MySQL with the these three ...
ALTER TABLE provider ADD PRIMARY KEY(person,place,thing); If a primary key already exists then you want to do this ALTER TABLE provider DROP PRIMARY KEY, ADD PRIMARY KEY(person, place, thing);
MySQL
8,859,353
234
I need to change my column type from date to datetime for an app I am making. I don't care about the data as its still being developed. How can I do this?
First in your terminal: rails g migration change_date_format_in_my_table Then in your migration file: For Rails >= 3.2: class ChangeDateFormatInMyTable < ActiveRecord::Migration def up change_column :my_table, :my_column, :datetime end def down change_column :my_table, :my_column, :date end end
MySQL
5,191,405
234
I need to do a mysqldump of a database on a remote server, but the server does not have mysqldump installed. I would like to use the mysqldump on my machine to connect to the remote database and do the dump on my machine. I have tried to create an ssh tunnel and then do the dump, but this does not seem to work. I tried...
As I haven't seen it at serverfault yet, and the answer is quite simple: Change: ssh -f -L3310:remote.server:3306 user@remote.server -N To: ssh -f -L3310:localhost:3306 user@remote.server -N And change: mysqldump -P 3310 -h localhost -u mysql_user -p database_name table_name To: mysqldump -P 3310 -h 127.0.0.1 -u my...
MySQL
2,989,724
234
The MySQL reference manual does not provide a clearcut example on how to do this. I have an ENUM-type column of country names that I need to add more countries to. What is the correct MySQL syntax to achieve this? Here's my attempt: ALTER TABLE carmake CHANGE country country ENUM('Sweden','Malaysia'); The error I get ...
ALTER TABLE `table_name` MODIFY COLUMN `column_name2` enum( 'existing_value1', 'existing_value2', 'new_value1', 'new_value2' ) NOT NULL AFTER `column_name1`;
MySQL
1,501,958
234
Is there a way in a MySQL statement to order records (through a date stamp) by >= NOW() -1 so all records from the day before today to the future are selected?
Judging by the documentation for date/time functions, you should be able to do something like: SELECT * FROM FOO WHERE MY_DATE_FIELD >= NOW() - INTERVAL 1 DAY
MySQL
8,544,438
233
I've read that Mysql server creates a log file where it keeps a record of all activities - like when and what queries execute. Can anybody tell me where it exists in my system? How can I read it? Basically, I need to back up the database with different input [backup between two dates] so I think I need to use log fil...
Here is a simple way to enable them. In mysql we need to see often 3 logs which are mostly needed during any project development. The Error Log. It contains information about errors that occur while the server is running (also server start and stop) The General Query Log. This is a general record of what mysqld is doi...
MySQL
5,441,972
233
I have two tables, one for job deadlines, one for describe a job. Each job can take a status and some statuses means the jobs' deadlines must be deleted from the other table. I can easily SELECT the jobs/deadlines that meets my criteria with a LEFT JOIN: SELECT * FROM `deadline` LEFT JOIN `job` ON deadline.job_id = job...
You simply need to specify on which tables to apply the DELETE. Delete only the deadline rows: DELETE `deadline` FROM `deadline` LEFT JOIN `job` .... Delete the deadline and job rows: DELETE `deadline`, `job` FROM `deadline` LEFT JOIN `job` .... Delete only the job rows: DELETE `job` FROM `deadline` LEFT JOIN `job` ...
MySQL
2,763,206
233
I have a perplexing issue that I can't seem to comprehend... I have two SQL statements: The first enters information from a form into the database. The second takes data from the database entered above, sends an email, and then logs the details of the transaction The problem is that it appears that a single quote is ...
You should be escaping each of these strings (in both snippets) with mysql_real_escape_string(). https://www.php.net/mysql-real-escape-string The reason your two queries are behaving differently is likely because you have magic_quotes_gpc turned on (which you should know is a bad idea). This means that strings gathere...
MySQL
2,687,866
233
There are many conflicting statements around. What is the best way to get the row count using PDO in PHP? Before using PDO, I just simply used mysql_num_rows. fetchAll is something I won't want because I may sometimes be dealing with large datasets, so not good for my use. Do you have any suggestions?
When you need only the number of rows, but not the data itself, such a function shouldn't be used anyway. Instead, ask the database to do the count, with a code like this: $sql = "SELECT count(*) FROM `table` WHERE foo = ?"; $result = $con->prepare($sql); $result->execute([$bar]); $number_of_rows = $result->fetchCol...
MySQL
883,365
233
I want to order by Time,but seems no way to do that ? mysql> show processlist; +--------+-------------+--------------------+------+---------+--------+----------------------------------+------------------------------------------------------------------------------------------------------+ | Id | User | Host ...
Newer versions of SQL support the process list in information_schema: SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST You can ORDER BY in any way you like. The INFORMATION_SCHEMA.PROCESSLIST table was added in MySQL 5.1.7. You can find out which version you're using with: SELECT VERSION()
MySQL
929,612
232
I am trying to understand how to UPDATE multiple rows with different values and I just don't get it. The solution is everywhere but to me it looks difficult to understand. For instance, three updates into 1 query: UPDATE table_users SET cod_user = '622057' , date = '12082014' WHERE user_rol = 'student' AND cod_...
You can do it this way: UPDATE table_users SET cod_user = (case when user_role = 'student' then '622057' when user_role = 'assistant' then '2913659' when user_role = 'admin' then '6160230' end), date = '12082014' WHERE user_role in ('...
MySQL
25,674,737
231
What's the main difference between length() and char_length()? I believe it has something to do with binary and non-binary strings. Is there any practical reason to store strings as binary? mysql> select length('MySQL'), char_length('MySQL'); +-----------------+----------------------+ | length('MySQL') | char_length('...
LENGTH() returns the length of the string measured in bytes. CHAR_LENGTH() returns the length of the string measured in characters. This is especially relevant for Unicode, in which most characters are encoded in two bytes. Or UTF-8, where the number of bytes varies. For example: select length(_utf8 '€'), char_leng...
MySQL
1,734,334
231
I have a table whose primary key is used in several other tables and has several foreign keys to other tables. CREATE TABLE location ( locationID INT NOT NULL AUTO_INCREMENT PRIMARY KEY ... ) ENGINE = InnoDB; CREATE TABLE assignment ( assignmentID INT NOT NULL AUTO_INCREMENT PRIMARY KEY, locationID INT NO...
As explained here, seems the foreign key constraint has to be dropped by constraint name and not the index name. The syntax is: ALTER TABLE footable DROP FOREIGN KEY fooconstraint;
MySQL
838,354
231
Scenario in short: A table with more than 16 million records [2GB in size]. The higher LIMIT offset with SELECT, the slower the query becomes, when using ORDER BY *primary_key* So SELECT * FROM large ORDER BY `id` LIMIT 0, 30 takes far less than SELECT * FROM large ORDER BY `id` LIMIT 10000, 30 That only o...
I had the exact same problem myself. Given the fact that you want to collect a large amount of this data and not a specific set of 30 you'll be probably running a loop and incrementing the offset by 30. So what you can do instead is: Hold the last id of a set of data(30) (e.g. lastId = 530) Add the condition WHERE id ...
MySQL
4,481,388
230
If you try to create a TEXT column on a table, and give it a default value in MySQL, you get an error (on Windows at least). I cannot see any reason why a text column should not have a default value. No explanation is given by the MySQL documentation. It seems illogical to me (and somewhat frustrating, as I want a defa...
Windows MySQL v5 throws an error but Linux and other versions only raise a warning. This needs to be fixed. WTF? Also see an attempt to fix this as bug #19498 in the MySQL Bugtracker: Bryce Nesbitt on April 4 2008 4:36pm: On MS Windows the "no DEFAULT" rule is an error, while on other platforms it is often a warni...
MySQL
3,466,872
230
Is there a way to check if a table exists without selecting and checking values from it? That is, I know I can go SELECT testcol FROM testtable and check the count of fields returned, but it seems there must be a more direct / elegant way to do it.
If you want to be correct, use INFORMATION_SCHEMA. SELECT * FROM information_schema.tables WHERE table_schema = 'yourdb' AND table_name = 'testtable' LIMIT 1; Alternatively, you can use SHOW TABLES SHOW TABLES LIKE 'yourtable'; If there is a row in the resultset, table exists.
MySQL
8,829,102
229
Here is a gross oversimplification of an intense setup I am working with. table_1 and table_2 both have auto-increment surrogate primary keys as the ID. info is a table that contains information about both table_1 and table_2. table_1 (id, field) table_2 (id, field, field) info ( ???, field) I am trying to decided i...
I would use a composite (multi-column) key. CREATE TABLE INFO ( t1ID INT, t2ID INT, PRIMARY KEY (t1ID, t2ID) ) This way you can have t1ID and t2ID as foreign keys pointing to their respective tables as well.
MySQL
5,835,978
229
I accidentally installed the PowerPC version of MySQL on my Intel Mac in Snow Leopard, and it installed without a problem but of course doesn't run properly. I just didn't pay enough attention. Now when I try to install the correct x86 version it says that it can't install because a newer version is already installed. ...
Try running also sudo rm -rf /var/db/receipts/com.mysql.*
MySQL
1,436,425
229
I recently installed MySQL and it seems I have to reset the password after install. It won't let me do anything else. Now I already reset the password the usual way: update user set password = password('XXX') where user = root; (BTW: took me ages to work out that MySQL for some bizarre reason has renamed the field 'pa...
If this is NOT your first time setting up the password, try this method: mysql> UPDATE mysql.user SET Password=PASSWORD('your_new_password') WHERE User='root'; And if you get the following error, there is a high chance that you have never set your password before: ERROR 1820 (HY000): You must reset your pa...
MySQL
33,467,337
228
In MySQL, is there a way to set the "total" fields to zero if they are NULL? Here is what I have: SELECT uo.order_id, uo.order_total, uo.order_status, (SELECT SUM(uop.price * uop.qty) FROM uc_order_products uop WHERE uo.order_id = uop.order_id ) AS products_subtotal, ...
Use IFNULL: IFNULL(expr1, 0) From the documentation: If expr1 is not NULL, IFNULL() returns expr1; otherwise it returns expr2. IFNULL() returns a numeric or string value, depending on the context in which it is used.
MySQL
3,997,327
228
I'm using the below code to pull some results from the database with Laravel 5. BookingDates::where('email', Input::get('email'))->orWhere('name', 'like', Input::get('name'))->get() However, the orWhereLike doesn't seem to be matching any results. What does that code produce in terms of MySQL statements? I'm trying t...
If you want to see what is run in the database use dd(DB::getQueryLog()) to see what queries were run. Try this BookingDates::where('email', Input::get('email')) ->orWhere('name', 'like', '%' . Input::get('name') . '%')->get();
MySQL
30,761,950
227
Are table names in MySQL case sensitive? On my Windows development machine the code I have is able to query my tables which appear to be all lowercase. When I deploy to the test server in our datacenter the table names appear to start with an uppercase letter. The servers we use are all on Ubuntu.
In general: Database and table names are not case sensitive in Windows, and case sensitive in most varieties of Unix. In MySQL, databases correspond to directories within the data directory. Each table within a database corresponds to at least one file within the database directory. Consequently, the case sensitiv...
MySQL
6,134,006
227
What's the best way to do following: SELECT * FROM users WHERE created >= today; Note: created is a datetime field.
SELECT * FROM users WHERE created >= CURDATE(); But I think you mean created < today You can compare datetime with date, for example: SELECT NOW() < CURDATE() gives 0, SELECT NOW() = CURDATE() gives 1.
MySQL
5,182,275
226
What is the best SQL data type for currency values? I'm using MySQL but would prefer a database independent type.
Something like Decimal(19,4) usually works pretty well in most cases. You can adjust the scale and precision to fit the needs of the numbers you need to store. Even in SQL Server, I tend not to use "money" as it's non-standard.
MySQL
628,637
226
In MySQL, can I select columns only where something exists? For example, I have the following query: select phone, phone2 from jewishyellow.users where phone like '813%' and phone2 I'm trying to select only the rows where phone starts with 813 and phone2 has something in it.
Compare value of phone2 with empty string: select phone, phone2 from jewishyellow.users where phone like '813%' and phone2<>'' Note that NULL value is interpreted as false.
MySQL
1,869,264
224
I had this previously in my normal mysql_* connection: mysql_set_charset("utf8",$link); mysql_query("SET NAMES 'UTF8'"); Do I need it for the PDO? And where should I have it? $connect = new PDO("mysql:host=$host;dbname=$db", $user, $pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
You'll have it in your connection string like: "mysql:host=$host;dbname=$db;charset=utf8mb4" HOWEVER, prior to PHP 5.3.6, the charset option was ignored. If you're running an older version of PHP, you must do it like this: $dbh = new PDO("mysql:host=$host;dbname=$db", $user, $password); $dbh->exec("set names utf8mb4"...
MySQL
4,361,459
223
Is there a way to detect if a value is a number in a MySQL query? Such as SELECT * FROM myTable WHERE isANumber(col1) = true
You can use Regular Expression too... it would be like: SELECT * FROM myTable WHERE col1 REGEXP '^[0-9]+$'; Reference: http://dev.mysql.com/doc/refman/5.1/en/regexp.html
MySQL
5,064,977
222
I'm trying to figure out how to locate all occurrences of a url in a database. I want to search all tables and all fields. But I have no idea where to start or if it's even possible.
A simple solution would be doing something like this: mysqldump -u myuser --no-create-info --extended-insert=FALSE databasename | grep -i "<search string>"
MySQL
562,457
222
I am not very familiar with databases and the theories behind how they work. Is it any slower from a performance standpoint (inserting/updating/querying) to use Strings for Primary Keys than integers? For Example I have a database that would have about 100 million row like mobile number, name and email. mobile number ...
Technically yes, but if a string makes sense to be the primary key then you should probably use it. This all depends on the size of the table you're making it for and the length of the string that is going to be the primary key (longer strings == harder to compare). I wouldn't necessarily use a string for a table that...
MySQL
517,579
222
To find out the start command for mysqld (using a mac) I can do: ps aux|grep mysql I get the following output, which allows me to start mysql server. /usr/local/mysql/bin/mysqld --basedir=/usr/local/mysql --datadir=... How would I find the necessary command to stop mysql from the command line?
Try: /usr/local/mysql/bin/mysqladmin -u root -p shutdown Or: sudo mysqld stop Or: sudo /usr/local/mysql/bin/mysqld stop Or: sudo mysql.server stop If you install the Launchctl in OSX you can try: MacPorts sudo launchctl unload -w /Library/LaunchDaemons/org.macports.mysql.plist sudo launchctl load -w /Library/Launc...
MySQL
11,091,414
221
I have the following table schema which maps user_customers to permissions on a live MySQL database: mysql> describe user_customer_permission; +------------------+---------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------------+---------+-----...
Without an index, maintaining an autoincrement column becomes too expensive, that's why MySQL requires an autoincrement column to be a leftmost part of an index. You should remove the autoincrement property before dropping the key: ALTER TABLE user_customer_permission MODIFY id INT NOT NULL; ALTER TABLE user_customer_p...
MySQL
2,111,291
221
create table check2(f1 varchar(20),f2 varchar(20)); creates a table with the default collation latin1_general_ci; alter table check2 collate latin1_general_cs; show full columns from check2; shows the individual collation of the columns as 'latin1_general_ci'. Then what is the effect of the alter table command?
To change the default character set and collation of a table including those of existing columns (note the convert to clause): alter table <some_table> convert to character set utf8mb4 collate utf8mb4_unicode_ci; Edited the answer, thanks to the prompting of some comments: Should avoid recommending utf8. It's almost ...
MySQL
742,205
221
I'm stumped, I don't know how to go about doing this. Basically I just want to create a table, but if it exists it needs to be dropped and re-created, not truncated, but if it doesn't exist just create it. Would anyone be able to help?
Just put DROP TABLE IF EXISTS `tablename`; before your CREATE TABLE statement. That statement drops the table if it exists but will not throw an error if it does not.
MySQL
20,155,989
220
I am continuously receiving this error. I am using mySQL Workbench and from what I am finding is that root's schema privileges are null. There are no privileges at all. I am having troubles across platforms that my server is used for and this has been all of a sudden issue. root@127.0.0.1 apparently has a lot of access...
If you have that same problem in MySql 5.7.+ : Access denied for user 'root'@'localhost' it's because MySql 5.7 by default allow to connect with socket, which means you just connect with sudo mysql. If you run sql : SELECT user,authentication_string,plugin,host FROM mysql.user; then you will see it : +---------------...
MySQL
17,975,120
220
So here's what I want to do on my MySQL database. I would like to do: SELECT * FROM itemsOrdered WHERE purchaseOrder_ID = '@purchaseOrdered_ID' AND status = 'PENDING' If that would not return any rows, which is possible through if(dr.HasRows == false), I would now create an UPDATE in the purchaseOrder ...
For your specific query, you can do: UPDATE purchaseOrder SET purchaseOrder_status = 'COMPLETED' WHERE purchaseOrder_ID = '@purchaseOrder_ID' and not exists (SELECT * FROM itemsOrdered WHERE purchaseOrder_ID = '@purchaseOrdered_ID' AND status = 'PENDING' ) H...
MySQL
13,991,817
220
Our previous programmer set the wrong collation in a table (Mysql). He set it up with Latin collation, when it should be UTF8, and now I have issues. Every record with Chinese and Japan character turn to ??? character. Is possible to change collation and get back the detail of character?
change database collation: ALTER DATABASE <database_name> CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci; change table collation: ALTER TABLE <table_name> CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci; change column collation: ALTER TABLE <table_name> MODIFY <column_name> VARCHAR(255) CHARACTER SET ut...
MySQL
5,906,585
220
Well here's my problem I have three tables; regions, countries, states. Countries can be inside of regions, states can be inside of regions. Regions are the top of the food chain. Now I'm adding a popular_areas table with two columns; region_id and popular_place_id. Is it possible to make popular_place_id be a forei...
What you're describing is called Polymorphic Associations. That is, the "foreign key" column contains an id value that must exist in one of a set of target tables. Typically the target tables are related in some way, such as being instances of some common superclass of data. You'd also need another column along side...
MySQL
441,001
220