Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
When a row is deleted from `titles_in_stock` table, I want to insert equivalent row in table named `titles_in_stock_out`. I tried the following ``` create trigger titles_in_stock_out on titles_in_stock after delete as begin insert into titles_in_stock_out (cd_title, invenotry, cd_type) valu...
Your syntax is incorrect. The `deleted` is virtual table which available in trigger, then you must refer it as table. ``` create trigger titles_in_stock_out on titles_in_stock after delete as begin insert into titles_in_stock_out (cd_title, invenotry, cd_type) select cd_title, invenotry, cd_...
You need to refer to`deleted`as a table, and also the trigger needs to have a different name; in your example it had the same name as the table. ``` create trigger titles_in_stock_out_trig on titles_in_stock after delete as begin insert into titles_in_stock_out (cd_title, invenotry, cd_type) ...
create trigger after delete
[ "", "sql", "sql-server", "" ]
*UPDATE* I was able to find my solution by leveraging NOT EXISTS. Thus, my and statement looks like this: ``` and NOT EXISTS (select RejectCode from #rejects where od.UnitDescription LIKE ('%' + RejectCode + '%')) ``` This leverages a temp table #results in which I'm storing the 184 reject codes. THANK YOU everyone ...
Here is how I would do it -- I can't see your exact example so you might need different columns in the criteria table. ``` with criteria as ( select 15 as groupid, '1' as discountpercent union all select 15 as groupid, '.4' as discountpercent union all select 15 as groupid, '.2' as discountpercent ), rejects ...
Another way might be filtering the ids of those "like" it first and then selecting those "not in" the ids returned (this is assuming you have a column id in OrderDetails): ``` select od.*, o.* from OrderDetails od join Orders o ON o.oKey = od.oKey where CustomerID = '104' and od.id not in (select od2.id ...
SQL NOT LIKE with multiple values
[ "", "sql", "sql-server", "" ]
I was trying to execute this statement to delete records from the F30026 table that followed the rules listed.. I'm able to run a select \* from and a select count(\*) from with that statement, but when running it with a delete it doesn't like it.. it gets lost on the 'a' that is to define F30026 as table a ``` delete...
This looks like an inner join to me, see [MySQL - DELETE Syntax](https://dev.mysql.com/doc/refman/5.5/en/delete.html) ``` delete a from CRPDTA.F30026 as a inner join CRPDTA.F4101 as b on a.IELITM = b.IMLITM where substring(b.IMGLPT, 1, 2) not in ('FG', 'IN', 'RM') ``` Please note the alias syntax `as a` and `as b`.
Instead of the 'exists' function, you can match the id (like you do in the where clause): ``` delete from CRPDTA.F30026 a where a.IELITM IN ( select b.IMLITM from CRPDTA.F4101 b where a.IELITM=b.IMLITM and substring(b.IMGLPT,1,2) not in ('FG','IN','RM')); ```
Delete values in one table based on values in another table
[ "", "mysql", "sql", "" ]
So I'm solving the interactive tutorial [http://www.sqlzoo.net/wiki/SELECT\_from\_Nobel\_Tutorial](http://www.sqlzoo.net/wiki/SELECT%5ffrom%5fNobel%5fTutorial) However the bonus part doesn't have a solution. **Here's the question:** In which years was the Physics prize awarded but no Chemistry prize. ``` SELECT yr FR...
There are two errors in your query: * You mistyped `Chemistry` (your query says `Literature` instead) * You did not ask for `distinct` results Here is your modified query: ``` SELECT DISTINCT yr FROM nobel WHERE subject = 'Physics' AND yr NOT IN (SELECT yr FROM nobel WHERE subject = 'Chemistry') ``` `DISTINCT` is i...
> In which years was the Physics prize awarded but no Chemistry prize. :) Read Your task again... > WHERE subject = 'Physics' AND yr NOT IN > (SELECT yr FROM nobel WHERE subject = 'Literature')
Whats wrong with my nested subquery?
[ "", "mysql", "sql", "subquery", "" ]
I'm trying to save a R dataframe back to a sql database with the following code: ``` channel <- odbcConnect("db") sqlSave(db, new_data, '[mydb].[dbo].mytable', fast=T, rownames=F, append=TRUE) ``` However, this returns the error "table not found on channel", while simultaneously creating an empty table with c...
Is this about what your data set looks like? ``` MemberNum x t.x T.cal m.x T.star h.x h.m.x e.trans e.spend 1 2.910165e+12 0 0 205 8.77 52 0 0 0.0449161 ``` I've had this exact problem a few times. It has nothing to do with a table not being found on the channel. From ...
As a first shot try to run `sqlTables(db)` to check the tables in the db and their correct names. You could then potentially use this functions return values as the input to `sqlSave(...)`
sqlSave error: table not found
[ "", "sql", "r", "rodbc", "" ]
I'm new to Oracle and I need to help with this query. I have table with data samples /records like: ``` name | datetime ----------- A | 20140414 10:00 A | 20140414 10:30 A | 20140414 11:00 B | 20140414 11:30 B | 20140414 12:00 A | 20140414 12:30 A | 20140414 13:00 A | 20140414 13:30 ``` And I ...
You need to find periods where the values are the same. The easiest way in Oracle is to use the `lag()` function, some logic, and aggregation: ``` select name, min(datetime), max(datetime) from (select t.*, sum(case when name <> prevname then 1 else 0 end) over (order by datetime) as cnt from (selec...
``` SQL> with t (name, datetime) as 2 ( 3 select 'A', to_date('20140414 10:00','YYYYMMDD HH24:MI') from dual union all 4 select 'A', to_date('20140414 10:30','YYYYMMDD HH24:MI') from dual union all 5 select 'A', to_date('20140414 11:00','YYYYMMDD HH24:MI') from dual union all 6 select 'B', to_date('20140...
Oracle query - without temporary table
[ "", "sql", "oracle", "" ]
I have created a cable database in Access, and I generate a report that has lists the connectors on each end of a cable. Each cable has its own ID, and 2 connector IDs, associated with it. All the connectors are from the same table and is linked to many other tables. I need 2 fields in one table (cable) associated wit...
You need two tables--one you have already: ``` Cables ID autoincrement primary key ... ``` The `Cables` table should just describe the properties of the cables, and should know nothing of how a cable connects to other cables. The second table should be a list of possible connections between pairs of cables and o...
The alternative is to have one connectors table, and then two foreign keys to it in the cables table. ``` CREATE TABLE connector ( id INT PRIMARY KEY, ... ); CREATE TABLE cable ( primary_connector_id INT NOT NULL REFERENCES connector(id), secondary_connector_id INT NOT NULL REFERENCES connector...
How can I associate one record with another in the same table?
[ "", "sql", "database", "ms-access", "entity-relationship", "" ]
I'm Having 2 tables ``` modules_templates ``` and ``` templates ``` In table templates i have 75 records . I want to insert into table modules\_templates some data which template\_id in modules\_templates = template\_id from templates. I created this query : ``` INSERT INTO `modules_templates` (`module_template_id...
Try this ``` INSERT INTO `modules_templates` (`module_template_id`,`module_template_modified`,`module_id`,`template_id`) (SELECT '','2014-04-14 10:07:03','300',template_id FROM templates WHERE 1) ``` Your query didn't work because you were inserting value for one row, where last field i.e result of su...
Try this: ``` INSERT INTO `modules_templates` (`module_template_id`,`module_template_modified`,`module_id`,`template_id`) SELECT '','2014-04-14 10:07:03','300',template_id FROM templates WHERE 1 ```
Inserting values from 1 table to another error
[ "", "mysql", "sql", "" ]
I have not found any documentation that explains the following behavior, both db and server level collation are CI (Case Insensitive), why is it still case sensitive in this aspect? ``` --Works SELECT CASE name WHEN 'a' THEN 'adam' ELSE 'bertrand' END AS name, COUNT(value) FROM ( SELECT 'a' AS name,1 AS value UNION SE...
This is more of extended comment that real answer. I believe this issue is coming from how SQL Server is attempting to evaluate `case` statement expression. To prove that server is case insensetive you can run the following two statements ``` SELECT CASE WHEN 'Bertrand' = 'bertrand' THEN 'true' ELSE 'false' end ``` ...
You have found something that is genuinely weird, but I think the problem is that you are using the case statement at all in the group by statement. It should be: ``` SELECT CASE name WHEN 'a' THEN 'adam' ELSE 'bertrand' END AS name FROM ( SELECT 'a' AS name,1 AS value UNION SELECT 'b',1 UNION SELECT 'b',2 ) a GROUP...
Group by is case sensitive in T-SQL even though db and server collations are CI
[ "", "sql", "sql-server", "t-sql", "" ]
I am creating multiple views in my code and each time the code is run, I would like to drop all the materialized views generated thus far. Is there any command that will list all the materialized views for Postgres or drop all of them?
### Pure SQL Show all: ``` SELECT oid::regclass::text FROM pg_class WHERE relkind = 'm'; ``` Names are automatically double-quoted and schema-qualified where needed according to your current [`search_path`](https://stackoverflow.com/questions/9067335/how-to-create-table-inside-specific-schema-by-default-in-postgr...
You may also use `pg_matviews` system view to list all the materialized views. This view will give you information including the materialized view definition, if the materialized view is populated or is empty (`ispopulated` column) ``` select * from pg_matviews where matviewname = 'my_materialized_view'; ```
Is there a postgres command to list/drop all materialized views?
[ "", "sql", "postgresql", "ddl", "materialized-views", "drop", "" ]
I have a `checkboxlist`. The selected (checked) items are stored in `List<string> selected`. For example, value selected is `monday,tuesday,thursday` out of 7 days I am converting `List<>` to a comma-separated `string`, i.e. ``` string a= "monday,tuesday,thursday" ``` Now, I am passing this value to a stored proced...
If you pass the comma separated (any separator) string to store procedure and use in query so must need to spit that string and then you will use it. Below have example: ``` DECLARE @str VARCHAR(500) = 'monday,tuesday,thursday' CREATE TABLE #Temp (tDay VARCHAR(100)) WHILE LEN(@str) > 0 BEGIN DECLARE @TDay VARCHAR...
Try this: ``` CREATE FUNCTION [dbo].[ufnSplit] (@string NVARCHAR(MAX)) RETURNS @parsedString TABLE (id NVARCHAR(MAX)) AS BEGIN DECLARE @separator NCHAR(1) SET @separator=',' DECLARE @position int SET @position = 1 SET @string = @string + @separator WHILE charindex(@separator,@string,@position) <> 0 ...
How to separate (split) string with comma in SQL Server stored procedure
[ "", "asp.net", "sql", "sql-server", "stored-procedures", "" ]
I am trying to make a stored procedure for the query I have: ``` SELECT count(DISTINCT account_number) from account NATURAL JOIN branch WHERE branch.branch_city='Albany'; ``` or ``` SELECT count(*) from ( select distinct account_number from account NATURAL JOIN branch WHERE branch.branch_city='Albany' ...
The PL/pgSQL version can look like this: ``` CREATE FUNCTION account_count_in(_branch_city text) RETURNS int LANGUAGE plpgsql AS $func$ BEGIN RETURN ( SELECT count(DISTINCT a.account_number)::int FROM account a NATURAL JOIN branch b WHERE b.branch_city = _branch_city ); END $func$; ``` Call: ...
you can use this template ``` CREATE OR REPLACE FUNCTION a1() RETURNS integer AS $BODY$ BEGIN return (select 1); END $BODY$ LANGUAGE plpgsql VOLATILE COST 100; select a1() ```
Stored procedure to return count
[ "", "sql", "postgresql", "stored-procedures", "plpgsql", "" ]
Given the following table: ``` id message owner_id counter_party_id datetime_col 1 "message 1" 4 8 2014-04-01 03:58:33 2 "message 2" 4 12 2014-04-02 10:27:34 3 "message 3" 4 8 2014-04-03 09:34:38 4 "message 4" 4 12 ...
Should be the last message so either max(id) or latest datetime in this case, counter\_party\_id is just an user id the most recent counter\_party\_id does not mean the max counter\_party\_id(I found the solution in the answers and I gave props): ``` SELECT * FROM yourTable WHERE counter_party_id = ( SELECT MAX(id) ...
A number of ways exists to do that. This is properly the most straight forward. ``` SELECT * FROM YourTable WHERE counter_party_id = (SELECT MAX(counter_party_id) FROM YourTable); ``` You could also select the MAX into a variable before hand; ``` DECLARE @m int SET @m = (SELECT MAX(counter_Party_id) FROM YourTable);...
SQL select id from a table to query again all at once
[ "", "sql", "select", "multi-query", "" ]
I'm currently stuck on a SQL query I'm trying to put together. Here is the table layout: --- ## Table 1: **tblUsers** *this table contains more columns, but not necessary in example* * UserID (int) **Sample Data:** ``` ------ | ID | ------ | 1 | ------ | 2 | ------ ``` --- ## Table 2: **tblColumns** * Colu...
I think this would help you: ``` with userCTE as ( select u.userId , c.columnId from tblUsers as u cross join tblColumns as c ) select u.* , Coalesce(cd.ColumnDatacontent, 'N/A') AS columnDataContent from userCTE as u left join tblColumnData as cd on u.columnId...
With Fiddle down we're all flying blind, but this is what I'd try first there if it were up. ``` SELECT tblUsers.UserID, tblColumns.ColumnID, tblColumns.ColumnName tblColumnData.ColumnDataContent FROM tblUsers, tblColumns LEFT JOIN tblColumnData ON tblColumnData.ColumnID = tblColumns.C...
SQL Query Join Issue
[ "", "sql", "sql-server", "join", "" ]
I have the following scenario: I have 2 columns, the first column is called AgentID and the second column is called AgentName in the agents table. Few AgentID starts with an "A" and few starts with an "M", what I want to do is the following: ``` AgentID AgentName A123 Name1 M123 Name2 A234 Name3 Aagents AAge...
Try this ``` WITH AAgents AS ( SELECT ROW_NUMBER() over (order by AgentID) AS RN, AgentID AS Aagents, AgentName As AAgentName FROM Agents WHERE LEFT(AgentID,1)='A' ), MAgents As ( SELECT ROW_NUMBER() over (order by AgentID) AS RN, AgentID AS Magents, AgentName As MAgentName ...
You can do a full outer join between 2 subqueries (one for A agents, one for M agents) and join on `ROW_NUMBER()` to have nulls on one side (the one with less records): ``` select A.AgentID Aagents, A.AgentName AAgentName, M.AgentID Magents, M.AgentName MAgentName from (select *, ROW_NUMBER() over (order by AgentID) r...
Query divides a column into multiple columns
[ "", "sql", "sql-server", "t-sql", "" ]
I can't to understand firebird group logic Query: ``` SELECT t.id FROM T1 t INNER JOIN T2 j ON j.id = t.jid WHERE t.id = 1 GROUP BY t.id ``` works perfectly But when I try to get other fields: ``` SELECT * FROM T1 t INNER JOIN T2 j ON j.id = t.jid WHERE t.id = 1 GROUP BY t.id ``` I get error: `Invalid expre...
When you use `GROUP BY` in your query, the field or fields specified are used as 'keys', and data rows are grouped based on unique combinations of those 2 fields. In the result set, every such unique combination has one and only one row. In your case, the only identifier in the group is `t.id`. Now consider that you h...
When you using `GROUP BY` clause in `SELECT` you should use only aggreagted functions or columns that listed in `GROUP BY` clause. More about `GROUP BY` clause:<http://www.firebirdsql.org/manual/nullguide-aggrfunc.html> As example: ``` SELECT Max(t.jid), t.id FROM T1 t INNER JOIN T2 j ON j.id = t.jid WHERE t.id = ...
Firebird group clause
[ "", "sql", "firebird", "" ]
I'm trying to solve #13 on <http://www.sqlzoo.net/wiki/The_JOIN_operation> "List every match with the goals scored by each team as shown. This will use "CASE WHEN" which has not been explained in any previous exercises." **Here's my query:** ``` SELECT game.mdate, game.team1, SUM(CASE WHEN goal.teamid = game.team1 ...
An `INNER JOIN` only returns games where there have been goals, i.e. matches between the `goal` and `game` table. What you need is a `LEFT JOIN`. You need all the rows from your first table, `game` but they don't need to match all the rows in `goal`, as per the 0-0 comment I made on your question: ``` SELECT game.mda...
As there are columns with the same names in both tables, no need to specify where the current column is coming from. ``` SELECT mdate, team1, SUM(CASE WHEN teamid = team1 THEN 1 ELSE 0 END) AS score1, team2, SUM(CASE WHEN teamid = team2 THEN 1 ELSE 0 END) AS score2 FROM game LEFT JOIN goal ON matchid = id GROUP ...
Whats wrong with my query with CASE statement
[ "", "mysql", "sql", "select", "group-by", "case", "" ]
I have 3 tables as follow. ``` DATA(entity_id, crv_name, data_cnt_id) PROCESSED_DATA(entity_id, crv_name, run_id) RUNS(run_id, data_cnt_id) ``` Both `DATA` and `PROCESSED_DATA` have similar columns, except for the last one. `PROCESSED_DATA` also has significantly more rows than `DATA`. `DATA` is about old crv\_name ...
You need to outer join the records: ``` select pd.ntt_id, pd.crv_name, d.crv_name from processed_data pd left join data d on d.entity_id = pd.entity_id left join runs r on r.run_id = pd.run_id and r.data_cnt_id = d.data_cnt_id and r.run_id = 7; ``` In case there must be a run 7: ``` select pd.ntt_id, pd.crv_name, d...
Change `join` to `left join`: ``` select pd.ntt_id, pd.crv_name, d.crv_name from processed_data pd left join data d on d.entity_id = pd.entity_id join runs r on r.run_id = pd.run_id and r.data_cnt_id = m.data_cnt_id where r.run_id = 7 ```
SQL query not returning some rows
[ "", "sql", "" ]
I have a database where the months and years are saved in different columns as integers. The query is working fine but if the user of the application is selecting a timespan over several years the query isn't working how it should be. ``` WORKS FINE: 01-2014 <--> 04-2014 DOESN'T WORK: 12-2013 <--> 02-2014 ``` Here is...
You need separate conditions for months that are in the same year as the start and stop year, and the other months. For example, if you want records from 2013-10 and forward, you want the months 10, 11 and 12 from 2013, but all the months in the following years. Example to get the records from 2012-05 to 2014-02: ``...
How much sense does this make to you? Give me a number less than or equal to 2 and greater than or equal to 12. ``` tbl_report.MONTH >= 12 AND tbl_report.MONTH <= 2 ``` That will never be true! As for a solution: Try this in your `WHERE` clause: ``` WHERE tbl_report.CITYID = 'london' AND ( ((tbl_repor...
MySQL integer as Date in where clause
[ "", "mysql", "sql", "function", "" ]
Using Sql Server 2012 I want to query a table to only fetch rows where certain columns are not null or don't contain an empty string. The columns I need to check for null and ' ' all start with either **col\_as** or **col\_m** followed by two digits. At the moment I write `where col_as01 is not null or` .... which be...
You should fill in the blanks. ``` select @myWhereString =stuff((select 'or isnull('+COLUMN_NAME+','''') = '''' ' as [text()] from Primebet.INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'YourTable' and (column_name like 'col_as%' ...
You can use something like this `WHERE DATALENGTH(col_as01) > 0` That will implicitly exclude null values, and the length greater 0 will guarantee you to retrieve non empty strings. PS: You could also use `LEN` instead of `DATALENGTH` but that will trim spaces in your string at the beginning and end so you would not...
TSQL - dynamic WHERE clause to check for NULL for certain columns
[ "", "sql", "t-sql", "null", "sql-server-2012", "" ]
So I have the following where conditions ``` sessions = sessions.Where(y => y.session.SESSION_DIVISION.Any(x => x.DIVISION.ToUpper().Contains(SearchContent)) || y.session.ROOM.ToUpper().Contains(SearchContent) || y.se...
There are a few ways to go about this: 1. Apply the "where" to the original query each time, and then `Union()` the resulting queries. ``` var queries = new List<IQueryable<Session>>(); if (!String.IsNullOrEmpty(Division)) { queries.Add(sessions.Where(y => y.session.SESSION_DIVISION.Any(x => x.DIVISIO...
`.Where()` assumes logical `AND` and as far as I know, there's no out of box solution to do it. If you want to separate `OR` statements, you may want to look into using [Predicate Builder](http://www.albahari.com/nutshell/predicatebuilder.aspx) or [Dynamic Linq](http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic...
LINQ: Split Where OR conditions
[ "", "sql", ".net", "linq", "where-clause", "multiple-conditions", "" ]
``` client_ref matter_suffix date_opened 1 1 1983-11-15 00:00:00.000 1 1 1983-11-15 00:00:00.000 1 6 2002-11-18 00:00:00.000 1 7 2005-08-01 00:00:00.000 1 9 2008-07-01 00:00:00.000 1 ...
In SQL 2012 there are handy functions to make this easier but in SQL 2008 you need to do it the old way: Find the most recent: ``` SELECT client_ref,MAX(date_opened) last_opened FROM YourTable GROUP BY client_ref ``` Now join to that back: ``` SELECT client_ref,matter_suffix, date_opened FROM YourTable YT INNER ...
Doesn't this work? ``` select client_ref,matter_suffix,max (Date_opened)[Most Recent] from archive a group by client_ref,matter_suffix order by client_ref ```
Including Data from other columns in Aggregate Function Result
[ "", "sql", "sql-server", "sql-server-2008", "" ]
i have bunch of discount scheme for my item table , and for each item i have different discount scheme. now i want to give row id to that item but it should be start from zer0(0) for each item group, and when it got different DiscountId then it should be change, my table is in below image..![enter image description her...
Maybe something like this: **Test data:** ``` DECLARE @tbl TABLE(ITEMCode INT,DiscountId INT) INSERT INTO @tbl VALUES (73,419),(73,419),(73,420),(73,420),(73,420), (429,427),(429,427),(429,427),(429,427),(429,427), (429,427),(429,427),(429,427),(429,428),(429,428) ``` **Query:** ``` ;WITH CTE AS ( SELECT ...
Just more simplified Arion's Answer ``` DECLARE @tbl TABLE(ITEMCode INT,DiscountId INT) INSERT INTO @tbl VALUES (73,419), (73,419), (73,420), (73,420), (73,420), (429,427), (429,427), (429,427), (429,427), (429,427), (429,427), (429,427), (429,427), (429,428), (429,428) ; SELECT (DENSE_RANK() OVER(PARTITION BY I...
how to give different row id to sub group in in a group in sql query?
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-2012", "" ]
I have 2 mysql tables: "Orders" table: ``` customer_id | money 3 120 5 80 3 45 3 70 6 20 ``` "collecting" table: ``` customer_id | money 3 50 3 70 4 20 4 90 ``` I want a result like: "Total" table: ``` cus...
The fastest way is to union your data with the money value being negative on the `collecting` table: ``` -- load test data create table orders(customer_id int, money int); insert into orders values (3,120), (5,80), (3,45), (3,70), (6,20); create table collecting(customer_id in...
The following returns the result you expect. ``` SELECT customer_id, SUM(amount) as amount FROM ( SELECT customer_id, SUM(money) as amount FROM orders GROUP BY customer_id UNION ALL SELECT customer_id, SUM(money) * -1 as amount FROM collecting GROUP BY customer_id ) as tb GROUP BY customer_id; ``` custom...
MYSQL calculate amount from two table?
[ "", "mysql", "sql", "join", "" ]
I've more experience using Access where I would build up my analysis in small parts and query each new view. I'm not trying to do something that must be simple in SQL. If I have a query of the format: ``` SELECT events.people, COUNT(events.eventType) AS usersAndEventCount FROM theDB.events WHERE event_id = 884 GROUP...
Your statement "*then want to query usersAndEventCount*" does not make sense because `usersAndEventCount` is a *column* - at least in your first example. You can not "query" a column. But from the example you have given it seems you want something like this: ``` Select usersAndEventCount.people, usersAndEventCount.ev...
In pure SQL, you can use nested queries (AKA sub-queries). Just enclose your first query in `()` brackets, so your query will look like this: ``` Select usersAndEventCount.people, usersAndEventCount.events FROM (SELECT events.people, COUNT(events.eventType) AS events FROM theDB.events WHERE event_id = 884 ...
Querying a query
[ "", "sql", "" ]
I'm trying to add a column named *order* to my table. I realize that *order* is a reserved word in SQL. So, how do I do it? My command: ``` alter table mytable add column order integer; ``` I've also tried: ``` alter table mytable add column 'order' integer; ``` PostgreSQL 9.1.
Use this: ``` alter table mytable add column "order" integer; ``` But, you might want to consider using a non-reserved name instead, like `sort_order` or something similar that reflects what the column is used for (and isn't a reserved word).
You are using order which is a reserved keyword you should consider renaming that to something like orders. And the problem should go away.
"syntax error at or near 'order'"" in PostgreSQL
[ "", "sql", "postgresql", "quoted-identifier", "" ]
I need to concatenate the `City`, `State` and `Country` columns into something like City, State, Country. This is my code: ``` Select City + ', ' + State + ', ' + Country as outputText from Places ``` However, because `City` and `State` allow `null` (or empty) value, what happen is, (for example) if the `City` is nu...
``` select isnull(City, '') + case when isnull(City, '') != '' then ', ' else '' end + isnull(State, '') + case when isnull(State, '') != '' then ', ' else '' end + isnull(Country, '') as outputText from Places ```
Since adding a string with null will result null so if they are null (not empty string) this will give you teh desired result ``` Select isnull(City + ', ','') + isnull(State + ', ' ,'') + isnull(Country,'') as outputText from Places ```
Concatenate and format text in SQL
[ "", "sql", "sql-server", "" ]
In the below code i have a document table ``` document name | document id | client id ``` and attachment table ``` attach id | document id | attachment name. ``` I want to get attachemt name from attachment table.in the below code i get document id,document name ,clientid from document name and i want...
``` @i_DocumentID varchar(MAX) SELECT a.DocumentID, a.DocumentName, a.ClientID, b.AttachmentName from Documents a join Attachments b on a.DocumentId = b.DocumentId where a.DocumentID IN (SELECT * FROM dbo.CSVToTable(@i_DocumentID)) ``` You can read more about joins here: <http://w...
Use a join: ``` @i_DocumentID varchar(MAX) SELECT D.DocumentID, D.DocumentName,D.ClientID, A.Attachement_name from Documents D JOIN Attachment A on D.document_id=A.document_id where D.DocumentID IN (SELECT * FROM dbo.CSVToTable(@i_DocumentID)) ```
Sql Query to get column name from another table
[ "", "sql", "sql-server", "" ]
My task is to validate existing data in an MSSQL database. I've got some SQL experience, but not enough, apparently. We have a zip code field that must be either 5 or 9 digits (US zip). What we are finding in the zip field are embedded spaces and other oddities that will be prevented in the future. I've searched enough...
Unfortunately, LIKE is not regex-compatible so nothing of the sort `\d`. Although, combining a length function with a numeric function may provide an acceptable result: ``` WHERE ISNUMERIC(ZIP) <> 1 OR LEN(ZIP) NOT IN(5,9) ``` I would however not recommend it because it ISNUMERIC will return 1 for a +, - or valid cur...
There are few ways you could achieve that. 1. You can replace `[0-9]` with `_` like ZIP NOT LIKE '**\_**' 2. USE LEN() so it's like LEN(ZIP) NOT IN(5,9)
Using SQL - how do I match an exact number of characters?
[ "", "sql", "sql-server", "regex", "sql-like", "" ]
I created a Hive Table, which loads data from a text file. But its returning empty result set on all queries. I tried the following command: ``` CREATE TABLE table2( id1 INT, id2 INT, id3 INT, id4 STRING, id5 INT, id6 STRING, id7 STRING, id8 STRING, id9 STRING, id10 STRING, id11 STRING, id12 STRING, id13 STRING, id14...
Please make sure that the location **/user/biadmin/lineitem.txt** actually exists and you have data present there. Since you are using **LOCATION** clause your data must be present there, instead of the default warehouse location, **/user/hive/warehouse**. Do a quick **ls** to verify that : ``` bin/hadoop fs -ls /use...
Did you tried with `LOAD DATA LOCAL INFILE` ``` LOAD DATA LOCAL INFILE'/user/biadmin/lineitem.txt' INTO TABLE table2 FIELDS TERMINATED BY '|' LINES TERMINATED BY '\n' (id1,id2,id3........); ``` Documentation: <http://dev.mysql.com/doc/refman/5.1/en/load-data.html>
Hive Table returning empty result set on all queries
[ "", "mysql", "sql", "hadoop", "hive", "bigdata", "" ]
Hey guys I have a dilemma with one of my SELECTS that I use in mySQL DB. Firstly this is how it looks : ![This](https://i.stack.imgur.com/4Kojm.png) My select is supposed to extract all the users and count each their prezente , when I use this select instead of taking all my users I get this : ``` SELECT users1.id,us...
You need to add a GROUP BY clause to your query. Also replace the old join syntax using WHERE clause with recommended JOIN / ON syntax. ``` SELECT users1.id,users1.Nume, COUNT(pontaj.prezente) FROM users1 INNER JOIN pontaj ON users1.id = pontaj.id GROUP BY users1.id,users1.Nume ```
I think you should add a group by clause meaning at the end of the SQL add ``` group by users1.Nume ```
display certain values mySQL
[ "", "mysql", "sql", "" ]
We have the following solution: ``` select substring(convert(varchar(20),convert(datetime,getdate())),5,2) + ' ' + left(convert(varchar(20),convert(datetime,getdate())),3) ``` What is the elegant way of achieving this format?
You can use the `dateName` function: ``` select right(N'0' + dateName(DD, getDate()), 2) + N'-' + dateName(M, getDate()) ``` If you really want the `mmm` part to only have the tree-letter abbreviation of the month, you're stuck with parsing the appropriate conversion type, for example ``` select left(convert(nvarcha...
You can do it this way: ``` declare @date as date = getdate() select replace(convert(varchar(6), @date, 6), ' ', '-') -- returns '11-Apr' ``` Format 6 is `dd mon yy` and you take the first 6 characters by converting to varchar(6). You just need to replace space with dash at the end.
Elegantly convert DateTime type to a string formatted "dd-mmm"
[ "", "sql", "sql-server", "t-sql", "" ]
I am trying to return an Employee Name and Award Date **if** they have no prior award dates before dates the user specifies (these are fields on a form, `StartDateTxt` and `EndDateTxt` as seen below), aka their "first occurrence." Example (AwardTbl only for simplicity): ``` AwardDate EmployeeID PlanID AwardedUni...
Min Award Date will work if grouped by EmployeeID with your date range in the `Having` clause and used as a filter list: ``` SELECT x.AstFirstName , x.AstLastName , y.AwardDate , y.AwardUnits , z.PlanDesc FROM ((AssociateTbl AS x INNER JOIN AwardTbl AS y ON x.EmployeeID = y.EmployeeID)...
Try like below ``` SELECT x.AstFirstName , x.AstLastName , y.AwardDate , y.AwardUnits , z.PlanDesc FROM (AssociateTbl AS x INNER JOIN AwardTbl AS y ON x.EmployeeID = y.EmployeeID) INNER JOIN PlanTbl AS z ON y.PlanID = z.PlanID WHERE y.AwardDate BETWEEN '1/1/2005' AND '12/31/2005' GROUP BY...
First Occurrence of Record by Date
[ "", "sql", "ms-access-2007", "" ]
I know some of SQL but, I always use `join`, `left`, `cross` and so on, but in a query where the tables are separated by a comma. It's looks like a cross join to me. But I don't know how to test it (the result is the same with the tries I made). ``` SELECT A.id, B.id FROM A,B WHERE A.id_B = B.id ``` Even in the great...
It *would* be a cross join if there wasn't a `WHERE` clause relating the two tables. In this case it's functionally equivalent to an inner join (matching records by `id_rel` and `id`) It's an older syntax for joining tables that is still supported in most systems, but JOIN syntax is largely preferred.
**This is old pre - 1992 standard SQL join syntax, which you should not mimic or use in anything you write today** The `where` clause specifies the join style and columns. You can use `=` or `*=` or`=*` in the where to make join, left or right joins. No joins in the `WHERE` make it a cross join.
Is a query with table separated by comma a cross join query?
[ "", "sql", "operation", "" ]
I have Table called `url_info` and the structure of the table is: url\_info: ``` url_id ( auto_increment, primary key ) url ( unique,varchar(500) ) ``` When I insert into table like this: ``` INSERT INTO url_info(url) VALUES('Tom'); INSERT INTO url_info(url) VALUES('Jerry'); ``` The output is: ``` 1 Tom 2 Jerry `...
It's probably worth creating a stored procedure to insert what you want into the table. But, in the stored procedure check what items you have already in the table. If these match what you're trying to insert, then the query should not even attempt the insert. Ie. The procedure needs to contain something like this: `...
This is expected behaviour in InnoDB. The reason is that they want to let go of the auto\_increment lock as fast as possible to improve concurrency. Unfortunately this means they increment the AUTO\_INCREMENT value before resolving any constraints, such as UNIQUE. You can read more about the idea in the manual on [AUT...
Prevent auto increment on duplicated entry?
[ "", "mysql", "sql", "duplicates", "" ]
I have one table containing all users information. **Example of the users table** ``` id username last_login 1 david 2014-01-30 12:21:54 2 sam 2014-01-30 17:43:12 3 lynda 2014-01-30 10:31:31 4 mark 2014-01-30 21:21:15 5 ...
Yes. You can have multiple arguments to `order by`. So, first identify the users you want ordered one way, then order them as you want, and order the rest: ``` order by userid in (1, 3, 4, 5, 6) desc, (case when userid in (1, 3, 4, 5, 6) then last_login end) ASC, id ASC ```
One of possibilities would be to create 2 queries and join them using `UNION` for example ``` SELECT Id, UserName, Last_login from Users where Id in(1,2,3,4,5,6,7) order by Id UNION SELECT Id, UserName, last_login from Users ORDER BY last_login ASC ```
MYSQL QUERY FOR THE FOLLOWING SCENARIO
[ "", "mysql", "sql", "performance", "" ]
I´m trying to generate unique datetime values for a set of legacy values. Unfortunately the GETDATE() call is only evaluated once, which results in the same datetime for each row. ``` UPDATE e SET e.moddate = GETDATE() FROM dbo.entries as e ``` Does anyone know how it would be possible to delay the single inserts or ...
Try this: ``` ;with cte as (select *,row_number() over (partition by getdate() order by getdate()) rn from entries) update entries set [moddate] = dateadd(second,rn,getdate()) from entries e inner join cte c on e.col1 = c.col1 ``` This will work as long as you have another column called `col1`, regardless of uni...
You need to generate some sort of formula to do this. System don't know by what logic you want to go to find unique date. If I would you I would do something like this ``` update e set e.moddate = DateAdd(second, 1, (select max(moddate) from dbo.entries)) FROM dbo.entries as e where e.id != 1 ``` Here system will pi...
TSQL Generate Unique Datetime values
[ "", "sql", "sql-server", "" ]
I have a query like this: ``` SELECT DISTINCT devices1_.id AS id27_, devices1_.createdTime AS createdT2_27_, devices1_.deletedOn AS deletedOn27_, devices1_.deviceAlias AS deviceAl4_27_, devices1_.deviceName AS deviceName27_, devices1_.deviceTypeId AS deviceT21_27_, devices1_.equipmentVendor AS equipmen6_27_, devices...
``` INNER JOIN goldenvariation goldenconf4_ ON goldenconf4_.deviceId = goldenconf0_deviceId AND (goldenconf4_.goldenVariationType = 'MISSING') AND (goldenconf4_.classType = 'policy-options') AND DATE(goldenconf4_.rundate)=DATE('2014-04-14 00:00:00')) ``` In the same way change another `EXISTS`. I think this one s...
Yes, the query could be rewritten to improve performance (though it looks like a query generated by Hibernate, and getting Hibernate to use a different query can be a challenge.) How sure are you that this query is returning the resultset you expect? Because the query is rather odd. In terms of performance, dollars t...
What should i use instead of IN?
[ "", "mysql", "sql", "performance", "join", "query-optimization", "" ]
I have a table structure like ``` Files Latest_Update ------------------- ------------------------------ Fid - Name - Type - l-id - c_name - c_val - Fid - ------------------- ------------------------------ 1 - D1 - xls - 1 - text1 - hello - 1 - ------------------- ...
I think union is the solution. Something like.. ``` SELECT * FROM ( SELECT Revisions.c_name, Revisions.c_val, Revisions.Fid FROM Revisions UNION ALL SELECT Latest_Update.c_name,Latest_Update.c_val, Latest_Update.c_name,Latest_Update.Fid FROM Latest_Update ) RS <if needed add Where Condition> ORDER BY RS.Fid ```
Why not to use union instead of inner join ... ``` select * from ( select c_name,c_val,fid from Revisions union select c_name,c_val,fid from Latest_updates)x where fid = 1 ```
SQL Subquery not working properly
[ "", "sql", "ms-access", "subquery", "" ]
I have a million row table in `Oracle 11g Express` and want to run a slow SQL select query so I can test stopping agents in various ways and observe the results on the database server. However no matter what I do, like self joins against a non-indexed column, selecting random rows using dbms\_random, where/order by st...
I'm not quite sure what you mean by "stopping agents" in this context. The only "agent" I can think of in this context would be an Enterprise Manager agent but I doubt that's what you're talking about and I don't see why you'd need a long-running query for that. The simplest way to force a query to run for a long time...
From `Oracle12c` you could use: ``` WITH FUNCTION my_sleep(t NUMBER) RETURN NUMBER AS BEGIN DBMS_LOCK.SLEEP(t); RETURN t; END; SELECT my_sleep(2) FROM dual; -- 2 after two seconds ``` This approach is nice because: * you don't need to use separate PL/SQL block (BEGIN ... END;) * it is fully contained query * doe...
How to create a slow SQL query?
[ "", "sql", "oracle", "database-performance", "" ]
I have a DB like ``` column_1 | column_2 | column_3 ------------------------------ aaa | bbb | ccc xys | hkj | fgh dfs | jhv | ccc cfg | rty | fgh iyd | olp | ccc gdv | tdr | www ``` I want to get the result such that all the ...
``` Select ... From table_name As T Where Exists ( Select 1 From table_name As T2 Where T2.column_3 = T.column_3 And T2.<Primary Key Column> <> T.<Primary Key Column> ) ``` Obviously, you would replace `<Primary Key Column>` with th...
Is it possible you're overthinking this? I believe you want ``` SELECT column_1, column_3 FROM table_name ORDER BY column_3, column_1 ```
sql query to return all rows with same column value
[ "", "mysql", "sql", "" ]
I have 2 tables. t1 and t2. t1 has an ID and a Reference. The format of that reference is TO-0000000 which cannot exceed 7 characters. t2 has 1500 records. How do insert that data with an incremented count? T2 doesn't contain a reference field. T2 contains an ID which has 1500 records. I want to import that ID or e...
I assume you want to import the `ID` column to T1 and also generate a reference field when inserting that data. If that is the case, then try this: ``` INSERT INTO T1 (ID,Reference) SELECT ID,'TO-'+Left('0000000',(7-LEN(ID)))+CAST(ID AS CHAR) FROM T2 ``` Try executing this in SSMS for easier understanding ``` DECLAR...
Make ID column of table t1 as `IDENTITY` and increment will automatically be taken care of. Now you only need to extarct refernces values from source table t2 and insert into target table t1. ``` INSERT INTO t1(References) SELECT References FROM t2 ```
SQL Server: How to generate a reference column with data that increments?
[ "", "sql", "sql-server", "" ]
Lets say you have the following table: ``` Id Index 1 3 1 1 2 1 3 3 1 5 ``` what I would like to have is the following: ``` Id Index 1 0 1 1 2 0 3 0 1 2 ``` As you might notice, the goal is for every row where Id is the same, to incrementally update the Index column, starting from zero. Now, I know this ...
Yes, assuming that the you don't really care about the order of the values for the new `index` values. SQL Server offers updatable CTEs and window functions that do exactly what you want: ``` with toupdate as ( select t.*, row_number() over (partition by id order by (select NULL)) as newindex from table t ...
With `Row_number()` -1 and `CTE` you can write as: ``` CREATE TABLE #temp1( Id int, [Index] int) INSERT INTO #temp1 VALUES (1,3),(1,1),(2,1),(3,3),(1,5); --select * from #temp1; With CTE as ( select t.*, row_number() over (partition by id order by (select null))-1 as newindex from #temp1 t ) Update CTE set [...
Is there a way to update groups of rows with separate incrementing values in one query
[ "", "sql", "sql-server", "t-sql", "" ]
What is "Impedance Mismatch" and how does it relate to databases?
Quoted from [hacked.com](http://haacked.com/archive/2004/06/15/impedance-mismatch.aspx/) > Imagine you have a low current flashlight that normally uses AAA > batteries. Don't try this at home, but suppose you could attach your > car battery to the flashlight. The low current flashlight will > pitifully output a fracti...
Relational impedance mismatch is a set of technical difficulties appearing because objects or class definitions must be mapped to database tables defined by relational schema. Concretely, initial versions of SQL were not computationally complete (they did not have any programming constructs like declarations or condit...
What is Impedance Mismatch?
[ "", "sql", "database", "" ]
I have a data structure, where I have to store pairs of elements. Each pair has exactly 2 values in it, so we are employing a table, with the fields(leftvalue, rightvalue....). These pairs should be unique, and they are considered the same, if the keys are changed. ``` Example: (Fruit, Apple) is the same as (Apple, Fr...
Two solutions, both really about changing the problem into an easier one. I'd usually prefer the `T1` solution if forcing a change on consumers is acceptable: ``` create table dbo.T1 ( Lft int not null, Rgt int not null, constraint CK_T1 CHECK (Lft < Rgt), constraint UQ_T1 UNIQUE (Lft,Rgt) ) go create ...
If you always store the values in order but store the direction in another column, ``` CREATE TABLE [Pairs] ( [A] NVarChar(MAX) NOT NULL, [B] NVarChar(MAX) NOT NULL, [DirectionAB] Bit NOT NULL, CONSTRAINT [PK_Pairs] PRIMARY KEY ([A],[B]) ) ``` You can acheive exaclty what you want with one clustered ...
Unique constraint on two fields, and their opposite
[ "", "sql", "sql-server", "sql-server-2008", "unique", "" ]
I have the following table: ``` DECLARE @T TABLE( Val NUMERIC(18,2) ``` ) with the following values: ``` INSERT INTO @T SELECT 3.01 INSERT INTO @T SELECT 30 INSERT INTO @T SELECT 2.00 INSERT INTO @T SELECT 2.1 ``` when I run this command: ``` SELECT * FROM @T ``` I get: ``` 3.01 30.00 2.00 2.10 ``` what I ...
Why don't you use a real number type instead. Following are the two ways. ``` DECLARE @T TABLE( Val real ) INSERT INTO @T SELECT 3.01 INSERT INTO @T SELECT 30 INSERT INTO @T SELECT 2.00 INSERT INTO @T SELECT 2.1 SELECT Val FROM @T ``` OR ``` DECLARE @T TABLE( Val NUMERIC(18,2) ) INSERT INTO @T SELECT 3.01...
Completely hackish, but a simple solution. But, it's not subject to rounding errors. ``` DECLARE @T TABLE( Val NUMERIC(18,2) ) INSERT INTO @T SELECT 3.01 INSERT INTO @T SELECT 30.00 INSERT INTO @T SELECT 2.0 INSERT INTO @T SELECT 2.10 INSERT INTO @T SELECT 2.20 INSERT INTO @T SELECT 2.30 INSERT INTO @T SELECT 2.4...
convert numeric(18,2) to varchar
[ "", "sql", "sql-server", "t-sql", "" ]
I have a text file with three columns of text (strings) per line. I want to create an SQL insert command by substituting each of the three strings into a skeleton SQL command. I have put place markers in the skeleton script and used SED s/placemarker1/first string/ but with no success. Is there an easier way to accompl...
``` awk '{print "INSERT INTO users (email,paypal_tran,CCReceipt) VALUES"; print "(\x27"$1"\x27,\x27"$2"\x27,\x27"$3"\x27);"}' input.txt ``` Converts your sample input to preferred output. It should work for multi line input. **EDIT** The variables you are using in this line: ``` cat temp1 | awk 'email="$1"; transac...
You can try this `bash`, ``` while read email transaction ccreceipt; do echo "INSERT INTO users (email,paypal_tran,CCReceipt) VALUES ('$email','$transaction','$ccreceipt');"; done<inputfile ``` inputfile: ``` catdog@gmail.com 2w4e5r6t7y8u9i8u7 1111-2222-3333-4444 dog@gmail.com 2dsdsda53563u9i8u7 3333-4444-5555-6666 ...
string substitution from text file to another string
[ "", "sql", "string", "bash", "awk", "sed", "" ]
I am attempting to group by twice, once by an individual level field and then by the month of the timestamp field. Little new to SQL but here's what I came up with after reading another SO post here: [SQL query to group by month part of timestamp](https://stackoverflow.com/questions/18087659/sql-query-to-group-by-mont...
There's no MONTH function in Teradata/Standard SQL, it's EXTRACT(YEAR/MONTH/DAY/HOUR/MINUTE/SECOND): ``` EXTRACT(MONTH FROM EVENT_GMT_TIMESTAMP) ```
Your query as written will result in a PRODUCT (Cartesian) JOIN between the VwNIMUserDIm and VwNIMEventFct tables (views). I have taken the liberty to modify the SQL based on your comments to the previous response: ``` SELECT User_.USER_EMAIL_ADDRESS, Event_.NIM_USER_ID, Event_.EVENT_GMT_TIM...
Grouping by Month of TimeStamp
[ "", "sql", "timestamp", "teradata", "group-by", "" ]
I have 2 Jobs that read and produce data in a Sql Server Database. Every once in a while the jobs crash with a System.Transactions.TransactionInDoubtException. The exact stack trace is: ``` Unhandled Exception: System.Transactions.TransactionInDoubtException: The transaction is in doubt. ---> System.Data.SqlClient.Sq...
Even if the transaction is local, transaction will still escalated to the MSDTC if you open multiple connections within the same transaction scope, according to this article: <http://msdn.microsoft.com/en-us/library/ms229978(v=vs.110).aspx> > An escalation that results in the System.Transactions infrastructure > trans...
I think this can happen also without MSDTC. I think I have had this happen in a system that did not use MSDTC at all. I think it is triggered if your DB connection fails at exactly a certain moment. The moment has to be such that the service has sent a COMMIT to the DB, but then the connection fails so that the service...
Reason for System.Transactions.TransactionInDoubtException
[ "", "sql", ".net", "sql-server", "transactions", "" ]
I have multiple tables. I only wanted to operate on these two. The objective is to project the order\_id, sum of (total order cost calculated from multiple table), order\_date ---grouped by each one order\_id and sorted by order\_date. It sounds quite simple, but I have multiple queries, sum gave error & wrong result....
The reason is that you combine the freightcharge from order\_detail\_table with aggregated data. Something like that should solve the problem: ``` select o.orderid, sq.total+o.freightcharge from order_table o left join ( select o.orderid, sum((od.unitprice*od.quantity)*(1-od.discount*0.01)) as total from order_ta...
I think this will work for you: ``` ;with OrderTotals AS ( select o.orderid ,o.freightcharge ,sum((od.unitprice*od.quantity)*(1-od.discount*0.01)) as total from order_table o inner join order_detail_table od on o.orderid = od.orderid group by o.orderid ,o.freightcharge ) select ...
SQL sum values from different tables using item_details group by order_id and order_date
[ "", "sql", "subquery", "aggregate-functions", "calculated-columns", "" ]
Im looking to query all Users without Comments in a single sql query? Models: ``` class User < ActiveRecord::Base has_many :comments end class Comment < ActiveRecord::Base belongs_to :user end ``` So I want the opposite of this: ``` User.joins(:comments).group('users.id') ``` But not like this: (because it ge...
You can accomplish this with: ``` User.includes(:comments).where.not(comments: { id: nil }) ``` This will result in raw SQL that looks something like: ``` SELECT DISTINCT `users`.`*` FROM `users` LEFT OUTER JOIN `comments` ON `comments`.`user_id` = `users`.`id` WHERE `comments`.`id` IS NULL ``` For accomplishing th...
If you are using `postgresql` you can do something like this ``` User.joins("LEFT join comments c on users.id = c.comment_id"). select("users.id"). group("users.id"). having("count(users.id) = 1") ``` This will generate this query ``` select u.id from users u LEFT join comments c on c.comment_id = u.id group by u.i...
Rails User.joins.not(...) in Active Record?
[ "", "sql", "ruby-on-rails", "activerecord", "ruby-on-rails-4", "" ]
I have a survey system which the following `questionanswer` table ``` questionId personId response 1 a red 2 a blue 3 a green 4 a black 1 b red 2 b blue 3 b green 4 b black ``...
How are you passing in the QuestionIds and Responses? Let's assume you eventually get them into a table variable: ``` DECLARE @Search TABLE ( questionId int, response varchar(30) ) ``` Then your SQL then becomes: ``` SELECT q.personID FROM questionanswertable AS q INNER JOIN @Search AS s ...
``` SELECT DISTINCT personId FROM questionanswer WHERE questionId IN(SELECT questionId FROM questionanswer WHERE questionId = 1 AND response = 'red') AND questionId IN(SELECT questionId FROM questionanswer WHERE questionId = 3 AND response = 'green') ```
Sql query which returns multiple rows matching criteria
[ "", "sql", "sql-server", "linq", "" ]
**Hello i have a table with columns:** ``` saled qty, item no, no -3, 1996-s, 149 -2, 1996-s, 150 -2, 1968-b, 151 ``` Now i should get the **top sold** products. Maybe i have to **group** somehow by item no and then sort by saled qty and then i could **select top 3** for example? **Update:** There are also other col...
``` SELECT TOP(3) item_no, SUM(saled qty) FROM TABLENAME GROUP BY item_no, [Item Ledger Entry Type] HAVING [Item Ledger Entry Type] = 1 ORDER BY SUM(saled qty) DESC ``` or ``` SELECT TOP(3) item_no, SUM(saled qty) FROM TABLENAME WHERE [Item Ledger Entry Type] = 1 GROUP BY ...
``` SELECT TOP 3 * FROM table GroupBy itemno ORDER BY saledqty DESC ``` **Update:** If you need to select other columns too, then include them in your GroupBy Clause also. For Example: ``` SELECT TOP 3 count(itemno),itemno,timestamp FROM table GroupBy itemno,timestamp ORDER BY saledqty DESC ```
SQL query - get top sold items from table with cols (saled qty, item no, no )
[ "", "sql", "sql-server", "select", "group-by", "" ]
I need a query to return a certain result for a certain column depending on what value the column that is being run the select statement against has. > if the column is one of the following : I, D, U then I want to return Y > > if the column is one of the following : N, E, D then I want to return N > > ``` > ...
I'd use the `IN` operator: ``` SELECT HIERARCHY_TYPE, NODE_ID, NODE_TYPE, NODE_NAME, NODE_LEVEL, PREFERRED_ALIAS, PARENT_NODE_ID, CASE WHEN ACTIVE_INDICATOR IN ('I','U','Y') THEN 'Y' WHEN ACTIVE_INDICATOR IN ('D','E','N') THEN 'N' ELSE NULL END AS ACTIVE_INDICATOR FROM MV_HIERARCHY MV; ```
``` CASE WHEN ACTIVE_INDICATOR IN ('I','U','Y') THEN 'Y' WHEN ACTIVE_INDICATOR IN ('D', 'E', 'N') THEN 'N' ELSE NULL -- useless, but for readbility END as ACTIVE_INDICATOR ``` You've got to repeat `ACTIVE_INDICATOR`, cause I don't think (may be wrong) you can use the syntax ``` CASE <field> WHEN IN() ```...
Case when using IN clause
[ "", "sql", "oracle", "select", "" ]
I want to return the 4 most recent for each CustomerID. So far I have: Use Northwind\_2012 ``` SELECT CustomerID, OrderDate FROM Orders ORDER BY CustomerID; ``` From here I want to restrict it to the 4 most recent OrderDate's for each CustomerID. Where do I go from here in order to achieve this, as I have also tried...
Tested, works: (assuming a "OrderID" primary key: ``` SELECT CustomerId, OrderDate FROM Orders as ExtOrders WHERE OrderId IN ( SELECT TOP 4 OrderId FROM Orders WHERE CustomerId LIKE ExtOrders.CustomerId ORDER BY OrderDate DESC) ORDER BY CustomerId; -- Might not work in SQLFiddle if CustomerId is t...
You can do this using `row_number()`, using either a subquery or CTE: ``` SELECT CustomerID, OrderDate FROM (SELECT o.*, ROW_NUMBER() OVER (PARTITION BY CustomerId ORDER BY OrderDate DESC) as seqnum FROM Orders ) o WHERE seqnum <= 4 ORDER BY CustomerID; ```
Returning the 4 most recent orders for each customer
[ "", "sql", "sql-server", "sql-server-2012", "" ]
**Problem:** I have a huge database with lots of tables and entries. My application is similar to a social network and in my database I've infos about user logged-in, users phone model, registration data... Number of page viewed, number of comments, replies... every info and user activity has a datetime reference. I ha...
Sounds like what you need is a [`materialized view`](http://docs.oracle.com/cd/B28359_01/server.111/b28326/repmview.htm#i29867) I suggest creating mviews with refresh on demand with an interval of your choice. You have two options to achieve your goal with materizlized views 1. Create a big mview using union all to ...
This can all be done with a single SQL statement and a single scan of the table, there's no need to do anything complicated unless this becomes too slow, in which case a MV might be the answer. ``` with all_cts as ( select os, count(*) as ct from peoples group by os ) select 'TotUser' as key, sum(ct) as valu...
Oracle best practice to store statistics and infos as key/value
[ "", "sql", "oracle", "jpa", "oracle11g", "" ]
I am a bit new to TSQL programming. I am using MS SQL Server 2008 R2. Why the following query doesn't work? I thought a select query just return a bunch of records and I should still be able to select from those records. ``` select * from ( select * from dbo.[sometable] ) ```
``` select * from ( select * from dbo.[sometable] ) as X ``` You always need to create alias if using FROM subquery even if later on you're not using this alias that's just how the thing works.
i want to select all the records from sometable then this should be enough ``` select * from dbo.[sometable] ``` However, if you want to filter your records of one table based on values from some other table then you can use nested queries like ``` select * from table1 where id in (select id from table2) ``` or you...
Why I cannot select from some selected results?
[ "", "sql", "t-sql", "" ]
I need to join two tables `Companies` and `Customers`. `Companies` table is in **MS SQLServer** and `Customer` table is in **MySQL Server** . What is the best way to achieve this goal ?
If I am understand correctly, you need to join tables in SQL Server, not in code, because tag is `sql`. If I have right, then you need to do some administrative tasks, like server linking. [Here](http://www.packtpub.com/article/mysql-linked-server-on-sql-server-2008) you have an explanation how to link MySQL server i...
1. Select Companies from DB1 2. Select Customers from DB2 3. Put them in `Map<WhatToJoinOn, Company>` and `Map<WhatToJoinOn, Customer>` 4. Join on map keys, creating a `List<CompanyCustomer>`
Joining two tables on different database servers
[ "", "sql", "" ]
I have a table that contains two text fields which hold a lot of text. For some reason our table have started growing exponentially. I suspect that TOAST (compression for text fields in postgres) is not working automatically. In our table definition we have not defined any clause to force compression of these fields. I...
[From the docs](http://www.postgresql.org/docs/9.3/static/storage-toast.html) . . . > If any of the columns of a table are TOAST-able, the table will have > an associated TOAST table, whose OID is stored in the table's > pg\_class.reltoastrelid entry. Out-of-line TOASTed values are kept in > the TOAST table, as descri...
This is old, but I've recently had some success with a similar issue. ANALYZE VERBOSE revealed that a couple of our tables had grown to > 1 page of disk per tuple, and EXPLAIN ANALYZE revealed that sequential scans were taking up to 30 seconds on a table of 27K rows. Estimates of the number of active rows were getting ...
How to check if TOAST is working on a particular table in postgres
[ "", "sql", "postgresql", "compression", "" ]
I am stuck in joining two tables "a" and "b". The structure of the two tables is given below. **Table A** ``` +-------------+---------------------+ + SKU | Title + +-------------+---------------------+ + 12345_786 | Some text + + | + + 12345_231 | S...
The problem you're finding is because the \_ underscore character has a meaning in a pattern string, much like the % percent character. You need to escape it as referenced in this post [How to escape underscore character in PATINDEX pattern argument?](https://stackoverflow.com/questions/863534/t-sql-how-to-escape-unde...
I would either create a new column on the table with the value after "\_" and then use this to join on OR create an indexed view. The view would create the new column. Your select query could then join on this new column (from the table or view) without having to do any additional string manipulation. This may also pr...
Joining two tables based on substring from foreign keys (MS SQL2005)
[ "", "mysql", "sql", "sql-server", "" ]
I have a table: ``` id firstval secondval 1 4 5 2 5 4 3 3 3 4 6 6 5 7 8 6 9 8 7 3 3 8 3 3 ``` The first thing I need to do is count the number of times `s...
``` SELECT id, @prevGreater AND secondval < firstval AS discrepancy, @prevGreater := secondval > firstval AS secondGreater FROM (SELECT * FROM YourTable ORDER BY id) AS x CROSS JOIN (SELECT @prevGreater := false) AS init ``` [DEMO](http://www.sqlfiddle.com/#!2/97f72c/9)
``` SELECT * from table t1 INNER JOIN table t2 on t1.ID+1=t2.ID -- here we join on t2.ID is t1.ID+1 WHERE t1.secondval>t1.firstval AND t2.secondval<t2.firstval ``` Now you can use COUNT statement as you want :)
Compare rows SQL counting discrepancies in value
[ "", "mysql", "sql", "" ]
I have two table of bank database. One is customer list and other is account list. When I left outer join customer to account I have records of customer which does not have anything. How can I print zero for them? ``` SQL> CREATE TABLE Customer ( 2 BSB# CHAR(6) NOT NULL, /* Bank B...
Change your first query line to ``` select c.name, COALESCE(CUS.MYSUM, 0) ``` `COALESCE` is a standard sql function that returns the value of the first expression among its arguments that does evaluate to NULL. if there is no such expression, it will return NULL instead. a searched `CASE` expression provides similar...
You can use [IFNULL](https://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#function_ifnull) for this <https://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#function_ifnull> ``` mysql> SELECT IFNULL(1,0); -> 1 mysql> SELECT IFNULL(NULL,10); -> 10 mysql> SELECT IFNULL(1/0,10); ->...
How to print zero for rows with no content?
[ "", "mysql", "sql", "sql-server", "oracle", "oracle11g", "" ]
<http://www.sqlfiddle.com/#!3/7a295/1> I have a ms sql database inside visual studio 10, I need help with a query to get me the most wanted game from the favourites table along with the game cover\_img from the games table. I have got the query working with the first part:- ``` SELECT game_name, game_platform...
Does this do what you want? ``` SELECT TOP 1 f.game_name, f.game_platform, g.cover_img, Count(f.game_name) as cnt FROM games g inner join favourites f ON g.name = f.game_name GROUP BY f.game_name, f.game_platform, g.cover_img ORDER BY Count(f.game_name) desc; ```
You can split your problem in smaller parts: ``` ; WITH Games AS ( SELECT * FROM ( VALUES ('Pacman', 'Atari', 'A'), ('Enduro', 'Atari', 'B'), ('River Raid', 'Atari', 'C') ) AS X (Name, [Platform], cover_img) ...
SQL Query get most wanted game details
[ "", "sql", "sql-server", "" ]
I'm sure this is a simple task, but I got stuck for couple of days: I've got simplified table: ``` INSERT INTO `tree` (`fruit`, `tree`) VALUES ('apple', 'A'), ('pear', 'A'), ('apple', 'B'), ('banana', 'B'); ``` and for example I need specify exactly what fruit i need and what i dont need, so I something like:...
You could also use grouping and check aggregate values in a HAVING clause, like this: ``` SELECT tree FROM tree GROUP BY tree HAVING MAX(fruit IN ('apple', 'banana')) = 1 AND MAX(fruit IN ('pear') ) = 0 ; ``` A more platform-independent version of the same method would involve CASEs: ``` SELEC...
A simple select should work with a NOT EXISTS check. ``` SELECT t1.tree FROM tree t1 WHERE t1.fruit='apple' AND NOT EXISTS (SELECT 1 FROM tree t2 WHERE t1.tree=t2.tree and t2.fruit='pear'); ```
mysql, how to select tree without node
[ "", "mysql", "sql", "" ]
I have two SQL Server 2008R2 tables as below: * `Tbl_Item` (`Item_Id`) * `Tbl_Item_Cost` (`Item_Id, Item_Cost`) Values in the tables are as below: `Tbl_Item`: ``` Item_Id -------------------- Candy Chocolate IceCream Chocolate/IceCream ``` `Tbl_Item_Cost`: ``` Item_Id Item_Cost ----------------------...
Okay. As you don't have the option of changing the design, although it's not good to hardcode anything but if you really want this to occur for only(always) these two items, you may try this. ``` SELECT I.Item_Id,CASE WHEN I.Item_Id='Chocolate/IceCream' THEN (SELECT SUM(Item_Cost) FROM dbo.Tbl_Item_Cost WHERE Item_Id ...
I would do it following: ``` SELECT t1.item_id+'/'+t2.item_id, t1.cost+t2.cost FROM tbl_item_cost t1 INNER JOIN tbl_item_cost t2 ON t1.item_id<>t2.item_id ``` We could also use CROSS JOIN which allows us to get all possible pairs `(xn, yn)` from sets `X={x1, x2, ..., xn}, Y={y1, y2, ... , yn}`. Here `X=Y`. But then w...
How to add same column value but having different IDs
[ "", "sql", "sql-server", "t-sql", "sql-server-2008-r2", "" ]
I have: ``` CREATE TABLE Vote (`pid` int, `choice` varchar(10)) ; INSERT INTO Vote (`pid`, `choice`) VALUES (1, 'a'), (2, 'b'), (3, 'ana'), (4, 'aya'), (5, 'ayna'), (6, 'anya'), (7, 'x'), (8, 'y'), (9, 'z') ``` And I'm trying to find how many choices included 'n' but not '...
The reason your result shows 12,12,12 is that the `count` gets the number of returned rows regardless of their values. You would use CASE for that as below ``` SELECT SUM(CASE WHEN v1.choice LIKE '%n%' AND v1.choice NOT LIKE '%y%' THEN 1 ELSE O) AS n_not_y SUM(CASE WHEN v2.choice LIKE '%y%' AND v2.choice NOT LIKE '%...
``` SELECT SUM(CASE WHEN (V.choice LIKE '%n%' AND V.choice NOT LIKE '%y%') THEN 1 ELSE 0 END) AS n_not_y, SUM(CASE WHEN (V.choice LIKE '%y%' AND V.choice NOT LIKE '%n%') THEN 1 ELSE 0 END) AS y_not_n ,SUM(CASE WHEN ((V.choice NOT LIKE '%y%' AND V.choice NOT LIKE '%n%') OR (V.choice LIKE '%y%n%' OR V.choice LIKE...
How to get three fields (one record) each counts different condition on the same field?
[ "", "sql", "" ]
I have a database table full of transactions. The transactions contain negative numbers from people returning items. I would like to add up all the amount field while also subtracting the negative values of returns from the total. How can I do this and output it out? Currently the best I can do is get: ``` SELECT SU...
``` SELECT personId,SUM(CASE WHEN amount<0 THEN amount ELSE 0 END) as NegativeTotal, SUM(CASE WHEN amount>=0 THEN amount ELSE 0 END) as PostiveTotal FROM outputaddition GROUP BY personID ``` If you want single column ``` SELECT personId,SUM(amount) as Total FROM outputaddition GROUP BY personID ```
try this, ``` SELECT SUM(amount) as ActualTotal ,Sum(Case When amount > 0 then amount else 0 end) totalOfPositiveOnly FROM outputaddition ```
MySQL Sum positive and negative - calculate the exact total from money transactions
[ "", "mysql", "sql", "" ]
I have two tables in my database and they each share the a field called cID. So here's an example: ``` Parent Table _______________ cID Name -- ------ 1 Record #1 2 Record #2 3 Record #3 Child Table _______________ ID cID Name -- --- ----- 10 1 Record #1 11 1 Record #2 12 2 Reco...
In your text, you say that parents are missing, but your example shows a parent without a child. For parents without children in a left join: ``` select p.* from parent p left join child c on p.cId = c.cId where c.cid is null ``` I created a [SQL Fiddle](http://sqlfiddle.com/#!3/84694/17) as an example. For...
With Subselect: ``` SELECT * FROM Child WHERE cID NOT IN (SELECT cID FROM Parent) ``` With Join: ``` SELECT Child.* FROM Child LEFT JOIN Parent ON Child.cID = Parent.cID WHERE Parent.cID IS NULL ```
Query database tables for missing link
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have a table a such that Select \* From a where person id =1; returns ``` person_id colA colB 1 AA BB 1 CC DD 1 EE FF ``` Now what i need is ``` person_id colA colB colA_row_2, colB_Row_2 ColA_row_3 ColB_ROW_3 1 AA BB CC DD EE FF ``...
You can use decode as an alternative. [https://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11\_QUESTION\_ID:4471013000346257238](https://asktom.oracle.com/pls/asktom/f?p=100:11:0%3a%3a%3a%3aP11_QUESTION_ID:4471013000346257238)
You need PIVOT for the query See the examples <http://www.oracle.com/technetwork/articles/sql/11g-pivot-097235.html> and <http://www.oracle-base.com/articles/11g/pivot-and-unpivot-operators-11gr1.php> You have to define how rows are converted into columns e.g. ``` pivot ( count(colA ) for colA in ('AA' as "AA"...
How to merge many rows into one oracle sql
[ "", "sql", "oracle", "oracle11g", "" ]
I have this query: ``` SELECT DISTINCT f.CourseEventKey, ( SELECT f.Title + '; ' AS [text()] FROM @Facilities WHERE CourseEventKey = f.CourseEventKey ORDER BY f.Title FOR XML PATH('') ...
I think you're going to have to manually wrap the Facilities inline query block with REPLACE statements to reverse the automatic escaping. It sounds like what you're wanting to do is concatenate multiple facilities that could present a given course. Have you considered other options? [This question](https://stackoverf...
Use `,TYPE).value('.','NVARCHAR(MAX)')` and your special characters will not be escaped: ``` SELECT DISTINCT f.CourseEventKey, ( SELECT f.Title + '; ' AS [text()] FROM @Facilities WHERE CourseEventKey = f.CourseEventKey ...
How to use FOR XML PATH('') in a query without escaping special characters?
[ "", "sql", "sql-server", "t-sql", "escaping", "for-xml-path", "" ]
I have an ID such as: ``` 61759092-5066-4D02-A0E4-000084E9E68D ``` The result I would like is: ``` \6\1\7\5 ``` This is my way: ``` select '\' + substring(CAST(idField as varchar(38)),1,1) + '\' + substring(CAST(idField as varchar(38)),2,1) + '\' + substring(CAST(idField as varchar(38)),3,1) + '\' + sub...
I'm not sure if it is any better but here is what I came up with. ``` Select left(x.id, 1) + '\' + left(right(x.Id, 3), 1) + '\' + left(right(x.Id, 2), 1) + '\' + right(x.Id, 1) From ( Select Left(cast(idField as varchar(38)), 4) as Id From myTable ) x ```
You can use the stuff function to accomplish this. ``` Select stuff(Stuff(Stuff(Stuff(Left(Cast(idField As VarChar(38)), 4),1,0,'\'), 3,0,'\'), 5,0,'\'), 7,0,'\') from myTable ```
build a varchar using the first four characters of a uniqueidentifier
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
I get crazy because of one query. I have a table like following and I want to get a data - **Summa of Values by Status For every Date in interval.** **Table** ``` Id Name Value Date Status 1 pro1 2 01.04.14 0 2 pro1 8 02.04.14 1 3 pro2 6 02.04.14 1 ...
Assuming you have a row for each date in the table, use conditional aggregation: ``` select date, sum(Case when name = 'pro4' and status = 0 then Value else 0 end) as values_0, sum(case when name = 'pro4' and status = 1 then Value else 0 end) as values_1 from Table t where date >= '2014-04-01' and date <...
To expand my comment the complete query is ``` WITH [counter](N) AS (SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL...
SQL query - sum of values by status for date interval
[ "", "sql", "sql-server", "t-sql", "group-by", "sql-order-by", "" ]
I really don't know what is happening insert query is not working for me. ``` $query_getgreenyear = "INSERT INTO `greenityear` `ConsolidateYear` VALUES ('".$sentdata."')"; ``` in $sentdata the value is ('A','B') and the datatype for `ConsolidateYear` is varchar.I need this value to be inserted into the database. but ...
You forgot to place a `bracket()` for your column name. Try this: ``` $query_getgreenyear = "INSERT INTO `greenityear` (`ConsolidateYear`) VALUES ('".$sentdata."')"; ```
Please take a look at the [MySQL Reference Manual](https://dev.mysql.com/doc/refman/5.1/en/insert.html). You need to surround your column name with parantheses in your INSERT statement: ``` $query_getgreenyear = "INSERT INTO `greenityear` (`ConsolidateYear`) VALUES ('".$sentdata."')"; ``` And I would highly recommen...
insert query is not working in mysql
[ "", "mysql", "sql", "insert", "" ]
I have following mysql table: ``` item code | warehouse | qty --------------------------- itm001 | abc |10 itm002 | xyz |20 itm003 | pqr |20 itm004 | pqr |15 itm001 | abc |60 itm002 | xyz |10 itm004 | tqr |20 itm003 | www |20 itm...
You should use `GROUP BY` with `HAVING`: ``` SELECT itemcode,warehouse,SUM(qty) FROM yourtable GROUP BY itemcode,warehouse HAVING COUNT(*) > 1; ``` `HAVING` filters out the items that only exist once in a warehouse.
try this: ``` SELECT itemcode,warehouse,SUM(qty) FROM table1 GROUP BY warehouse,itemcode; ```
Sum of one column based on two columns of dynamically value
[ "", "mysql", "sql", "" ]
I have a table: ``` id | value 1 | - 1 | a 2 | b 1 | c 3 | d 2 | e ``` then I need a counter column which begins from 1 for every different value in the id column Desired select result: ``` id | value | counter 1 | - | 1 1 | a | 2 2 | b | 1 1 | c | 3 3 | d | 1 2 | e | 2 ``` All ...
If you do not care about ordering, only about corresponding row number, use variables like this: ``` SELECT t.*, @i:=IF(id=@id, @i+1, 1) AS num, @id:=id FROM t CROSS JOIN (SELECT @i:=0, @id:=0) AS init ORDER BY id ```
What you are trying to accomplish is called **RANKING** . Unfortunately MySQL doesnot have ranking functions like in SQL Server `ROW_NUMBER()` , `DENSE_RANK()` etc.. You can try below query for MySQL ``` SELECT t.ID, t.Value, count(*) as Counter FROM tableName t JOIN tableName b ON t.ID = b.ID AND t.Value >= b.Value...
Incrementing counter on each duplicate in column
[ "", "mysql", "sql", "duplicates", "" ]
I'm not sure how to search for this and hence I started a new question. I have a table in the following structure ``` ---------------------------------------- | TALKS | PERSON ---------------------------------------- | Networks | John Doe | Steganography | Alex | Assembly | Mark...
SELECT DISTINCT talks, person FROM table
This is how you can achieve what you are trying ``` ( select talks,name from table1 group by name order by talks ) UNION ALL ( select distinct talks as talks, case when name is not null then '' end name from table1 ) ``` **[DEMO](http://www.sqlfiddle.com/#!2/b2a23/12)**
Selecting distinct row
[ "", "mysql", "sql", "" ]
I have this query: ``` SELECT DISTINCT ces.CourseEventKey, up.Firstname + ' ' + up.Lastname FROM InstructorCourseEventSchedule ices INNER JOIN CourseEventSchedule ces ON ces.CourseEventScheduleKey = ices.MemberKey INNER JOIN UserProfile up ON up.UserKey = ices.UserKey WHERE ces.C...
You can use `FOR XML PATH('')` in an inner query to get the concatenated values and then use it to match with `CourseEventKey` from the outer query: ``` ;WITH CTE AS ( SELECT DISTINCT ces.CourseEventKey, up.Firstname + ' ' + up.Lastname AS Name FROM InstructorCourseEventSchedule ...
``` select distinct ces.CourseEventKey,STUFF((SELECT ', ' +up.Firstname + ' ' + up.Lastname) AS Name FROM UserProfile up where UP.id = UserKey = ices.UserKey FOR XML PATH ('')) , 1, 1, '') AS Name) FROM InstructorCourseEventSchedule ices INNER JOIN CourseEventSchedule ...
How to concatenate distinct column values from rows with duplicate IDs into one row?
[ "", "sql", "sql-server", "t-sql", "concatenation", "" ]
Tables: ``` Users Roles RolesUsers ``` Associations: ``` User hasMany Role through RolesUsers Role hasMany User through RolesUsers ``` What I want is to get all **users** along with their all **roles** that (user) contain **at least one role** that matches given requirements. I use this query to get all users that...
``` SELECT u.* , r."name" AS "Roles.name" , r."id" AS "Roles.id" , ru."createdAt" AS "createdAt" , ru."updatedAt" AS "updatedAt" , ru."UserId" AS "UserId" , ru."RoleId" AS "RoleId" FROM "Users" u JOIN "RolesUsers" ru ON u."id" = ru."UserId" JOIN "Roles" r ON r."id" = ru."RoleId" WHERE EXI...
I would use analytic functions for this purpose, as in the following: ``` select ur.* from (select u.*, ru.name as rolename, ru.id as roleid, ru.createdAt as rolecreatedat, sum(case when ru.name in ('member', 'admin') then 1 else 0 end) over (partition by u.id) as NumMatches from users u join ...
Query to return all records (including all associated data) where at least one associated data matches requirements
[ "", "sql", "postgresql", "" ]
I have a script which declares a couple of temporary tables and has cursors to loop through each item and then performs updates. However, I wanted to add a rollback to this in case anything within the script fails it can roll back, otherwise commit. How would I do this exactly? I have looked at the other questions rel...
Roughly your code will work fine: ``` OPEN CURSOR BEGIN TRANSACTION BEGIN TRY COMMIT END TRY BEGIN CATCH ROLLBACK END CATCH END TRANSACTION CLOSE CURSOR ``` However, why do you want to use cursor? as far as I know, cursor performs slow in term of perform...
Here it is a [code snippet](http://sqlhint.com/sqlserver/scripts/tsql/code-template-handling-transactions-sql-server-rollback-xact_abort) to use: ``` SET XACT_ABORT ON; BEGIN TRY BEGIN TRANSACTION -- Your script here COMMIT TRANSACTION END TRY ...
Rollback and commit transaction SQL Server
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
I'm new in programming. I'm designing a database that has two tables: Addresses and Customers. I don't know how to assign foreign keys. I don't know which way is better to use: **Method1:** Customer Table Columns: CustomerID FirstName LastName Address ID Addresses Table Columns: AddressId Country State City Addres...
If you are trying to implement one to many, so the recommended way is to put the primary key for the table besides the one into the table of the many as a foreign key.. For example: if one costumer have many addresses and address have one costumer. so you will have to put the costumerId as a foreign key in the table o...
I will point out that you **may** actually have a many to many relationship. One address can have more than one customer and one customer can have more than one address. In this case you use a Join table to model the relationship that contains the addressid and the customerid and nothing else. This would have a join PK...
Implementing one to many relationship
[ "", "sql", "database", "" ]
Let's say I have a table `call_log` that has a column named `duration`. Let's further pretend that when I put the table together, I made the mistake of making `duration` a varchar column instead of a number. Now I can't properly sort on that column. I want to rename the column so I issue... ``` ALTER TABLE call_log MO...
Create a temporary column with the correct data type, copy the data to the new column, drop the old column, rename the new column to match what the old column was named. ``` ALTER TABLE call_log ADD (duration_temp NUMBER); UPDATE call_log SET duration_temp = duration; ALTER TABLE call_log DROP COLUMN duration; ALTER T...
the previous solution is excellent, however if you don't want to change the columns orders in call\_log table structure, then the following steps are for this: ``` create table temp_call_log as select * from call_log; /* temp backup table for call_log */ UPDATE call_log SET duration = null; /*check,... be sure.... th...
How to change datatype of column with data
[ "", "sql", "oracle", "" ]
I have the following: ``` create table words (value varchar(10)); insert into words values('bbbbb'); insert into words values('ccccc'); ``` If now I query `select * from words where value > 'b%';` I get: ``` +-------+ | value | +-------+ | bbbbb | | ccccc | +-------+ ``` The question is: how can I get all tuples ha...
`>` operator compares string in [lexicographical order](http://en.wikipedia.org/wiki/Lexicographical_order) see examples below: ``` mysql> SELECT 'a' > 'b', 'b' > 'a', 'ab' > 'aaa', 'ab' > 'b'; +-----------+-----------+--------------+------------+ | 'a' > 'b' | 'b' > 'a' | 'ab' > 'aaa' | 'ab' > 'b' | +-----------+----...
Try ``` WHERE value REGEXP '^[c-z]' ```
Get all values greater than 'x'
[ "", "mysql", "sql", "" ]
How can sum or Multiply row in SQL Server? For example... ![enter image description here](https://i.stack.imgur.com/fRkUE.png) I want to Sum Number1 and Number2 (1 + 4) and automatically number 5 will be added to Number3 column
If you want `Number3` to always contain the sum of `Number1` and `Number2`, then define it as a computed column. In the `create table` statement, say: ``` Number3 as (Number1 + Number2) ``` This will ensure that the third number is always the sum of the other two. Automatically.
``` update t set t.Number3 = t.Number1 + t.Number2 from mytable t ``` As @JoelCoehoorn very insightfully suggests, perhaps you want to include the value of `Number3` in which case it would be: ``` t.Number3 = t.Number3 + t.Number1 + t.Number2 ```
Sum or Multiply in SQL Server
[ "", "sql", "sql-server", "visual-studio", "" ]
I am trying to return FirstName, LastName, Line1, City, State, and ZipCode from the Customers table and the Addresses table using a join. I am to return one row for each customer, but only return addresses that are the shipping address for a customer. This is what I have so far: ``` SELECT FirstName, LastName, Line1, ...
Your join has to be based on AddressIds, not CustomerIds, ie: ``` SELECT FirstName, LastName, Line1, City, State, ZipCode FROM Customers JOIN Addresses ON (Customers.ShippingAddressId = Addresses.AddressID); ```
Do you mean, you need to return Customer detail even if doesn't have an address. If so, use Left Join ``` SELECT FirstName, LastName, Line1, City, State, ZipCode FROM Customers LEFT JOIN Addresses ON (Customers.CustomerID = Addresses.CustomerID and Customers.ShippingAddressID=Addresses.AddressID) ```
How do I extract only the shipping address and not the billing address using SQL and join?
[ "", "sql", "sql-server", "select", "join", "filtering", "" ]
Can I get data types of each column I selected instead of the values, using a select statement? FOR EXAMPLE: ``` SELECT a.name, a.surname, b.ordernum FROM customer a JOIN orders b ON a.id = b.id ``` and result should be like this ``` name | NVARCHAR(100) surname | NVARCHAR(100) ordernum| INTEGER ``` or it can ...
You can query the `all_tab_columns` view in the database. ``` SELECT table_name, column_name, data_type, data_length FROM all_tab_columns where table_name = 'CUSTOMER' ```
I found a not-very-intuitive way to do this by using `DUMP()` ``` SELECT DUMP(A.NAME), DUMP(A.surname), DUMP(B.ordernum) FROM customer A JOIN orders B ON A.id = B.id ``` It will return something like: `'Typ=1 Len=2: 0,48'` for each column. `Type=1` means `VARCHAR2/NVARCHAR2` `...
Get data type of field in select statement in ORACLE
[ "", "sql", "oracle", "function", "types", "" ]
apologies as i am fairly new to SQL but im having trouble finding a solution to a problem. I have two tables outline bellow: **Comment table** > Columns: Name, Comment, rating a, rating b, rating c, venue\_id **Venue table** > Columns: id, venue\_name, description, address I would like to get the Name from the ve...
Use Simple Join query. `SELECT Venue.venue_name, Comment.rating_a, Comment.rating_b, Comment.rating_c FROM Venue INNER JOIN Comment ON Venue.id=Comment.venue_id;` This will give you: * venue\_name (from the venue table) * rating a (from the comment table) * rating b (from the comment table) * rating c (from the comme...
``` select Venue.venue_name, rating_a, rating_b, rating_c from Venue, Comment where Comment.venue_id = Venue.id; ``` Explanation: Venue.venue\_name and the three rating\_ identifiers all tell SQL which columns you want to output (note: you may have to prepend Comment. in front of the three rating columns, but I t...
logical issue with SQL query dealing with two tables
[ "", "mysql", "sql", "sql-server", "" ]
Is it possible to search for multi-accounters in a cleaner method than what follows? I am searching for this in logs, having multiple accounts isn't against the rules, but I would like to know who is multi accounting. ``` SELECT a.username, a.ipaddr FROM logs AS a INNER JOIN logs AS b ON a.ipaddr = b.ipaddr AND a.user...
Use group\_concat with a distinct select subquery: ``` SELECT GROUP_CONCAT(a.username SEPARATOR ' & ') as username, a.ipaddr FROM (select distinct username,ipaddr from logs) AS a GROUP BY a.ipaddr HAVING count(*) > 1 ORDER BY a.ipaddr ``` <http://www.sqlfiddle.com/#!2/d9211/2> **EDIT** Added `HAVING count(*)...
Try with GROUP\_CONCAT ``` SELECT GROUP_CONCAT(a.username SEPARATOR ' & ') as username, a.ipaddr FROM logs AS a INNER JOIN logs AS b ON a.ipaddr = b.ipaddr AND a.username <> b.username GROUP BY a.username ORDER BY a.ipaddr ```
mySQL searching for multi accounters
[ "", "mysql", "sql", "" ]
I am trying to write a stored procedure in which the where clause needs to be dynamic based on the parameter passed to the procedure. Based on whether an empty string is passed to StartDate and EndDate, the ContractDate condition selects rows. If they are empty strings, the user would have passed a list of dates(assum...
Thanks for all your valuable suggestions. Just ended up cracking this with ands and ors ``` select TermDescription,ContractDate,Price,SortOrder into #tbtp from BaseTermPrice inner hash join Term on Term.TermID = BaseTermPrice.TermID where BaseID = @BaseID and ((@PeakType IS NULL and PeakType is null) or (@PeakType...
You should look into Dynamic SQL. Best place to start is <http://www.sommarskog.se/dynamic_sql.html>. Dynamic SQL lets you build the SQL string programmatically based on whatever conditions you need.
T-SQL stored proc conditionals in where clause
[ "", "sql", "sql-server", "" ]
``` CREATE TABLE kategorijos( kat_id number(11) not null, kat_pavadinimas varchar(255), CONSTRAINT kategorijos_pk PRIMARY KEY(kat_id) ); create or replace procedure delete_kategorijos (kat_id number) is begin delete from kategorijos where kat_id = kat_id; end; ``` I call procedure: ``` BEGIN delete_kategorijos(1); E...
You are using the below line of code for deleting records ``` delete from kategorijos where kat_id = kat_id; ``` Where in condition filed you can find that ``` where kat_id = kat_id; ``` Which is always true cause you are comparing same value thats why its deleting all the records
It is better to give the parameter another name, as follows: create or replace procedure delete\_kategorijos (l\_kat\_id number) is begin delete from kategorijos where kat\_id = l\_kat\_id; end; But think about the following: - what if kat\_id = 1 does not exist? - what if the record is locked by another transaction?
Oracle stored delete procedure
[ "", "sql", "oracle", "stored-procedures", "plsql", "" ]
I need to migrate data from one Database to another one, both are on the same local system. The tables and columns got different names and I mustn't migrate all the Columns from the old Database, so `Select *` doesn't work for me. ``` INSERT INTO newDatabase.table1(Column1, Column2); SELECT oldDatabase.table1(column...
Your query should go like this: ``` INSERT INTO newDatabase.table1 (Column1, Column2) SELECT column1, column2 FROM oldDatabase.table1; ``` **UPDATE** Since this answer is getting more attention than I even anticipated, I should expand on this answer. First of all, it might not be obvious from the answer itself, but...
``` INSERT INTO db1.table SELECT * FROM db2.table; ``` If you want to copy data to same tables of different db.
MySQL Insert Into from one Database in another
[ "", "mysql", "sql", "database", "" ]
I have this largish table with three columns as such: ``` +-----+-----+----------+ | id1 | id2 | associd | +-----+-----+----------+ | 1 | 38 | 73157604 | | 1 | 112 | 73157605 | | 1 | 113 | 73157606 | | 1 | 198 | 31936810 | | 1 | 391 | 73157607 | +-----+-----+----------+ ``` This continues for 38m rows. Th...
Anything that you do is going to require reading and writing 38m rows, so nothing is going to be real fast. Probably the fastest method is to put the data into a new table: ``` create table newTable as select id1, id2 from oldTable; ``` Or, if you want to be sure that you preserve types and indexes: ``` crea...
Disclaimer: this answer is MySQL oriented and might not work for other databases. I think in the accepted answer there are some things missing, I have tried to expose here a generic sequence I use to do this kind of operations in a production environment, not only for adding/removing columns but also to add indexes fo...
Drop Column from Large Table
[ "", "mysql", "sql", "" ]
Got three tables I'm joining. `submissions`, `submissions_votes`, and `users`. I want to find out how many total helpfulVotes there are (which is a sum of the count of all `submissions_votes`) and I've got that. I also want to return a count (boolean, rather) of 0 or 1 if the `user_id` of `sv.user_id` relates to the ...
You can check if the `sv.user_id` = input `user_id` using `CASE` and `SUM` it up (grouped by each submission). If the SUM is 1, then the input user\_id has a submission, otherwise not. *So, your input user\_id would go into the CASE function.* Also, the `COALESCE(SUM(sv.up), 0)` requires a grouping by whichever column...
I don't think you need an additional join. Just a boolean expression in the `select`: ``` SELECT s.*, u.username, u.photo as userPhoto, COALESCE(SUM(sv.up), 0) helpfulVotes, SUM(sv.user_id = u.id) as SubmissionUserMatches FROM submissions s LEFT JOIN submissions_votes sv on s.id =...
Get total count in addition of count if user voted
[ "", "mysql", "sql", "" ]
How can I do it so that when I run this query. ``` SELECT distinct cus_areacode AS "Area Code", cus_code AS "Number" FROM CUSTOMER WHERE cus_areacode = 713 OR cus_areacode = 615; ``` instead of showing the following. ``` Area Code Number 713 10015 713 10018 615 10019 615 10017 713 ...
``` SELECT cus_areacode AS "Area Code", count(cus_code) AS "Number" FROM CUSTOMER GROUP BY cus_areacode ```
Try this ``` SELECT cus_areacode AS "Area Code", count(cus_code) AS "Number" FROM CUSTOMER WHERE cus_areacode IN(713,615) GROUP BY cus_areacode; ``` OR: ``` SELECT cus_areacode AS "Area Code", count(cus_code) AS "Number" FROM CUSTOMER WHERE cus_areacode = 713 OR cus_areacode = 615 GROUP BY cus_areacode; ``` **[Fid...
Get count on SQL
[ "", "mysql", "sql", "" ]
`tableOne`: ``` id name -- ---- 1 A 2 B 3 C ``` `tableTwo`: ``` stuffno id stuff stufftype ------- -- ----- --------- 1 1 D1 D 2 1 E1 E 3 1 F1 F 4 2 D2 D 5 2 E2 E 6 2 F2 F 7 3 D3 D 8 3 E3 E 9 ...
You can use multiple `JOIN` to `tableTwo` to achieve the result you want: ``` SELECT p.name as name, f.stuff AS stuffF, d.stuff AS stuffD, e.stuff AS stuffE FROM tableOne p JOIN tableTwo f on (p.id = f.id AND f.stufftype = 'F') JOIN tableTwo d on (p.id = d.id AND d.stufftype = 'D') ...
Try something like ``` SELECT t1.name, t2.stuff as stuffD, t3.stuff as stuffE, t4.stuff as stuffF FROM tableOne t1 JOIN tableTwo t2 ON (t1.id = t2.id AND t2.stufftype = 'D') ... and repeat JOIN .. ON .. for 'E' (tableTwo t3) and 'F' (tableTwo t4) ```
grouping one to many relationship in a row
[ "", "sql", "join", "pivot", "" ]
``` Product ID Quantity DateAdded 1 100 4/1/14 2 200 4/2/14 3 300 4/2/14 1 80 4/3/14 3 40 4/5/14 2 5 4/6/14 1 10 4/7/14 ``` I am using this SQL statemen...
You are getting the same quantities because you are aggregating by `quantity` in the `group by` as well as product. Your version of the query, properly written would be: ``` SELECT ProductID, MIN(Quantity) AS Starting, MAX(Quantity) AS Ending FROM Records WHERE DateAdded BETWEEN '2014-04-01' AND '2014-04-30' GROUP BY...
Use the `row_number()` ranking function ``` select starting.*, ending.ending from (select ProductID, quantity as starting from (select * , ROW_NUMBER() over (partition by productid order by dateadded) rn from yourtable where DateAdded BETWEEN '2014-04-01' AND '2014-04-30'...
Get the first and last record of each item for the month
[ "", "sql", "sql-server", "" ]
``` create table #sample ( product varchar(100), Price float ) insert into #sample values ('Pen',10) insert into #sample values ('DVD',29) insert into #sample values ('Pendrive',45) insert into #sample values ('Mouse',12.5) insert into #sample values ('TV',49) select * from #sample ``` Consider this situati...
This is hard coded and has little flexiblity. Took my system 2 minutes to run. But might be helpful, sorry if it isn't. fnGenerate\_Numbers is a table function that returns integers within the range of the parameters. [Ways to do that.](http://www.sqlperformance.com/2013/01/t-sql-queries/generate-a-set-1) ``` DECLARE ...
The problem you are referring to is also known as the [knapsack problem](http://en.wikipedia.org/wiki/Knapsack_problem). There's a range of algorithms you can use to solve this. The most well known is dynamic programming, it requires that the weights are integer numbers, so you'd have to measure in cents. None of them ...
Need T-SQL Query find all possible ways
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "knapsack-problem", "" ]
the problem story goes like: consider a program to manage bank accounts with balance limits for each customer {`table Customers`, `table Limits`} where for each Customer.id there's one Limit record then the client said to store a history for the limits' changes, it's not a problem since I've already had date colum...
Will this do? ``` ;with l as ( select *, row_number() over(partition by customer_id order by date desc) as rn from limits ) select * from customers c left join l on c.customer_id = l.customer_id and l.rn = 1 ```
I am assuming that earlier (i.e. before implementing the history functionality) you must be updating the `Limits` table. Now, for implementing the history functionality you have started inserting new records. Doesnt this trigger a lot of changes in your databases and code? Instead of inserting new records, how about k...
SQL, to loop or not to loop?
[ "", "sql", "sql-server", "sql-server-2012", "" ]
i tried the query below and it returned an error "`single-row query returns more than one row`" ``` SELECT (SELECT COUNT(*) FROM pans) AS NUMBEROFPANS, (SELECT name FROM facts, pans WHERE fact_id=pafact_id) AS NAMEOFPANS, (SELECT COUNT(*) FROM stas) AS NUMBEROFSTAS, (SELECT name FROM facts, stas W...
It wasn't very clear what you were trying to do in your post. I think, considering your other answer / comments on other answers, here might be what you're trying to do: ``` SELECT Count(p.pafact_id) as PanCount, p.name as Pan, Count(s.safact_id) as StasCount, s.name as Stas, Count(z.zafact_id) as Zelyc...
You could run each sub-query to find the one(s) returning multiple rows. Alternatively, you could add '`where rownum = 1`' to each subquery, to force it to return only the first row it comes to.
single row query returns more than one row
[ "", "sql", "oracle", "" ]
I have a lot of rows with `city` and `direction` fields. But from an old import, city and direction are mixed in `direction` field. Like: ``` dir number, extra data, CITY, AL 111111 dir number, CITY, AL 111111 number, dir, number, CITY, dir number, CITY, AL 111111 ``` The important thing is that 'CITY' always com...
If you want the part before the last comma, one way (of many) is with a plain [`substring()`](https://www.postgresql.org/docs/current/functions-string.html#FUNCTIONS-STRING-SQL) call (regexp variant): ``` substring(direction FROM ',([^,]+),[^,]+$') AS city ``` [db<>fiddle here](https://dbfiddle.uk/?rdbms=postgres_11&...
From your data I would gather that you'll need something like this: ``` SELECT regexp_matches('direction_field', '([^,]+) \d{5}'); ```
Extract string from text field in PostgreSQL (using regex?)
[ "", "sql", "regex", "postgresql", "sql-update", "" ]
Price Table: ``` date | price ------------------ 2014-01-01 100 2014-01-02 20 2014-01-03 -30 2014-01-04 70 ... ``` Is it possible to show a result table with a SQL query? Result table: ``` date | price | total -------------------------- 2014-01-01 100 100 2014-01-02 20 120 2014-01-...
``` select date, price, @total := @total + price as total from (select date, price from your_table order by date) x CROSS JOIN (select @total := 0) r ```
``` select date, @total := @total + price as running_total, price from your_table, (select @total := 0) r order by date ```
MySQL Dynamic Addition and Subtraction Row
[ "", "mysql", "sql", "" ]