SQLite: How to add a column to all the tables in the database? - sql

I am quite new to SQLite (SQL overall). I created a database and created multiple tables in it and suddenly realized I had forgot to add a column to them. Now I have 280 tables having distinct names without a column. I have tried adding * and combining with SELECT but it gives an error. How can I accomplish it?
my code:
ALTER TABLE "MYBUS.*" ADD COLUMN STOPID int null;

After 3 hours issue finally solved.
After searching for sometime, I stumbled upon this answer
SQlite alter table with result from select statement
I ran the code:select 'alter table '||tbl_name||' add STOPID int null' from sqlite_master
It returned all the 280 SQL queries needed but with quotation marks, so I took the clue from this.lau and created a python regex script and ran it. Worked like a charm and within 10 lines of code I was able to add a column to all my 280 tables.

See this link https://dba.stackexchange.com/questions/160145/add-columns-to-all-tables-in-a-database-if-the-columns-dont-exist
Even though it applies to SQL Server, this should help you in getting started.
Ensure that you perform a check on the column name before adding it to a table.

Related

Azure Data Studio not respect specified casing with PostgreSQL [duplicate]

I'm writing a Java application to automatically build and run SQL queries. For many tables my code works fine but on a certain table it gets stuck by throwing the following exception:
Exception in thread "main" org.postgresql.util.PSQLException: ERROR: column "continent" does not exist
Hint: Perhaps you meant to reference the column "countries.Continent".
Position: 8
The query that has been run is the following:
SELECT Continent
FROM network.countries
WHERE Continent IS NOT NULL
AND Continent <> ''
LIMIT 5
This essentially returns 5 non-empty values from the column.
I don't understand why I'm getting the "column does not exist" error when it clearly does in pgAdmin 4. I can see that there is a schema with the name Network which contains the table countries and that table has a column called Continent just as expected.
Since all column, schema and table names are retrieved by the application itself I don't think there has been a spelling or semantical error so why does PostgreSQL cause problems regardless? Running the query in pgAdmin4 nor using the suggested countries.Continent is working.
My PostgreSQL version is the newest as of now:
$ psql --version
psql (PostgreSQL) 9.6.1
How can I successfully run the query?
Try to take it into double quotes - like "Continent" in the query:
SELECT "Continent"
FROM network.countries
...
In working with SQLAlchemy environment, i have got this error with the SQL like this,
db.session.execute(
text('SELECT name,type,ST_Area(geom) FROM buildings WHERE type == "plaza" '))
ERROR: column "plaza" does not exist
Well, i changed == by = , Error still persists, then i interchanged the quotes, like follows. It worked. Weird!
....
text("SELECT name,type,ST_Area(geom) FROM buildings WHERE type = 'plaza' "))
This problem occurs in postgres because the table name is not tablename instead it is "tablename".
for eg.
If it shows user as table name,
than table name is "user".
See this:
Such an error can appear when you add a space in the name of a column by mistake (for example "users ").
QUICK FIX (TRICK)
If you have recently added a field which you have already deleted before and now trying to add the same field back then let me share you this simple trick! i did this and the problem was gone!!
so, now just delete the migration folder entirely on the app,then instead of adding that field you need to now add a field but with the name of which you have never declared on this app before, example if you are trying to add title field then create it by the name of heading and now do the migration process separately on the app and runserver, now go to admin page and look for that model and delete all the objects and come to models back and rename the field that you recently made and name it to which you were wishing it with earlier and do the migrations again and now your problem must have been gone!!
this occurs when the objects are there in the db but you added a field which wasn't there when the earlier objs were made, so by this we can delete those objs and make fresh ones again!
I got the same error when I do PIVOT in RedShift.
My code is similar to
SELECT *
INTO output_table
FROM (
SELECT name, year_month, sales
FROM input_table
)
PIVOT
(
SUM(sales)
FOR year_month IN ('nov_2020', 'dec_2020', 'jan_2021', 'feb_2021', 'mar_2021', 'apr_2021', 'may_2021', 'jun_2021', 'jul_2021', 'aug_2021',
'sep_2021', 'oct_2021', 'nov_2021', 'dec_2021', 'jan_2022', 'feb_2022', 'mar_2022', 'apr_2022', 'may_2022', 'jun_2022',
'jul_2022', 'aug_2022', 'sep_2022', 'oct_2022', 'nov_2022')
)
I tried year_month without any quote (got the error), year_month with double quote (got the error), and finally year_month with single quote (it works this time). This may help if someone in the same situation like my example.

Best way to duplicate data in the same table and updating a column at the same time

I'm trying to find the best way to duplicate all the rows in a table.By this i mean inserting them again in the same table, but i need to update a single column only on the values that were inserted.
This is to help me write a script so I can automate some work on some clients.
I can't use select * as it will throw an error because of the identity columns but at the same time i don't want to be manually writting all the column names for several tables.
Is there a simple way to translate this into SQL server?
Sorry for not showing a piece of code, but i have nothing at the moment and i'm not really fluent in SQL.
EDIT: I have ended up following the advice of JamieD77 in the comments below this post by moving everything to a table, drop the id column, updating what i need and then moving back as it seems to be the most effiecient.
In SQL Server Management Studio you can drag the "Columns" folder under a table and drop it on the query window and it will paste a comma-delimited list of all the columns.
Or run a query like:
select string_agg(quotename(name),', ')
from sys.columns
where object_id = object_id('MyTable')

Copy all columns without data but with dependencies in SQL [duplicate]

This question already has answers here:
In SQL Server, how do I generate a CREATE TABLE statement for a given table?
(16 answers)
Closed 5 years ago.
So i'm trying to copy all data of table CarOrders into a new table, NewCarOrders. But i only want to copy columns and dependencies and not data. I don't know if it truly matters, but i'm using SQL Server Management Studio.
Here are two things that i tried, but none worked.
SELECT *
INTO NewCarOrders
FROM CarOrders
WHERE 0 = 1
The issue with above is, it is copying all the columns but it is not copying the dependencies/relationships.
I saw some posts on some of the forums regarding this, but the suggested solution was using SSMS Wizard. I want to do it using SQL (or T-SQL).
I'm new to SQL world, so i'm really sorry if it is a stupid or no brainer question. Let me know if i am missing some important information, i'll update it.
Try below query and check if this works for you
SELECT TOP 0 *
INTO NewCarOrders
FROM CarOrders
This will create NewCarOrders table with same structure as CarOrders table and no rows in NewCarOrders.
SELECT * FROM NewCarOrders -- Returns zero rows
Note : This will not copy constraints , only structure is copied.
For constraints do as below -
In SSMS right click on the table CarOrders, Script Table As > Create To > New Query Window.
Change the name in the generated script to NewCarOrders and execute.
Also change the constraints name in the generated script else it will throw error like There is already an object named 'xyz' in the database
You can use the like command:
CREATE TABLE NewCarOrders LIKE CarOrders;

Trying to create a new column, get #1064 error

I've been using phpMyAdmin to manage my db without any problem, but today I ran into this error if I try to add any column by using the interface to any table of any database:
ALTER TABLE `testing` ADD `faaa` INT NOT NULL AFTER ;
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
But if I add the column via SQL command in phpMyAdmin, this time by removing AFTER, the column is added without any problem.
I'm still inexperience with phpMyAdmin, so I guess I must have missed a mandatory field to fill when creating a new column in the interface. Can anyone shed a light on this for me?
AFTER column_name is used to designate which column in the table you want to insert the new column after. You're providing the AFTER without telling it which column you want the new column to be inserted behind. If you don't care about the order of the columns in your table, omit the AFTER, and the new column will be inserted at the end of the column list.
You have no column name after the AFTER statement, so the phpMyAdmin doesn't know where it should be put. Whether it's you forgetting to select the column or a phpMyAdmin bug, I have no idea because for adding a new column, the only required fields are the name and type, which you have.

find and replace data in multiple records

I have a mysql 5 database table with a longtext field that permits html code (via markdown) to be entered as data. Unfortunately, I made a minor copy/paste error that I didn't catch until I had more that 200 records. Because it's the same error on each record
href:"http://someurl.com"
as opposed to
href="http://someurl.com"
it would be easier if there were some sql I could write that would allow me to find "href:" on all records and replace with "href=" in the same transaction, than if I have to edit each record individually. Is there anything I can do or am I just screwed?
You can do this:
UPDATE Data_Table
SET Html_Column = REPLACE(Html_Column, 'href:', 'href=');
if using phpmyadmin click on sql and run this UPDATETable_Name
SETColumn_Name= replace(Column_Name, 'href:', 'href=')