SQL query for finding Foreign key constraints - postgresql

I have one column , and i want to find in How many table that column used as foreign and also name of the table in which that column is used. I have PostgreSQL database . and i am using PG admin tool
select R.TABLE_NAME from INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE u
inner join INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS FK
on U.CONSTRAINT_CATALOG = FK.UNIQUE_CONSTRAINT_CATALOG
and U.CONSTRAINT_SCHEMA = FK.UNIQUE_CONSTRAINT_SCHEMA
and U.CONSTRAINT_NAME = FK.UNIQUE_CONSTRAINT_NAME inner join INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE R
ON R.CONSTRAINT_CATALOG = FK.CONSTRAINT_CATALOG
AND R.CONSTRAINT_SCHEMA = FK.CONSTRAINT_SCHEMA
AND R.CONSTRAINT_NAME = FK.CONSTRAINT_NAME WHERE U.COLUMN_NAME='M_InLine_ID'
AND U.TABLE_NAME = 'M_InLine'
I tried above query but it snot given any output
Please help me out

Related

Is there a way to modify this query and make it more simple?

I am working on a MySQl data base and have several tables that I need to join based on a temporary table that I created (layer_2).
Each table that I join has the join key for the next table;
E.g. layer_2 joins with "colegios" table, then the result will have the join key for the next table "ciudades". and finally the result will have the Join key for the next table "departamentos".
from what I got it works but I want to know if there is a way to simplify this?
Select
cuestionario_id,
tiempo,
nro_preguntas,
nro_preguntas_correctas,
tipo_usuario,
fecha_creacion_cuestionario,
con_tiempo,
det_cuestionarios_id,
respuesta_seleccionada,
pregunta_id,
enunciado,
respuesta_correcta,
usuarios_id,
dominio_correo,
tipo_institucion,
materia,
tematica,
area,
nombre_colegios,
direccion_colegios,
nombre_ciudades,
redsaber.departamentos.nombre as nombre_departamentos
From
(
Select
cuestionario_id,
tiempo,
nro_preguntas,
nro_preguntas_correctas,
cuestionable_id,
tipo_usuario,
fecha_creacion_cuestionario,
con_tiempo,
det_cuestionarios_id,
respuesta_seleccionada,
pregunta_id,
enunciado,
respuesta_correcta,
usuarios_id,
dominio_correo,
cole_ciud_id,
tipo_institucion,
materia,
tematica,
area,
combine_ciudad_id,
nombre_colegios,
direccion_colegios,
redsaber.ciudades.nombre as nombre_ciudades,
departamento_id
From
(Select
cuestionario_id,
tiempo,
nro_preguntas,
nro_preguntas_correctas,
cuestionable_id,
tipo_usuario,
fecha_creacion_cuestionario,
con_tiempo,
det_cuestionarios_id,
respuesta_seleccionada,
pregunta_id,
enunciado,
respuesta_correcta,
usuarios_id,
dominio_correo,
cole_ciud_id,
tipo_institucion,
materia,
tematica,
area,
ifnull(redsaber.colegios.ciudad_id,cole_ciud_id) as combine_ciudad_id,
redsaber.colegios.nombre as nombre_colegios,
redsaber.colegios.direccion as direccion_colegios
From layer_2
Left Join redsaber.colegios on layer_2.cole_ciud_id = redsaber.colegios.id
AND tipo_institucion = 'Colegio') as layer_3
Left Join redsaber.ciudades on combine_ciudad_id = redsaber.ciudades.id) as layer_4
Left Join redsaber.departamentos on departamento_id = redsaber.departamentos.id

Update all using alias from an aggregate value derived from a Join

SELECT activities.id, max(symbols.bought_at) AS bought_at
FROM "activities"
JOIN holdings ON trackable_id = holdings.id AND trackable_type = 'Holding'
JOIN symbols on symbols.holding_id = holdings.id
GROUP BY activities.id"
I have a SQL that looks like the above. This works fine. However, I want to update all activities' created_at to the alias bought_at. I get an error that bought_at is not a column. Is it possible to do so in Postgres?
you can use that query as the source for an UPDATE statement:
update activities
set created_at = t.bought_at
from (
SELECT activities.id, max(symbols.bought_at) AS bought_at
FROM activities
JOIN holdings ON trackable_id = holdings.id AND trackable_type = 'Holding'
JOIN symbols on symbols.holding_id = holdings.id
GROUP BY activities.id
) t
where activities.id = t.id;
This assumes that activities.id is the primary key of that table.

AS400 index configuration table

How can I view index of particular table in AS400? In which table index description of table is stored?
If your "index" is really a logical file, you can see a list of these using:
select * from qsys2.systables
where table_schema = 'YOURLIBNAME' and table_type = 'L'
To complete the previous answers: if your AS400/IBMi's files are "IBM's old style" Physical and Logical files, the qsys2.syskeys and qsys2.sysindexes are empty.
==> you retrieve index infos in QADBKFLD (for "indexes" info) and QADBXREF(for fields list) tables
select * from QSYS.QADBXREF where DBXFIL = 'YOUR_LOGICAL_FILE_NAME' and DBXLIB = 'YOUR_LIBRARY'
select * from QSYS.QADBKFLD where DBKFIL = 'YOUR_LOGICAL_FILE_NAME' and DBKLB2 = 'YOUR_LIBRARY'
WARNING: YOUR_LOGICAL_FILE_NAME is not your "table name", but the name of the file ! You have to join another table QSYS.QADBFDEP to match LOGICAL_FILE_NAME / TABLE_NAME :
To found indexes from your table's name:
Select r.*
from QSYS.QADBXREF r, QSYS.QADBFDEP d
where d.DBFFDP = r.DBXFIL and d.DBFLIB=r.DBXLIB
and d.DBFFIL = 'YOUR_TABLE_NAME' and d.DBFLIB = 'YOUR_LIBRARY'
To found all indexes' fields from your table:
Select DBXFIL , f.DBKFLD, DBKPOS , t.DBXUNQ
from QSYS.QADBXREF t
INNER JOIN QSYS.QADBKFLD f on DBXFIL = DBKFIL and DBXLIB = DBKLIB
INNER JOIN QSYS.QADBFDEP d on d.DBFFDP = t.DBXFIL and d.DBFLIB=t.DBXLIB
where d.DBFFIL = 'YOUR_TABLE_NAME' and d.DBFLIB = 'YOUR_LIBRARY'
order by DBXFIL, DBKPOS
if your indexes is create with SQL you can see liste of index in sysindexes system view
SELECT * FROM qsys2.sysindexes WHERE TABLE_SCHEMA='YOURLIBNAME' and
TABLE_NAME = 'YOURTABLENAME'
if you want detail columns for index you can join syskeys tables
SELECT KEYS.INDEX_NAME, KEYS.COLUMN_NAME
FROM qsys2.syskeys KEYS
JOIN qsys2.sysindexes IX ON KEYS.ixname = IX.name
WHERE TABLE_SCHEMA='YOURLIBNAME' and TABLE_NAME = 'YOURTABLENAME'
order by INDEX_NAME
You could also use commands to get the information. Command DSPDBR FILE(LIBNAME/FILENAME) will show a list of the objects dependent on a physical file. The objects that show a data dependency can then be further explored by running DSPFD FILE(LIBNAME/FILENAME). This will show the access paths of the logical file.

postgresql multi join syntax

SELECT sessions_compare.*
FROM archive_sessions as f_session, sessions_compare
LEFT JOIN archive_sessions as s_session ON (s_session.id = sessions_compare.second_session_id)
LEFT JOIN consols as f_consol ON (f_session.console_id = f_consol.id)
where sessions_compare.first_session_id = f_session.id
after executing a get error like
ERROR: invalid reference to FROM-clause entry for table "f_session"
LINE 13:
LEFT JOIN consols as f_consol ON (f_session.console_id
=...
HINT: There is an entry for table "f_session", but it cannot be referenced from this
part of the query.
When i switch places and have from like sessions_compare, archive_sessions as f_session
i get error like
ERROR: invalid reference to FROM-clause entry for table
"sessions_compare"
LINE 4: ... archive_sessions as s_session ON
(s_session.id = sessions_c...
HINT: There is an entry for table "sessions_compare", but it cannot be
referenced from this part of the query.
And only thing that work is
SELECT sessions_compare.*
FROM sessions_compare
LEFT JOIN archive_sessions as s_session ON (s_session.id = sessions_compare.second_session_id)
,archive_sessions as f_session
LEFT JOIN consols as f_consol ON (f_session.console_id = f_consol.id)
where sessions_compare.first_session_id = f_session.id
And my question is it normal ?? Im young in Postgresql in mysql when using multiple join from tables needed to be in ()
Yes, that's documented behavior in PostgreSQL.
In any case JOIN binds more tightly than the commas separating FROM items.
That means PostgreSQL acts like it builds its working table by evaluating the JOIN clauses before evaluating a comma-list in the FROM clause.
Best practice is generally considered to be to always use JOIN clauses; never put more than one table name in the FROM clause.
Changing the main query to a JOIN (and adding/shortening some correlation names) seems to fix the problem.
DROP SCHEMA fuzz CASCADE;
CREATE SCHEMA fuzz;
SET search_path='fuzz';
create table archive_sessions ( id INTEGER NOT NULL
, console_id INTEGER NOT NULL, game_id INTEGER NOT NULL);
create table sessions_compare (first_session_id INTEGER NOT NULL
, second_session_id INTEGER NOT NULL);
create table consols (id INTEGER NOT NULL);
create table games (id INTEGER NOT NULL);
create table localizations ( consols_id INTEGER NOT NULL, bars_id INTEGER NOT NULL);
create table bars ( id_bars INTEGER NOT NULL, area_id INTEGER NOT NULL);
create table areas ( id_areas INTEGER NOT NULL );
SELECT sco.*
FROM archive_sessions as ase
JOIN sessions_compare sco ON sco.first_session_id = ase.id
LEFT JOIN archive_sessions as ss ON (ss.id = sco.second_session_id)
LEFT JOIN consols as sc ON (ss.console_id = sc.id)
LEFT JOIN games as sg ON (ss.game_id = sg.id)
LEFT JOIN localizations as sl ON (sc.id = sl.consols_id)
LEFT JOIN bars as sb ON (sl.bars_id = sb.id_bars)
LEFT JOIN areas as sa ON (sb.area_id = sa.id_areas)
LEFT JOIN consols as fc ON (ase.console_id = fc.id)
LEFT JOIN games as fg ON (ase.game_id = fg.id)
LEFT JOIN localizations as fl ON (fc.id = fl.consols_id)
LEFT JOIN bars as fb ON (fl.bars_id = fb.id_bars)
LEFT JOIN areas as fa ON (fb.area_id = fa.id_areas)
-- WHERE sco.first_session_id = ase.id
;

How to perform Linq to Entites Left Outer Join

I have read plenty of blog posts and have yet to find a clear and simple example of how to perform a LEFT OUTER JOIN between two tables. The Wikipedia article on joins Join (SQL) provides this simple model:
CREATE TABLE `employee` (
`LastName` varchar(25),
`DepartmentID` int(4),
UNIQUE KEY `LastName` (`LastName`)
);
CREATE TABLE `department` (
`DepartmentID` int(4),
`DepartmentName` varchar(25),
UNIQUE KEY `DepartmentID` (`DepartmentID`)
);
Assume we had a EmployeeSet as an employee container ObjectSet<Employee> EmployeeSet and a DepartmentSet ObjectSet<Department> DepartmentSet. How would you perform the following query using Linq?
SELECT LastName, DepartmentName
FROM employee e
LEFT JOIN department d
ON e.DepartmentID = d.DepartmentID
I would write this, which is far simpler than join and does exactly the same thing:
var q = from e in db.EmployeeSet
select new
{
LastName = e.LastName,
DepartmentName = e.Department.DepartmentName
};
You need to use the DefaultIfEmpty method :
var query =
from e in db.EmployeeSet
join d in db.DepartmentSet on e.DepartmentID equals d.DepartmentID into temp
from d in temp.DefaultIfEmpty()
select new { Employee = e, Department = d };