Is there any way to later output the name of the database that is currently selected?
5 Answers
Just use mysql_query (or mysqli_query, even better, or use PDO, best of all) with:
SELECT DATABASE();
Addendum:
There is much discussion over whether or not FROM DUAL
should be included in this or not. On a technical level, it is a holdover from Oracle and can safely be removed. If you are inclined, you can use it as follows:
SELECT DATABASE() FROM DUAL;
That said, it is perhaps important to note, that while FROM DUAL
does not actually do anything, it is valid MySQL syntax. From a strict perspective, including braces in a single line conditional in JavaScript also does not do anything, but it is still a valid practice.
-
11DUAL is an Oracle table, that was taken over into MySQL. It's a dummy table for operations that do not require an actual table. en.wikipedia.org/wiki/DUAL_table Nov 11, 2011 at 16:03
-
12@DigitalPrecision It is a holdover from the fact that I've done a lot of work with Oracle. Oracle does not allow you to select unless it is from something, so there is a special table called "DUAL" which has only one cell in it. You can omit it. Nov 11, 2011 at 16:09
-
3Probably should edit this keeping the existing answer for posterity but adding
SELECT DATABASE();
as the "actual" answer.– UserAug 19, 2014 at 2:53 -
-
1@PardeepJain that is outside my area of expertise maybe cwallenpoole can answer that. Feb 26, 2018 at 7:32
SELECT DATABASE();
p.s. I didn't want to take the liberty of modifying @cwallenpoole's answer to reflect the fact that this is a MySQL question and not an Oracle question and doesn't need DUAL
.
-
5Old habits die hard. I still sometimes think "FROM DUAL" even though I haven't touched Oracle since 2011. Aug 20, 2014 at 2:33
-
6Yep. Still thinking FROM DUAL even though I haven't touched Oracle since 2011. May 12, 2016 at 3:18
-
13
-
3
-
5
-
although not reflected in the output above, on my system, it also shows the TCP port, which is handy for me since I'm running mysqld_multi and I like to remind myself which instance I'm talking to.– JeffMay 28, 2018 at 20:30
slightly off-topic (using the CLI instead of PHP), but still worth knowing: You can set the prompt to display the default database by using any of the following
mysql --prompt='\d> '
export MYSQL_PS1='\d> '
or once inside
prompt \d>\_
\R \d>\_
Another way for filtering the database with specific word.
SHOW DATABASES WHERE `Database` LIKE '<yourDatabasePrefixHere>%'
or
SHOW DATABASES LIKE '<yourDatabasePrefixHere>%';
Example:
SHOW DATABASES WHERE `Database` LIKE 'foobar%'
foobar_animal
foobar_humans_gender
foobar_objects
-
Question is to show which is the currently selected database, however your reply is showing procedure to filter database. Correct way is to run: SELECT DATABASE(); Jun 21, 2022 at 22:16
-
I think you missed the intro text 'Another way...' The Accepted answer already mentioned
SELECT DATABASE();
.– DexterJun 22, 2022 at 10:29