So I'm really new to learning SQL and I'm interested about the command
SELECT DATABASE();
At my point in learning, I know that command is used to show what database I'm currently working with. I accidentally made the typo,
SELECT DATABASE() L; and the MySQL terminal displayed the letter L above the name of the database I was working with. Why does this happen? And what exactly does SELECT DATABASE() mean?
I tried this again and did the command
SELECT DATABASE() HI; and it did the same thing and showed "HI" above the name of my selected database. Using the correct syntax, it normally shows, "DATABASE()" above the db that I'm currently working with.
database() is an information function provided by MySQL to return the name of the current database. It can be used anywhere a string constant would be expected.
MySQL does not require a from clause, so a select is a complete query that returns one row -- the values calculated in the select.
Databases allow you to assign a name ("column alias") to an expression in the select. Normally, this would be written as:
select database() as database_name
However, the as is optional (although I strongly recommend using it for column aliases). And nothing enforces a reasonable name.
So:
select database() l
returns a result set with one row and one column. The column is called l and the value in the one row is the database name.
You are selecting a dataset with one column. The contents of the column is the current database. You are naming that column L.
Compare with
select 4 label;
I am not expert in database. But I am quite sure that show database(); will show you the selected database in other words the database which you have chosen.
Related
I'm trying select all values if such table exists. If it doesn't exist, just leave it.
I'm trying to do this only in one MYSQL code. Not with the help of python or something.
SELECT CASE WHEN (SELECT count(*)
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = '{db0}' AND TABLE_NAME = '{table0}')=0
THEN 'None' ELSE (SELECT MAX({colname}) FROM {db0}.{table0}) END;
If i inject existing table name on it, it works well.
But if not , it shows the error sign that saying such table doesn't exist.(Table 'corps.060311' doesn't exist)
What should I do?
This cannot be achieved using a simple query because MySQL analyses the query as a whole before performing it: it is not a procedural language and the queries are never executed line by line.
To do what you want to do without help of any other language, you must use stored procedures: https://dev.mysql.com/doc/refman/8.0/en/create-procedure.html
So the first step is to add a new FUNCTION in your database that will contain the "if table exists" part (see https://dev.mysql.com/doc/refman/8.0/en/if.html for if statements) and will return the desired value based on the schema, table, and column provided as strings in input of the function.
Then you can use the FUNCTION in any query in your database.
I have a database with tables and I need to work with inputs from java. For that, I need to know if the input from java can be inserted to the database by not overloading the length of a column. I've tried using SELECT COLUMNPROPERTY( OBJECT_ID('utilizador'),'U_NOME','PRECISION'); but it is giving me an error saying
SQL Error (1305):FUNCTION bd.COLUMNPROPERTY does not exist
Could some one please help me?
Once again, I'm trying to get the maximum input value that can be inserted to the column, not some that already exists. I just need to know which is the biggest size that I can insert. Per example, if I have a column named U_NOME and its a char with length 30, I want to get the 30, not the lenght of some data that already is in that column.
Thank you.
COLUMNPROPERTY is a SQL Server-specific function.
Based on your error code, it appears you're using MySQL, which doesn't implement COLUMNPROPERTY. Use the INFORMATION_SCHEMA database's COLUMN to query the length of the column in question:
SELECT CHARACTER_MAXIMUM_LENGTH
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME = "u_nome"
AND TABLE_NAME = "utilizador"
AND TABLE_SCHEMA="<database_name>"
You can try DESCRIBE your_table_here. This will give the table column information.
Examples and details of other options from MySQL are:
Explain / Describe
SHOW COLUMNS
In SQL Server you can do the below
SELECT Top 1 DATALENGTH(U_NOME) FROM utilizador
In MySQl it would be
Select LENGTH(U_NOME) FROM utilizador LIMIT 1
I have the following problem. I have Table A and would like to join to table B if table B exists. Can this be done? I am only writing SQL in WorkBench to try achieve it.
I am aware I cannot use the EXISTS option as I have tried typing it out but it prompts for an error.
Any suggestions would be greatly appreciated.
Thanks.
I managed to do this using EXECUTE, so using a query that is only prepared at runtime:
SET #sqlCommand = IF(
EXISTS (SELECT column_name FROM information_schema.columns WHERE table_schema = '{{yourschemaname}}' AND table_name = '{{yourtablename}}' AND column_name = '{{yourcolumnname}}'),
'SELECT \'Yes! Good to go!\' as ColumnExists',
'SELECT \'Nope!\' as ColumnExists');
PREPARE executable FROM #sqlCommand;
EXECUTE executable;
Note that the two selects at the center (Yes!/No!) are the custom statements that are to be executed conditionally. So if the column exists, the first command is executed (select 'yes!'), otherwise the second one (select 'nope').
I got the hint from this discussion here.. have a look if you're looking for the MSSQL equivalent: https://ask.sqlservercentral.com/questions/97579/check-if-table-exists-in-join.html
Data manipulation language statements are typically written for a specific schema; you are assumed to know what the schema looks like when you issue the statement. So you don't generally have the capacity to ask whether a particular schema object exists or has a particular structure. You could however write a stored procedure that did different things depending upon the schema. You have the ability in a stored procedure to use conditional statements and to look in INFORMATION_SCHEMA.
I have just noticed that where mysql_num_rows should return the number of rows returned for either SELECT or SHOW commands, returns 0 for SHOW TABLE command specifically.
Instead it shows the affected rows count instead of the num rows.
Can anyone please tell me if this is a bug or if am I missing anything here?
SHOW TABLE command is used to Show you table name in your database . On the other hand , mysql_num_rows is used to count how many result got from your query. This query is depend on your requirement basis ...
As stated on the PHP documentation page:
Retrieves the number of rows from a result set. This command is only
valid for statements like SELECT or SHOW that return an actual result
set.
My guess is that SHOW TABLES is not a technical query that would produce the type of result set that mysql_num_rows enumerates.
These "helper" functions (such as SHOW, EXPLAIN, DESCRIBE etc.) won't let you issue their results like you would in a regular table.
But if you're looking for how you can do this, for SHOW TABLES you can do
SELECT `table_name` FROM `information_schema`.`tables`
WHERE `table_schema`=DATABASE()
-- DATABASE() selects current database name
-- you can use the name of any database as a string instead
So basically you can use the information_schema database to get that information.
It was a bug in mysql, fixed it with the update.
I have a Moodle installation that I migrated to another server and I need to change several references to the old domain.
How can I replace a string for another string in MySQL for a given database searching all tables, all fields, and all rows?
I don't need to change the field names, just the values.
Related: How can I use mySQL replace() to replace strings in multiple records?
But the marked as answer solution implies I strongly type the table name and I need to fire this into an entire database, not manually work on each table running the script N times.
This may seem a bit ... ugly. But maybe simply dump the database to a sql/txt file, replace all strings and recreate the database using the modified dump.
You could run the following code to create all the udpate statements you would need to run to do your updates. It would update every field in every table within your database. You would need to run this code, and copy the results and run them.
WARNING - Be sure to test this in a test environment. You don't want any unpleasant surprises. Modify as needed.
SELECT concat('UPDATE ', TABLE_NAME, ' SET ', COLUMN_NAME, ' = REPLACE(', COLUMN_NAME, ', ''STRING_TO_REPLACE'', ''REPLACE_STRING'')')
FROM INFORMATION_SCHEMA.COLUMNS c
WHERE TABLE_SCHEMA = 'YOUR_DATABASE_NAME'
AND DATA_TYPE IN ('char', 'varchar')
;
I limited this to only char and varchar fields. You may need to add additional data types.
I would consider querying INFORMATION_SCHEMA.COLUMNS and dynamically searching the columns and tables. Try something like creating a cursor of all the columns and tables in the db:
DECLARE col_names CURSOR FOR
SELECT column_name, table_name
FROM INFORMATION_SCHEMA.COLUMNS
Then iterate through each of the columns in each of the tables and run dynamic/prepared sql to update where the string exists.
Here are a couple of good posts to get you in the right direction:
https://stackoverflow.com/a/4951354/1073631
https://stackoverflow.com/a/5728155/1073631