Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have a table with 2 fields, `val1` and `val2`, that contain same type. `val1` is mandatory and `val2` is optional -- but if present, should count as much as `val1`. ``` CREATE TABLE VALS ( id INT NOT NULL AUTO_INCREMENT, val1 INT NOT NULL, val2 INT DEFAULT NULL, timesign TIMESTAMP); ``` For that, I want to retrieve...
Try this: ``` SELECT val1 as res FROM VALS UNION SELECT val2 as res FROM VALS WHERE val2 is notNULL; ``` You don't need "distict", Union is itself give set.
One query with union ``` SELECT a AS f FROM t UNION SELECT b AS f FROM t HAVING f IS NOT NULL ORDER BY f ``` Works when both columns can be `NULL`
Select different fields as one field (no CONCAT)
[ "", "mysql", "sql", "field", "" ]
An application which we have built has undergone a large change in its database schema, particularly in the way financial data is stored. We have functions that calculate the total amount of billing, based on various scenarios; and the change is causing huge performance problems when the functions must be run many time...
**Answer to the update** To increase the performance you can create a view with the same definition of the CTE, so that the query plan will be stored and reused. If you have to calculate more than one total amount don't try to get them individually, a better plan would be to get all of them with a single query, wri...
A very quick win is to use a (TABLE VALUED) (INLINE) FUNCTION instead of a (SCALAR) (MULTI-STATEMENT) FUNCTION. ``` CREATE FUNCTION [dbo].[fnProcTotalBilled] (@PROCEDUREID INT) AS RETURN ( SELECT (sub-query1) + (sub-query2) + (sub-query3) AS amount );...
Poor performance in SQL Server function
[ "", "sql", "sql-server", "stored-procedures", "" ]
Is there a way to create a new table based on a SELECT query in SQL Server ? I do not want to manually enter all the fields (the table should be auto generated based on the fields in the query). I already tried : ``` CREATE TABLE new_table AS (SELECT * FROM ...); ``` but it did not work.
I had to alias the columns in the select, but I would have to think your current query aliases the fields if they don't have name. > ``` > select > * > into #tempabc > from ( > Select 'a' [test] > union > Select 'b' [test] > ) a > > select * from #tempabc > ```
You are using the wrong syntax for SQL Server. Instead, try: ``` SELECT * INTO new_table FROM old_table ```
Create table using select query in SQL Server
[ "", "sql", "sql-server", "" ]
I'm drawing a blank and need some help figuring out the right syntax for a between statement in mysql I'm doing a report and need to display the Year to Date information. I would like to have the query figure out the year and put it in the BETWEEN statement. if I do the following it works: ``` AND aa.entry_date BETW...
You need to use proper MySQL syntax. `+` the is SQL Server way to concat strings. `concat()` is MySQL, '+' is just numeric addition: ``` AND aa.entry_date BETWEEN date(concat(Year(CURDATE()), '-01-01')) AND date('2014-04-30') ``` Notice that I also switched to using single quotes for the string and date constants. T...
One option is to use the DATE\_FORMAT function, and supply a literal for the month and day. For example: ``` aa.entry_date BETWEEN DATE_FORMAT(NOW(),'%Y-01-01') AND NOW() ```
mysql between statement using the current year
[ "", "mysql", "sql", "" ]
I am currently testing out something, and encountering an issue when trying to insert some values in a table. I have 3 tables as following; Devices, Outdoor, indoor. ``` **outdoor** ---> **devices** <----- **indoor** net_id(pk) net_id(fk) net_id(pk) `...
Maintain a relation table among devices and in & out devices. **Solution 1**: For **Device\_Relation** Table ``` +------------------+--------------+ | Of Table | Column | +------------------+--------------+ | Indoor | net_id | -- <--- pk | Outdoor | net_id | -- <--- pk | ...
Use two columns in table device, one for indoor and one for outdoor, otherwise you can't distinguish which is indoor and which is outdoor because they may have same id as you describe. ``` ALTER TABLE devices ADD CONSTRAINT o_relationship FOREIGN KEY (net_indoor_id) REFERENCES indoor (net_id); ALTER TABLE devices ADD...
Insert issue on foreign key column
[ "", "mysql", "sql", "database", "foreign-keys", "sql-insert", "" ]
I am trying to load data into a table of my MySQL database, and getting this error. ``` LOAD DATA LOCAL INFILE 'C:\Users\Myself\Desktop\Blah Blah\LOAD DATA\week.txt' INTO TABLE week; ``` Reference: [this](https://dev.mysql.com/doc/refman/5.5/en/optimizing-innodb-bulk-data-loading.html) The path is hundred percent c...
I don't know what version of MySQL you are using but a quick Google search found possible answers to both your questions. Below are excerpts from the [MySQL 5.1 Reference Manual](http://dev.mysql.com/doc/refman/5.1/en/load-data.html): > The file name must be given as a literal string. On Windows, specify > backslashes...
I spent 2 days on this and finally got my mistake, Just changing backslashes by forward ones, as one contributor previously said. And finally worked for me. so was: ``` LOAD DATA LOCAL INFILE 'C:/ProgramData/MySQL/MySQL Server 5.7/Data/menagerie/pet.txt' INTO TABLE pet; ``` I just can say thanks a lot. p.s. don't wa...
MySQL LOAD DATA Error (Errcode: 2 - "No such file or directory")
[ "", "mysql", "sql", "bulkinsert", "load-data-infile", "" ]
Hi everyone I need some help, please. I have to do the following with pl/sql: For every Request\_number, assign the v\_id on each voucher a number starting with 1 and incrementing by 1. For example, If Request number 786530 has 3 vouchers associated to it, the first voucher should v\_id 1, the second voucher should ...
You can use a merge for efficiency: ``` create table vouchers (request_no number not null ,voucher_no number primary key ,v_id number); insert into vouchers values (200,22211,null); insert into vouchers values (200,22212,null); insert into vouchers values (200,22213,null); insert into vouchers values (201,22214,null)...
In Oracle, you can do this with a correlated subquery: ``` update table t set v_id = (select count(*) from table t2 where t2.Request_NO = t.Request_NO and t2.Voucher_no <= t.Voucher_no ); ```
For every Request_number, assign the v_id on each voucher a number starting with 1 and incrementing by 1
[ "", "sql", "oracle", "plsql", "" ]
I get the error from this line ``` SELECT table.field FROM table WHERE table.month = 'october' AND DATEDIFF(day, table.start_date, table.end_date) < 30 ``` The dates in my column are in the format m-d-yy Do I need to convert this to a different format? If so how? Using MariaDB
According to the documentation for MariaDB [`DATEDIFF`](https://mariadb.com/kb/en/datediff/) only takes *two* arguments: > **Syntax** > > `DATEDIFF(expr1,expr2)` > > **Description** > > `DATEDIFF()` returns `(expr1 – expr2)` > expressed as a value in days from one date to the other. `expr1` and > `expr2` are date or d...
@alex\_b it is a very common observation to get confused between the syntaxes of the DATEDIFF & TIMESTAMPDIFF functions. Following [link](http://www.w3schools.com/sql/func_datediff_mysql.asp) will certainly help with the syntax of DATEDIFF & [this page](https://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.ht...
Incorrect parameter count in the call to native function 'DATEDIFF'
[ "", "sql", "mariadb", "" ]
In my database, have 2 different fields i.) Employee ii.) Department In my `employee` table, ``` NAME Department --------------------- John IT Siti Research Jason Research ``` In my `Department`, ``` Name ------------ IT Research Computer ``` Using statement ``` SELECT DEPARTMENT.DNAME F...
**Two alternatives:** 1. Using `IN`: ``` SELECT name FROM Department WHERE name NOT IN (SELECT DISTINCT Department FROM Employee) ``` 2. Using `Left Join`: ``` SELECT D.NAME FROM DEPARTMENT D LEFT JOIN EMPLOYEE ON D.NAME = EMPLOYEE.Department WHERE EMPLOYEE.Department ...
Try `NOT IN`. Sub query need to be `DISTINCT` to avoid performance issue in future: ``` SELECT name FROM Department WHERE name NOT IN ( SELECT DISTINCT Department FROM Employee); ``` Or `NOT EXIST`, faster in most cases: ``` SELECT name FROM Department WHERE NOT EXIST ( SELECT 1 FROM Employee WH...
SQL count with another table in SELECT clause
[ "", "mysql", "sql", "sql-server", "oracle", "" ]
I'm trying to find the devices that are stuck in a certain status, and group them by their types. I query the database for the `count()` of devices in that status, and then do a couple of checks to see if those devices meet the criteria. However, it is not showing the types that do not have any `count()`. I need all ty...
If you use `left outer join`, you need to use it for all the joins in the query (typically). Otherwise, you might be "undoing" the earlier join. However, I don't think that is your only issue. The expression `count(d.name)` has to return at least 1 (unless `name` can be `NULL`). ``` SELECT d.type, count(h471.id) FROM...
I think you need something like ``` SELECT type, SUM(COUNT_RESULT) FROM ( SELECT device.type, 0 COUNT_RESULT FROM device UNION ALL SELECT device.type, count(1) FROM device, h471 WHERE device.recnum = h471.id AND device.changedon < (((SYSDATE ...
Display 0 when COUNT() returns nothing
[ "", "sql", "oracle", "join", "count", "subquery", "" ]
I am building a system that contains consultant profiles. In this system, each consultant can choose which certifications he or she has. Right now I am expanding the system to contain titles when a consultant has a certain set of certifications. The interesting tables is: ``` Person(stores ID, Firstname etc. of a pers...
Try this approach: ``` ;with pc as ( select p.personid, tc.titleid, count(*) as cnt_pc from person p inner join personcertification pc on p.personid = pc.personid inner join titlecertifications tc on pc.certificationid = tc.certificationid group by p.personid, tc.titleid ), tc as ( select t.tit...
There are a number of ways of doing this. Here is one: ``` select p.ID, p.Name, tcount.ID from Person p inner join ( -- Get the count of certs for each title for each person select pc.PersonID, t.ID TitleId, count(*) CertCount from PersonCertification pc inner join Certification c on c.ID = pc.Certifi...
Matching lists in sql
[ "", "sql", "sql-server", "sql-server-2012", "" ]
if i try the below code for eg: i will set the date as Fri July 25 2014 10:00 AM. which gives date in milliseconds as `1402080056000`, now if i try to read the same milliseconds to date as below ``` long time = 1402080056000; Date mydate = new Date(time); ``` mydate variable shows date as `Sat Jun 25 00:10:56 ...
Just need to work on the format string, ``` String dateTimeString= String.valueOf(new SimpleDateFormat("dd-MM-yyyy hh:mm").format(new Date(time))); ``` Explicitly set time zone: ``` SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm"); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); String re...
Try this: ``` String date= DateFormat.format("dd/MM/yyyy hh:mm:ss", new Date(date_in_milis)).toString(); ```
How to get standard format date in android
[ "", "android", "sql", "date", "android-date", "" ]
This question must be really silly, but I haven't found an answer for it yet. I'm making a program in C # that dynamically writes a script to run on SQL Server. I declared two variables that receive the values returned from two calls *exec 'procedure\_name'*. In the next block of the script, I want these variables to...
You can do it via SELECT: ``` SELECT @a = 0, @b = 0 ``` With SET you need 2 SET commands: ``` SET @a = 0; SET @b = 0 ```
Method 1 ``` set @a = 0 set @b = 0 ``` Method 2 ``` Select @a = 0, @b = 0 ```
How to set two local variables with the same value in sql server?
[ "", "sql", "sql-server", "variables", "local", "" ]
Having two tables Department table ``` //Department D# DNAME ------------------- 1 SALES 2 ACCOUNTING 3 GAMES 5 SPORTS ``` Project table ``` //Project P# D# ----------- 1001 1 1002 3 1003 5 1004 5 ``` When output display it should be something like: ...
``` SELECT D.D#, COUNT(p.P#) FROM Department d LEFT JOIN Project p ON Project.D#=Department.D GROUP BY d.D#; ```
Try This: ``` SELECT D# , CASE WHEN A.COUNT > 0 THEN D# ELSE 0 END AS TOTAL_PROJECT FROM DEPARTMENT JOIN (SELECT D# , COUNT(*) FROM PROJECT GROUP BY PROJECT.D#) A ON DEPARTMENT.D# = A.D#; ```
SELECT using GROUP BY and display the total with two tables
[ "", "mysql", "sql", "oracle", "" ]
I am using the following line within a Select which returns a number with decimals, e.g. 33.33333. How can I round this within the Select and convert to integers so that I don't have decimals, e.g. in the above example it should return 33 ? ``` 100 * AVG(CASE WHEN col2 = col3 THEN 1.0 ELSE 0.0 END) AS matchPercent ``...
You can use `ROUND` function to round the value to integer: ``` ROUND(INT, 100 * AVG(CASE WHEN col2 = col3 THEN 1.0 ELSE 0.0 END), 0) AS matchPercent ``` This will retain the type, e.g rounded `float` will stay `float`. If you also need to return `int` data type (or other integer data types), you need to also convert...
Use the `round` function to round the number: ``` ROUND(100 * AVG(CASE WHEN col2 = col3 THEN 1.0 ELSE 0.0 END), 0) AS matchPercent ```
SQL Server: round decimal number and convert to int (within Select)
[ "", "sql", "sql-server", "select", "int", "rounding", "" ]
I have a table of employees Salary named as **empSalary**. ![empSalary](https://i.stack.imgur.com/mOFVj.png) I want to calculate sum of salaries issued by each department. What comes to my mind is ``` Select sum(Salary) from empSalary where deptId = (Select deptId from empSalary) ``` This statement gives me **5100*...
You want to `GROUP BY` the Department: ``` SELECT Dept_ID ,sum(Salary) Total_Salary FROM empSalary GROUP BY Dept_ID ```
This is exact use of group by , you make groups and and each group you can calculate sum, average, min , max or count ``` select DeptID, Sum(Salary) as SumSalary From empSalary Group by DeptID ```
Sum of a field with respect to another field
[ "", "sql", "group-by", "" ]
I have two identical tables that need to be updated on daily basis. Both tables have Exact same structure. They have 100+ columns. So, is there a way in SQL to update all the columns from TableA based on TableB without writing a (Set columnname = '') update statement for every single column? Both table have identical c...
It is a bit hacky but it can be done. I have created two identical tables with each 2 records. (Table\_1 and Table\_2) **Table\_1** ![Table_1](https://i.stack.imgur.com/qVgaj.png) **Table\_2** ![Table_2](https://i.stack.imgur.com/ojgBl.png) SQL: ``` DECLARE @LeftTable VARCHAR(MAX) = 'Table_1'; DECLARE @RightTab...
Available ways of doing are `UPDATE` statement and `MERGE` statement. Both of them require specyfing column names to update in `SET` clause. If you want, you can write a dynamic SQL that would read the schema of the tables and produce a query with all column names. This way you wouldn't have to write all the column na...
SQL Update Two Identical Tables
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
Consider a sorted table (according to id). How to count number of changes of the values in column 'value'? In the following example, the number of changes is 3 (10 to 20, 20 to 10, 10 to 30). Thx ``` id value 1 10 2 10 3 20 4 20 5 10 6 30 7 30 ```
if ids are sequential with no gaps... ``` Select count(*) From table t1 join table t2 on t2.id = t1.id + 1 where t2.value <> t1.value ``` else... ``` Select count(*) From table t1 join table t2 on t2.id = (Select min(id) From table where id > t1.id) where ...
You can identify the changes by using a correlated subquery. Then add them up. A change occurs when the value is different from the previous value: ``` select count(*) from (select t.*, (select value from table t2 where t2.id < t.id order by t2.id desc ...
Counting value changes in a table column
[ "", "sql", "sqlite", "" ]
How do you access another database from same server? Got server name using SELECT @@SERVERNAME, and then did servername.dbo.mydatabasename.mytablename but query analyzer says Invalid object name. Any ideas? Am doing ``` insert into Myservername.Mydatabasename.Mytablename (Email,Username1) Values ('h','h') ``` Using M...
Assuming you're using MS SQL Server, fully qualified references are in the form: ``` [servername].[databasename].[schema].[object] ``` On the same server you do not need the `[servername]` reference. In your case, you reversed the `databasename` and `schema`. It should be: `servername.mydatabasename.dbo.mytablename...
Is it not rather `mydatabasename.DBO.mytablename` ? And if your database is on the same server, you normally don't have to use the `servername`.
Access another database from same server?
[ "", "sql", "sql-server", "" ]
How can I get all the dates between two dates? I have a variable `@MAXDATE` which is storing the maximum date from the table. Now I want to get the all dates between `@Maxdate` and `GETDATE()` and want to store these dates in a cursor. So far I have done as follows: ``` ;with GetDates As ( select DATEADD(day...
My first suggestion would be use your [calendar table](http://web.archive.org/web/20170820091319/http://blog.jontav.com/post/9380766884/calendar-tables-are-incredibly-useful-in-sql), if you don't have one, then create one. They are very useful. Your query is then as simple as: ``` DECLARE @MinDate DATE = '20140101', ...
You can use this script to find dates between two dates. [Reference taken from this Article:](http://www.dbrnd.com/2015/08/list-all-dates-between-two-dates-in-sql-server/) ``` DECLARE @StartDateTime DATETIME DECLARE @EndDateTime DATETIME SET @StartDateTime = '2015-01-01' SET @EndDateTime = '2015-01-12'; WITH DateRan...
Get all dates between two dates in SQL Server
[ "", "sql", "sql-server", "" ]
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''comments' ( 'id' int(10) unsigned NOT NULL AUTO\_INCREMENT, 'article\_i' at line 1 ``` CREATE TABLE IF NOT EXISTS 'comments' ( 'id' int(10) unsigned NOT NULL AUTO_INCREMENT...
Remove the single quotes. Try this: ``` CREATE TABLE IF NOT EXISTS comments ( id int(10) unsigned NOT NULL AUTO_INCREMENT, article_id int(10) NOT NULL, comment varchar(45) NOT NULL, time datetime NOT NULL, name varchar(45) NOT NULL, email varchar(45) NOT NULL, PRIMARY KEY (id), KEY 'fk_...
Use backticks instead of single qoutes .Single qoutes are used for string literals. ``` CREATE TABLE IF NOT EXISTS `comments` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `article_id` int(10) NOT NULL, `comment` varchar(45) NOT NULL, `time` datetime NOT NULL, `name` varchar(45) NOT NULL, `e...
SQL syntax error, Can't find it?
[ "", "mysql", "sql", "ddl", "" ]
I have the following SQL table that keeps track of a user's score at a particular timepoint. A user can have multiple scores per day. ``` +-------+------------+-------+-----+ | user | date | score | ... | +-------+------------+-------+-----+ | bob | 2014-04-19 | 100 | ... | | mary | 2014-04-19 | 100 | .....
If you want all the fields, the easiest (and fastest) way in MySQL is to use `not exists`: ``` SELECT * FROM `user_score` us WHERE `user` = 'bob' AND NOT EXISTS (SELECT 1 FROM user_score us2 WHERE us2.`user` = us.`user` AND us2.date = us.date AND ...
You can use a `JOIN`: ``` SELECT a.* FROM `user_score` as a INNER JOIN (SELECT `user`, `date`, MAX(score) MaxScore FROM `user_score` GROUP BY `user`, `date`) as b ON a.`user` = b.`user` AND a.`date` = b.`date` AND a.score = b.MaxScore WHERE a.`user` = 'bob' ```
SELECT specific rows when using GROUP BY
[ "", "mysql", "sql", "" ]
I'm able to unpivot a table but null values are not included in the result. ``` create table pivot_task ( age int null, [a] numeric(8,2), [b] numeric(8,2), [c] numeric(8,2), [d] numeric(8,2), [e] numeric(8,2) ); select * from pivot_task; insert into pivot_task values (18, 0.5, null, 0.6, 1.21, 1.52), (19, 7.51, 6.51...
This is ugly but doesn't rely on having to find an out-of-band replacement for `NULL`: ``` declare @pivot_task table ( age int null, [a] numeric(8,2), [b] numeric(8,2), [c] numeric(8,2), [d] numeric(8,2), [e] numeric(8,2) ); insert into @pivot_task values (18, 0.5, null, 0.6, 1.21, 1.52), (19, 7.51, 6.51, 5.51, null,...
Try this, it will replace all the null values with 10000000 before unpivot that is not an acceptable number in numeric(8,2), so the value will not exist already. Then the value will be replaced by null after unpivot: ``` ;WITH x as ( select age, coalesce(cast(a as numeric(9,2)), 10000000) a, coalesce(cast(b as numeri...
Handle NULL value in UNPIVOT
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-2012", "unpivot", "" ]
I would say my understanding of SQL is average, but I am wondering if there is any way to more efficiently write this statement? The primary key of table `Company` is `uniqentity` and has the company name `nameof` in that row. In the table `Line`, the primary key is `uniqline` and I have columns `entityCompanyBilling...
Changing the structure of the *query* may not make it more efficient (it seems to be as simple as it can be). But changing the structure of the *data* might: * Add indexes (if not already) on `UniqEntityCompanyBilling` and `UniqEntityCompanyIssuing` * Add index on `Company.UniqEntity` Didn't catch that the column is t...
This query is perfectly fine as it is. You could make it shorter like below, but this will decrease readability and is generally considered bad practice, so don't. ``` SELECT l.uniqline, b.nameof AS billingcompany, l.UniqEntityCompanyBilling, i.nameof AS issuingcompany, l.UniqEntityCompanyIssuing FROM Line l, Company...
SQL Combining two joins
[ "", "sql", "join", "" ]
This is how my table looks like: ``` SELECT table2.status, table1.title FROM table1 RIGHT JOIN table2 ON table1.id = table2.id ``` ``` status title EXPIRED USER A EXPIRED USER B ACTIVE USER B EXPIRED USER C ``` And I want to get the titles from the users which status is not ACTIVE, I tried: ``` SELECT ...
Here is a statement that gives you one row per non-active user: ``` SELECT CASE WHEN MAX( case when table2.status = 'EXPIRED' then 1 else 0 end ) = 1 THEN 'EXPIRED' WHEN MAX( case when table2.status = 'CANCELLED' then 1 else 0 end ) = 1 THEN 'CANCELLED' WHEN MAX( case when table2.status = 'NEW' then 1 ...
It would help if you showed your table structure. But here is one way to approach this: ``` select t1.* from table1 t1 where not exists (select 1 from table2 t2 where t2.id = t1.id and t2.status = 'ACTiVE' ); ```
MySQL select row with NOT LIKE
[ "", "mysql", "sql", "" ]
``` | user_id | name | =================== | 1 | marc | | 2 | paul | | 3 | glen | | 4 | kyle | | 5 | jayc | | 6 | ken | | 7 | raff | ``` I have a sample table shown above. I want to retrieve the row of user id 1,2 and 5 only in a single query. Can you ...
Try this [**IN**](http://technet.microsoft.com/en-us/library/ms177682.aspx) ``` SELECT * FROM tablename WHERE user_id IN (1,2,5); ``` # [**Working Fiddle**](http://www.sqlfiddle.com/#!2/06bef/1) ![enter image description here](https://i.stack.imgur.com/VyyCr.png)
``` Select * from users where user_id in (1,2,5) ```
Get multiple rows in a single query
[ "", "mysql", "sql", "" ]
I have a query operation as below, it is from a single table but too much sub-query. Anybody could optimizing on it? ``` SELECT t.order_no , user_assign , t.busi_code , t.inst_addr4 AS district, t.inst_addr3 AS estate ,listagg(to_char(date_appoint,'yyyy-mm-dd'),',') within g...
The first step you can take, is to remove the subquery with the "total > 2", and replace that with the more elegant HAVING clause, like this: ``` SELECT t.order_no , user_assign , t.busi_code , t.inst_addr4 AS district , t.inst_addr3 AS estate , listagg(to_char(date_appoint,'yyyy-mm-dd'),','...
Replace `WHERE t.order_no IN` with ``` JOIN (subselect) sub ON t.order_no =sub.order_no ``` Replace the calls `AND date_appoint <= to_date('2014-04-17', 'yyyy-mm-dd')` with `AND date_appoint <= :date_parameter` to avoid to\_date() convert for each row. Add indexes for the columns used in `WHERE`
How to optimize this sql in oracle?
[ "", "sql", "oracle", "" ]
I have a problem regarding a select query, I'm using CTE for execute a query, my query is how to apply condition in CTE before `Where` clause, Table `Temp`: ``` Id | Title -------------- 1 | ABCD 2 | ABCD 3 | AB 4 | CD 5 | DA Declare @Count int,@search nvarchar(50) Select @se...
I think this is what you are after: ``` WITH TempResult AS ( SELECT * FROM Temp WHERE (@Count<>1 OR Title LIKE '%'+@Search+'%') ) SELECT * FROM TempResult ``` **Explanation:** The records will be filtered with `Title LIKE '%'+@Search+'%'` **only** when @Count != 1. To be more precise: When `@Count` = 1, it will g...
Looks like ``` WITH TempResult as ( Select * from Temp WHERE @count <> 1 OR Title = @Search ) SELECT * from TempResult ```
How to apply condition before where clause within CTE
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
In Oracle, to retrieve the SQL used to create a Function, Package, etc, the user\_source view can be queried. However, views are not included in this view - nor do they exist in the underlying `sys.source$`. To access the text of views, the `user_views.text` column can be used, but this is not exact because Oracle will...
I think the original text is lost: ``` create table t1(id number) / create view t1_vw as select * from t1 / alter table t1 add val varchar2(20) / alter view t1_vw compile / select * from t1_vw / ``` will return only id column. Interesting, but for materialized views original text is preserved.
You can use the following query: ``` SELECT VIEW_NAME, TEXT FROM USER_VIEWS; ``` or you can use ALL\_VIEWS, as in ``` SELECT VIEW_NAME, TEXT FROM ALL_VIEWS; ``` **References**: [ALL\_VIEWS on Oracle® Database Reference](http://docs.oracle.com/cd/B19306_01/server.102/b14237/statviews_2117.htm#i1593583)
How to retrieve the SQL used to create a view in Oracle?
[ "", "sql", "oracle", "" ]
I have tables a, b, c, and d whereby: ``` There are 0 or more b rows for each a row There are 0 or more c rows for each a row There are 0 or more d rows for each a row ``` If I try a query like the following: ``` SELECT a.id, SUM(b.debit), SUM(c.credit), SUM(d.other) FROM a LEFT JOIN b on a.id = b.a_id LEFT JOIN c o...
``` SELECT a.ID, debit, credit, other FROM a LEFT JOIN (SELECT a_id, SUM(b.debit) as debit FROM b GROUP BY a_id) b ON a.ID = b.a_id LEFT JOIN (SELECT a_id, SUM(b.credit) as credit FROM c GROUP BY a_id) c ON a.ID = c.a_id LEFT JOIN (SELECT a_id, SUM(b.other) as other ...
Your analysis is correct. Unrelated `JOIN` create cartesian products. You have to do the sums separately and then do a final addition. This is doable in one query and you have several options for that: * Sub-requests in your SELECT: `SELECT a.id, (SELECT SUM(b.debit) FROM b WHERE b.a_id = a.id) + ...` * `CROSS APPLY`...
SQL summations with multiple outer joins
[ "", "sql", "" ]
I am trying to show only the highest selling product per work center, however, it keeps telling me that LIMIT 1 is the incorrect syntax. I cant seem to find an answer on here that has helped so I decided to ask the question. Here's my query. ``` SELECT WorkCenter.WorkCenterCode, Product.Name, SUM(CustomerOrderLine.Qua...
Here is your query cleaned up a bit: ``` SELECT wc.WorkCenterCode, p.Name, SUM(col.Quantity*col.ActualPrice) AS "Total Sales" FROM WorkCenter wc INNER JOIN Product p ON wc.WorkCenterCode = p.WorkCenterCode INNER JOIN CustomerOrderLine col ON p.ProductID = col.ProductID GROUP BY wc.WorkCenterCode, ...
For SQL Server use `SELECT TOP 1` ``` SELECT TOP 1 WorkCenter.WorkCenterCode, Product.Name, SUM(CustomerOrderLine.Quantity*CustomerOrderLine.ActualPrice) AS [Total Sales] FROM WorkCenter INNER JOIN Product ON WorkCenter.WorkCenterCode = Product.WorkCenterCode INNER JOIN ...
SQL LIMIT 1 DESC order
[ "", "sql", "sql-server", "ssms", "" ]
``` delimiter // CREATE TRIGGER Discount BEFORE INSERT ON ORDER_TABLE FOR EACH ROW BEGIN DECLARE OrderNum INT; DECLARE Membership BOOLEAN; DECLARE Disc DECIMAL(10, 2); DECLARE Cost DECIMAL(10, 2); SELECT OrderCount INTO OrderNum FROM Customer WHERE CustomerID = NEW.CustomerID; SELECT M...
First of all, the error message is coming from using OrderCount in the if block. You should be using the variable you declared and read this value into, OrderNum. The other problem you might have, which I can't tell from this design, is when the Order Number is being updated. It might be best to add this to the trigge...
I work with oracle and it's quite different, but reading your trigger i suggest you , to rewrite the 4 querys to 2, this way you can avoid read each table twice. .: .: ``` .: SELECT OrderCount, Member INTO OrderNum, Membership FROM Customer WHERE CustomerID = NEW.CustomerID; SELECT Discount, Price ...
SQL Trigger Causing Error 1054
[ "", "mysql", "sql", "triggers", "" ]
I have got a following query which counts the number of orders for last week for seven sites. If there is no order for a given site in last week it display 0 rather than not displaying the site at all, hence the reason i am using the Case statement. All well and good, the challenge is that for a given date lets say 21/...
You can get distinct dates in an inner query and then run your query on top: ``` select SITENAME ,SUM(Case When OrderDate >= dateadd(dd,(datediff(dd,-53690,getdate()-1)/7)*7,-53690) Then 1 Else 0 End) as COMPLETED from ( SELECT DISTINCT SITENAME, OrderDate FROM TABLE1 ...
A simple and readable way to do that would be using a CTE: ``` ;WITH data AS ( SELECT DISTINCT Sitename, DATEADD(dd,(datediff(dd,-53690,getdate()-1)/7)*7,-53690) Date, ORDERDATE, FROM TABLE1 WHERE CLIENT in ('SITE1','SITE2','SITE3','SITE4','SITE5','SITE6','SITE7') ) select SITENAME ,SUM(Case...
SQL SERVER Counting one record for a day
[ "", "sql", "sql-server", "" ]
I have a logic-thinking problem. How should I design following database? A manufacturer sells cars. He sells them as they are, or with a package A, or with a package B, or with both packages. I would create a table with the different car models, then a table with the different packages, but I don't know how to create...
Add "offer" table. This table will contain price. Each offer should have at least one car and no, one, two, many, or all (if there will be more then 2 of them) packages. ![enter image description here](https://i.stack.imgur.com/hiRYu.png)
I would guess that a car would have a manufacturers suggested retail price (MSRP). Each package or option would have its own additional price on top of the MSRP. I'd have a base Car table, a Package table, and another purchased Car table, one to many with a Customer table, where the Customer can associate their base C...
How to design a car-packages-database?
[ "", "sql", "database", "database-design", "" ]
Find the names of all departments located either in BOSTON or in DALLAS" and not in both cities. I having the code like this ``` SELECT D.DNAME FROM DEPARTMENT D INNER JOIN DEPTLOC L ON L.DNAME = D.DNAME WHERE L.CITY='BOSTON' OR L.CITY='DALLAS' ; ``` But this will show the department that located in BOSTON OR DA...
Group them, then calculate the total count for each departments, then filter all departments which has only one location. ``` SELECT D.DNAME FROM DEPARTMENT D INNER JOIN DEPTLOC L ON L.DNAME = D.DNAME WHERE L.CITY='BOSTON' OR L.CITY='DALLAS' GROUP BY D.DNAME HAVING COUNT(1) = 1 ```
Try this: ``` SELECT D.DNAME FROM DEPARTMENT D INNER JOIN DEPTLOC L ON L.DNAME = D.DNAME GROUP BY D.DNAME HAVING 1 = SUM(CASE WHEN L.CITY IN ('BOSTON', 'DALLAS') THEN 1 ELSE 0 END); ```
Either in not both clause in select sql
[ "", "sql", "oracle", "" ]
For some reason I get the following error when running the code below: ``` #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM postcodes_demographics INNER JOIN latlon1 on postcodes_demographics.postc' at line 3 ``` I don'...
You have an errant comma: ``` SELECT postcodes_demographics.*, latlon1.*, <--- HERE ``` Remove it.
I would be very surprised if merely removing the comma fixes the problem. When using `insert`, you should get in the habit of listing all the columns explicitly: ``` INSERT INTO pslatlong(col1, col2, . . . ) SELECT d.col1, l.col2, . . . FROM postcodes_demographics d INNER JOIN latlon1 ll on d...
mysql statement returns syntax error
[ "", "mysql", "sql", "syntax-error", "" ]
How do I not include people with a birth date older than 5 years from today's date? Here is what I have, I just dont know how to put it in my where clause. ``` SELECT firstname, lastname, age, gender, birthdate FROM Person WHERE ... ... ... ```
I would use: ``` dateadd(year,-5, getdate()) >= birthdate ```
``` datediff(year,yourdate,getdate()) > 5 ```
sql where clause issue with date older than 5 years
[ "", "sql", "sql-server", "t-sql", "" ]
I have a set of data with a `DateTime`, say `CalculatedOn` what I would like is to get start at the current date `getdate()` and get an `x` amount of records from before the current date, and the same amount from after. If `x = 50` then 50 prior to now and 50 in front of now. I was thinking `rownumber()` would be perf...
You can use two CTE's, one for past and one for future dates, then use `ROW_NUMBER` with `ASC` and `DESC`, multiply before now with `-1` and concat all: ``` WITH dataBefore AS ( SELECT d.*, rn = (-1) * row_Number() over (Order By CalculatedOn DESC) FROM dbo.TableName d WHERE CalculatedOn < GetDate() ) , da...
If you want to get 50 rows before and after, perhaps this will do what you want: ``` with cte1 as ( select top 50 t.* from table t where CalculatedDate <= getdate() order by CalculatedDate desc ), cte2 as ( select top 50 t.* from table t where CalculatedDate > getdat...
How to get a negative rownumber in sql server
[ "", "sql", "sql-server", "t-sql", "row-number", "windowing", "" ]
How can I represent the following table in database efficiently, assuming that the number of rows and cols is more the several hundreds (I think creating database with 100 fields is not a good idea:)) ![enter image description here](https://i.stack.imgur.com/RKy3v.jpg) I'm using Ruby on Rails/SQLite.
What you have here is a classical de-normalisation task. And the classical approach (not knowing your read-write patterns or other needs) is to make three tables: ``` ID | Name --------- 1 | Gothamist 2 | GigaOm 3 | Quick Online Tips ID | Name ---------- 1 | China 2 | Kids 3 | Music 4 | Yahoo ID1 | ID2 | Valu...
Your data structure is a bipartite non-directional weighted graph. If you can use a graph database, that would be a good fit.
Save two dimensional table to database
[ "", "sql", "ruby-on-rails", "ruby", "database", "sqlite", "" ]
I have a column which is varchar data type.Some sample values are like ``` abc 56 def 34 ghi jkl mno 78 ``` I wanted to get the numeric values only, like ``` 56 34 78 ``` Thanks in advance.
If you're on TD14 you can simply use a Regular Expression: ``` REGEXP_SUBSTR(col, '[0-9]+') ``` Before you might have the OTRANSLATE UDF, there's an old trick to remove any character but a list of wanted ones: ``` OTRANSLATE(col,OTRANSLATE(col, '0123456789',''),'') ```
``` SEL OTRANSLATE('abc 56 def', 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()', '') ``` or column data = 'abc 56 def' '34 ghi' 'jkl mno 78' ``` SEL columnname,OTRANSLATE(columnname, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()', '') FROM TableA; ```
Extracting numeric value in teradata
[ "", "sql", "teradata", "" ]
I have a table in a DB2 database containing customer information that I need to retrieve along with a count of how many times a specific column in the table is duplicated. Here is an example of the data. ``` CUSTOMERID | CUSTOMERGROUP | PRODUCTID | PRODUCTNAME | ALERTNAME | ALERTLEVEL | XXX | YYY | ZZZ 12345 AB...
You can do what you want with analytic functions: ``` SELECT customerID, customerGroup, ProductID, ProductName, AlertName, AlertCount, AlertLevel, more data.... FROM (SELECT t.*, COUNT(*) OVER (PARTITION BY AlertName) as AlertCount, ROW_NUMBER() OVER (PARTITION BY AlertName ORDER BY cu...
You can compute counts in separate query and then join it to the original query: ``` SELECT customerID, customerGroup, ProductID, ProductName, AlertName, t2.alert_count as AlertName, AlertLevel, more data.... FROM TABLE t1 JOIN ( SELECT customerid, customergroup, count(AlertName) alert_count FROM ta...
DB2 SELECT statement using COUNT and GROUP BY
[ "", "sql", "database", "db2", "" ]
I have 4 tables: \*\*[PERSON] ``` ID_Person Person_NAME** 1 First name 1 Last name 1 2 First name 2 Last name 2 3 First name 3 Last name 3 4 First name 4 Last name 4 5 First name 5 Last name 5 6 First name 6 Last name 6 **[mobile_number] ID Mobile_Number OPERATOR** 1 797900...
Try this -- same base query, plus a WHERE-clause subquery that filters out Persons who did not have calls from multiple years. ``` -- Person, phone number, message, and year, for persons who had messages in multiple years Select a.Person_Name, Mobile_Nr, message, year(Date) as Years from PERSON a inner join USER_MO...
Try something like this: ``` Select a.Person_Name, Mobile_Nr, message, year(D.Date) as Years from PERSON a inner join USER_MOBILE b on a.ID_PERSON=b.ID_USER inner join MOBILE_NUMBER c on b.ID_MOBILE=C.ID inner join MESSAGE_ID d on c.ID=d.ID_Mobile WHERE EXISTS( SELECT 1 FROM PERSON a1 ...
How to select rows that have more than 1 distinct values in SQL?
[ "", "sql", "" ]
I have the following postgresql syntax that returns values WHERE session\_date matches $date\_string Problem is that sometimes the $date\_string will not be available in the table, so I am looking to return the closest date to the $date\_string ``` $date_string = '2014-04-25'; SELECT year, session_date FROM calendar...
If you want the closest date before, do it this way: ``` SELECT year, session_date FROM calendar_dates WHERE session_date < '$date_string' ORDER BY session_date DESC LIMIT 1; ``` The closest date after uses similar logic. For the closest on either side: ``` SELECT year, session_date FROM calendar_dates ORDER BY abs...
# Using [`btree_gist`](https://www.postgresql.org/docs/current/static/btree-gist.html) and knn Using this method you can find the nearest event with an index. ``` CREATE EXTENSION btree_gist; CREATE TABLE foo ( id serial, ts timestamp ); INSERT INTO foo (ts) VALUES ('2017-06-02 03:09'), ('2016-06-02 03:09'), (...
PostgreSQL return exact or closest date to queried date
[ "", "sql", "postgresql", "" ]
**The content of this question is long so please bear with me.** I am looking for a way to filter a view from a stored procedure where the stored procedure has a bunch of parameters that can be nullable. Here are the options I've identified for doing this, along with any pros and cons I can see for them: ## Option 1...
I think you're over-complicating this. A standard way to deal with this type of situation is: ``` SELECT <columns> FROM MyView WHERE (@Param1 IS NULL OR ColA = @Param1) AND (@Param2 IS NULL OR ColB = @Param2) ... ``` There's no need for complicated logic here involving deleting from temporary result sets.
Plain TSQL with option recompile should be included in this list as well. It isn't right for every situation, but it's where I start from. ``` WHERE (@Param1 IS NULL OR @Param1 = col1) AND (@Param2 IS NULL OR @Param2 = col2) OPTION (RECOMPILE) ``` Recompiling will allow for an optimized query based on the speci...
How can I optimally filter a view from a stored procedure that accepts lots of nullable parameters?
[ "", "sql", "sql-server", "stored-procedures", "" ]
Do I need to issue commit command after running the stored function with select query?
commit means "save the changes" select statement does not change any data. changing data can be done by Insert, update, delete statements (Data Manipulation language) .
Yes, you do, in some cases (please read the discussion in the link below). The rule is: Always commit if you made change in DB (after DML commands), even with SELECT statement. Use the COMMIT statement to end your current transaction and make permanent all changes performed in the transaction. Read more: [oracle - wh...
Commit statement after Stored Function with select query
[ "", "sql", "oracle", "" ]
I have a primary key in my table something like "abc.001 to abc.100" and "xyz.1000 to xyz.2000". So, there is a range of variable numbers but constant String value. Now, if I wanted to find the particular range between abc.011 to abc.020 then what query should I supposed to use. I tried using the between clause but it ...
I found the answer using the regexp\_like. I made the query something like this, `select * from orders where REGEXP_LIKE (order_id, '^abc.(\d{1}|\d{2})$');` This query returns the results from 0-99 however if I need the result until 0-100 then I tried to use the third criteria `select * from orders where REGEXP_...
Will the string bit be constant? If so you can substring (SUBSTR()) the primary key to just take the number part, to\_number it and then filter by that. e.g. ``` select * from table where to_number(substr(col,5,3)) between 1 and 100 ``` If you want to use the characters for comparison as well you'll have to do somet...
How to find the range of values using the SQL query where the string is constant and the number is variable
[ "", "sql", "oracle11g", "" ]
I have a table in SQL, and it looks like this: ``` FOO BAR DateTime --- --- ------ FOO1 BAR1 4/25/2014 FOO2 BAR2 4/24/2014 ........ ``` to any n number of records in the above format. I am trying to write a query that first returns all records that meet two property conditions, say all the records where ...
Well if I understood the request correctly (and it is SQL Server) it would be something like this: ``` SELECT TOP 1 FOO, BAR, DateTime FROM Table WHERE FOO='FOO1' AND BAR='BAR1' ORDER BY DateTime DESC ``` WHERE condition limits the set, ORDER BY sorts the set in descending order by date and TOP 1 selects the most re...
``` SELECT FOO, BAR, Datetime FROM table WHERE Foo = 'FOO1' and Bar = 'BAR1' and DateTime = (SELECT MAX(DATETIME) from table WHERE Foo = 'FOO1' and Bar = 'BAR1') ``` Probably this...or any other answer...haha
T-SQL, Compare Record Property, Then Suusequent Date Compare
[ "", "mysql", "sql", "sql-server", "t-sql", "" ]
I have designed the following query ``` SELECT v.visitid, CASE WHEN vd.DocType = 1 THEN 'y' ELSE 'n' END as 'FinalReportAttached' ,CASE WHEN vd.DocType = 13 THEN 'y' ELSE 'n' END as 'InspectorReportAttached' ,CASE WHEN vd.DocType = 2 THEN 'y' ELSE 'n' END as 'Co-ordReportAttached' FROM Visits v INNER JOI...
You could try this: ``` SELECT v.visitid, CASE WHEN SUM(CASE WHEN vd.DocType = 1 THEN 1 ELSE 0 END)>0 THEN 'y' ELSE 'n' END as 'FinalReportAttached' ,CASE WHEN SUM(CASE WHEN vd.DocType = 13 THEN 1 ELSE 0 END)>0 THEN 'y' ELSE 'n' END as 'InspectorReportAttached' ,CASE WHEN SUM(CASE WHEN vd.DocType = 2 THEN...
To get one row, use aggregation functions: ``` SELECT vd.visitid, MAX(CASE WHEN vd.DocType = 1 THEN 'y' ELSE 'n' END) as FinalReportAttached, MAX(CASE WHEN vd.DocType = 13 THEN 'y' ELSE 'n' END) as InspectorReportAttached, MAX(CASE WHEN vd.DocType = 2 THEN 'y' ELSE 'n' END) as [Co-ordReportAttache...
How to combine rows based on field value
[ "", "sql", "sql-server-2008", "" ]
I want to copy/update data from Table A to Table B. Table B has some more additional columns. I have tried the following options. ``` 1) `REPLACE INTO `B` (SHOW FIELDS FROM 'A') SELECT * FROM `A 2) `REPLACE INTO `B` (SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`='t...
Actually there is a way ``` SET @query = CONCAT('REPLACE INTO `A` (', (SELECT GROUP_CONCAT(CONCAT('`',column_name, '`')) FROM information_schema.columns WHERE `TABLE_SCHEMA`='test1' AND `table_name` = 'A' AND column_name IN (SELECT column_name...
You can't do this dynamically in mysql like you are trying to do. MySQL expects your list of column names to be provided directly, not from a subquery. If you want to do this dynamically you'll have to step back upstream to whatever language you are using to interact with MySQL such as PHP or Java.
How to select column name in select statement
[ "", "mysql", "sql", "" ]
I have data like this : ``` ID VERSION SEQUENCE -------------- -------------- --------------- 01-001 01 001 01-002 01 002 02-002 02 002 ``` And I want to select only the higher version for each sequence in order ...
So filter to include only those rows where the version ***is*** the highest version in it's sequence ``` Select id, version, sequence From DataTable dt where version = (Select Max(version) From DataTable where Sequence = dt.Sequence) ```
using a Common Table Expression you could: ``` with HighestSequence(ID,MaxSequence) as ( select id, max(Sequence) from table group by ID ) select t.* from table t inner join HighestSequence hs on t.id = hs.id and t.sequence = hs.sequence ```
SQL, Group by one column
[ "", "sql", "oracle", "group-by", "" ]
So this generates Hours, Projects, Descriptions and Client names. But the problem is that all the fields need to be grouped together if they're the same instead of displayed multiple times. I searched around and using the SUM function might work. Here's the SQL statement: ``` SELECT h.hoursworked AS Hours, p...
You'll need to add a `GROUP BY` clause. Try the following: ``` SELECT SUM(h.hoursworked) AS TotalHours , p.projectname AS DocketName , p.description AS Description , p.archive AS Archived , c.clientname AS Clients FROM hours h JOIN projects p ON h...
Grouping can be done but if there are different combinations then grouping will only work to some extent. Try this: Assuming all fields are `Varchar` and except `hours` ``` SELECT p.projectname AS DocketName, p.description AS Description, p.archive AS Archived, c.clientname AS Clients,Sum(h.hoursworked) AS Hours ...
Grouping Project Names and Total Hours together SQL JOIN ONs
[ "", "sql", "database", "sum", "" ]
Using MS-SQL server 2008 r2 I have a table that I'm trying to count the number of groups of duplicates in: ``` id adId 1 a 2 a 3 b 4 c 5 c 6 c ``` I want to find the total number of records that have duplicates in column adId. The result I want here is 2 (as a and c have both been duplicated) These do not work...
For getting the records which have duplicates: ``` SELECT adId,COUNT(adId) AS TotalRecords FROM oc_cal_sc GROUP BY adId HAVING COUNT(adId) > 1 ``` With the example you have given, result would be: ``` adId TotalRecords a 2 c 3 ``` **EDIT:** For getting the **number of records** which have duplicate...
``` SELECT COUNT(1) TotalRecords FROM ( SELECT adId, COUNT(1) FROM oc_cal_sc GROUP BY adId HAVING COUNT(1) > 1 ) x ```
SELECT COUNT(*) DISTINCT - Finding the total number of times any groups of duplicates appear in a table
[ "", "sql", "sql-server", "" ]
Currently to reference multiple databases from the same query, we do it like so ``` DatabaseName.Tablename.Column ``` I was wondering if you can actually reference the database name from a field. The reason for this is sometimes there are hundreds of these references and when creating new instances for customers the ...
You cannot use syntax like in your question. What you could do is to use dynamic SQL and build the query dynamically based on the database name. For example: ``` declare @sql nvarchar(max) = (SELECT DatabaseName FROM ConfigurationTable) set @sql = N'SELECT ColumnName FROM ' + QUOTENAME(@sql) + N'..TableName' exec sp...
You seem to have an architecture where each customer has a separate database. Why are you including the database name in the query? Just add `use DatabaseName` and run the query as you would want. Such an architecture normally copies views, stored procedures, functions, tables and whatever else into each database. If...
Get database name from field?
[ "", "sql", "sql-server-2012", "" ]
Let's say I have the following tables: ``` Batch Items ---+----- ---+----------+-------- id | size id | batch_id | quality ---+----- ---+----------+-------- 1 | 10 1 | 1 | 9 2 | 2 2 | 1 | 10 3 | 2 | 1 4 | 2 | 2 5 | 2 ...
``` SELECT b.id AS batch_id , count(i.quality < 4 OR NULL) AS broken_item_count FROM batch b LEFT JOIN ( SELECT batch_id, quality , row_number() OVER (PARTITION BY batch_id ORDER BY id DESC) AS rn FROM items ) i ON i.batch_id = b.id AND i.rn <= b.size GROUP BY 1 ORDER BY 1; ``` ...
[SQL Fiddle](http://sqlfiddle.com/#!15/ddbc1/1) ``` select b.id as batch_id, count(quality <= 3 or null) as broken_item_count from batch b inner join ( select id, quality, batch_id, row_number() over (partition by batch_id order by id) as rn from items ) i on...
Join a dynamic number of rows in postgres
[ "", "sql", "postgresql", "join", "" ]
The question can be specific to SQL server. When I write a query such as : ``` SELECT * FROM IndustryData WHERE Date='20131231' AND ReportTypeID = CASE WHEN (fnQuarterDate('20131231')='20131231') THEN 1 WHEN (fnQuarterDate('20131231')!='20131231') THEN 4 END; ``` **D...
I think the solution may in theory help you increase the performance, but it also depends on what the scalar function actually does. I think that in this case (my guess is formatting the date to last day in the quarter) would really be negligible. You may want to read this page with suggested workarounds: <http://con...
It depends. See [User-Defined Functions](http://technet.microsoft.com/en-us/library/ms191007.aspx): > The number of times that a function specified in a query is actually executed can vary between execution plans built by the optimizer. An example is a function invoked by a subquery in a WHERE clause. The number of ti...
WHERE-CASE clause Subquery Performance
[ "", "sql", "sql-server-2012", "subquery", "case", "database-performance", "" ]
How would I go about updating a table by using another table so it puts in the new data and if it doesnt match on an id it adds the new id and the data with it. My original table i much bigger than the new table that will update it. and the new table has a few ids that aren't in the old table but need to be added. for...
You can use MERGE statement to put this UPSERT operation in one statement but there are issues with merge statement I would split it into two Statements, UPDATE and INSERT **UPDATE** ``` UPDATE O SET O.Initials = N.Initials FROM Original_Table O INNER JOIN New_Table N ON O.ID = N.ID ``` **INSERT** ``` INSERT IN...
You need to use the MERGE statement for this: ``` MERGE original_table AS Target USING updated_table as Source ON original_table.id = updated_table.id WHEN MATCHED THEN UPDATE SET Target.Initials = Source.Initials WHEN NOT MATCHED THEN INSERT(id, Initials) VALUES(Source.id, Source.Initials); ``` You have not specifi...
update a table from another table and add new values
[ "", "sql", "sql-server", "" ]
This is in Oracle database. Say I have the following table A: ``` column1 column2 id1 a id2 a id3 a id4 b id5 b id6 c ``` So what I want the sql does is: First count there's three As and two bs and one c, then based on the counts return me the smallest number of these counts, in t...
Try this: ``` SELECT MIN(Count) as MinVal FROM (SELECT column2,COUNT(column2) as Count FROM TableA GROUP BY column2) T ``` **Explanation:** Inner query select the counts of `column2` for each value of `column2` in the table. Then with the outer query, the minimum count is selected.
In Oracle you can do this directly; count per group and use MIN on the results to get back one row with the desired value. ``` select min(count(*)) from tablea group by column1; ```
SQL - combination of MIN and COUNT
[ "", "sql", "oracle", "aggregate-functions", "oracle-sqldeveloper", "" ]
I am using Oracle SQL (TeraTerm), and I am trying to join specific information from two tables CONSULTANT, and PROJECT\_CONSULTANT, and I need to retrieve only the employees who worked over 40 hours. Here are the tables Project Consultant ``` PROJECT_ID CONSULTANT_ID NUMBER_HOURS --------------- ------...
You don't use `and` in the `select` clause: ``` select c.Consultant_ID, c.Name, c.Zip, pc.Number_Hours from Consultant c Inner Join project_consultant pc on c.Consultant_ID = pc.Consultant_ID where pc.number_Hours > 40; ``` You also need a table alias in the `select` clause to be clear what table `Consulta...
You can't use **and** in Select Clause Try this ``` SELECT C.Consultant_ID, C.Name, C.ip, PC.Number_Hours FROM Consultant C INNER Join project_consultant PC ON C.Consultant_ID=PC.Consultant_ID WHERE PC.number_Hours > 40; ```
Having trouble creating join looking for specific data
[ "", "sql", "join", "inner-join", "" ]
I'm storing tweets, twitter users, and categorising twitter users in groups. I have the following 4 tables tweets: ``` tweet_id | user_id | created ------------------------------- 23452345 | 2345 | 2013-08-12 23456094 | 1234 | 2014-03-24 23097777 | 1234 | 2014-04-12 23948798 | 9999 | 2013-09-22 ``` twit...
``` SELECT tu.screen_name as Handle ,MIN(tw.created_at) as Earliest FROM twitter_users tu LEFT JOIN tweets tw ON tu.user_id = tw.user_id LEFT JOIN twitter_social ts ON ts.user_id = tu.user_id LEFT JOIN social_categories cs ON ts.social_id = cs.social_id WHERE cs.category_id=3 GROUP BY tu.screen_name ORD...
If you want the earliest, it's not ASC (ascending) ``` ORDER BY Earliest ASC ``` It should be DESC (descending) ``` ORDER BY Earliest DESC ```
SQL Limit & Order By across joins
[ "", "mysql", "sql", "join", "" ]
Can I do like this ``` select * from tableA JOIN tableB ON tableA.id=tableB.id where tableB.someId = select id from otherTable where anotherId = 1 ``` I have 2 where, possible?
You can use `=` when the subquery returns only 1 value. When subquery returns more than 1 value, you will have to use `IN` or `EXISTS`: 1. Using `IN`: ``` select * from tableA JOIN tableB ON tableA.id=tableB.id where tableB.someId IN (select id from otherTable ...
You could use the [`IN` Clause](https://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_in): ``` select * from tableA JOIN tableB ON tableA.id = tableB.id where tableB.someId IN (select id from otherTable where anotherId = 1) ``` You could also us...
SQL where equal to expression
[ "", "mysql", "sql", "" ]
I have a table with close to 3 million rows that has 5-10 updates/inserts every second. Each row is assigned a category, and I want to group by the category to count the total number of rows for each category. ``` Select CategoryId , COUNT(*) as TotalRows FROM Table1 WHERE SaleTypeId = 2 AND CategoryId > 1 GR...
I ended up running this as a nightly aggregate job and storing the result in an aggregate table. It doesn't provide up to date results (which, after deliberation, we can live with) nor is the nightly query any faster, but reading from the aggregate table is a lot faster.
Reverse the columns order in the nonclustered index, like this: ``` CREATE NONCLUSTERED INDEX [Index1] ON [dbo].[Table1] ( [CategoryId] ASC, [SaleTypeId] ASC ) ```
SQL Group By with Count is slow
[ "", "sql", "sql-server", "performance", "" ]
``` CREATE TABLE Personn ( pid INTEGER PRIMARY KEY, iname VARCHAR(50), gender CHAR(1), dateOfBirth DATE, CONSTRAINT person_gender CHECK (Gender BETWEEN 'f' AND 'm') ); INSERT INTO Personn VALUES ('1005','john', 'M', 24/apr/1999 ); ``` ``` Error starting at line : 18 in command - INSERT INTO Pe...
You should change your insert statement. Date values should be given as string literals. So change ``` INSERT INTO Personn VALUES ('1005','john', 'M', 24/apr/1999 ); ``` to ``` INSERT INTO Personn VALUES (1005, 'john', 'M', '24/apr/1999'); ``` Since your primary key is an integer, you can leave out the single quot...
``` INSERT INTO Personn VALUES ('1005','john', 'm', to_date('24/apr/1999', 'dd/mon/yyyy') ); ```
oracle error: "column not allowed here"
[ "", "sql", "oracle", "" ]
I need to select some columns from a table as XML with namespaces included in them along with other columns as is. For example, I have a following table layout: ``` ID C1 X1C1 X1C2 X2C3 1 A 1 2 3 ``` What the query should return is: ``` ID C1 XmlData 1 A <xmldata1> 2 A <xmldata2> ``` Where...
I used this solution: [TSQL for xml add schema attribute to root node](https://stackoverflow.com/questions/12726426/tsql-for-xml-add-schema-attribute-to-root-node) Basically, I did not put the namespace in the beginning but after generating the required xml structure I casted the xml to `nvarchar(max)` and replaced th...
you need to include WITH xmlnamespaces , example: ``` ;with xmlnamespaces('w3.org/2001/XMLSchema' as xsd, 'w3.org/2001/XMLSchema-instance' as xsi, 'microsoft.com/wsdl/types/' as mst) select ID, C1, (select (SELECT 'C1' "@name",t.C1 as 'value'FOR XML PATH('Property'), type), (SELECT 'C2' "@name",t.C2 as 'value'FOR XML...
Selecting columns as XML with namespace
[ "", "sql", "xml", "t-sql", "sql-server-2008-r2", "" ]
If I have to work with `localdb`, do we need to install it separately? I have SQL Server 2008 R2 Management Studio installed, SQL Server 2012 installed, .net 4.0.2 update installed. But I don't see localdb in the PC yet.
From [MSDN](http://msdn.microsoft.com/ru-ru/library/hh510202.aspx) > The primary method of installing LocalDB is by using the > SqlLocalDB.msi program. LocalDB is an option when installing any SKU > of SQL Server 2012 Express. **Select LocalDB on the Feature Selection > page during installation of SQL Server Express**...
If you downloaded **SqlLocalDB.msi** You can use silent install. ``` msiexec /i SqlLocalDB.msi /qn IACCEPTSQLLOCALDBLICENSETERMS=YES ``` Remember about administrative rights for installation !
How to install localdb separately?
[ "", "sql", "sql-server", "localdb", "" ]
i am using the below query to return rowcount for paging, it works fine but take very long to return, because all of the table have millions of records. currently its taking 7 sec to return rowcount, can anyone help me in this to return it fast. i have also tried same query with #table and @table both are slow. query ...
I'd say to look at the indexes, but it probably won't help much, because a) you probably did it already, and b) you can get no seeks with this kind of a query, only scans. The idea is to get rid of these ORs and allow the optimizer to produce a sound plan. There are two options. Don't know which version of SQL Serve...
This is hard to answer because with huge bulk of data many things could happen. In term of join, this should perform well. If this query is just here to perform a count, then I can just suggest you to do it directly `SELECT count('x')` without `CTE` and without `(nolock)`. ``` SELECT @rowcount = count('x') as rc FROM...
optimized way to get row count from a query contains large amount of data
[ "", "sql", "sql-server", "t-sql", "rowcount", "" ]
I have three tables called Hours, Projects and Clients. I'm somewhat experienced with SQL statements and can't seem to get my head around why this isn't working. Projects and Hours tables both share a foreign key called projectid and Projects and Clients both share a foreign key called clientid. Here's my query so fa...
You are mixing implicit joins and explicit joins. A simple rule: don't use commas in `from` clauses. ``` SELECT h.hoursworked, p.projectname, p.description, p.archive, c.clientname FROM hours h join projects p on h.projectid = p.projectid join clients c ON p.clientid = c.clientid WHERE p.archive = ...
You need to prepend the table name to the field/column, not put it at the end, and usually you would use `AS` for field/column aliases, not for table aliases. Also, I would name the tables in the `JOIN`s, not separated by commas in the `FROM` statement. This is how it should look: ``` SELECT h.hoursworked, p...
SQL JOIN ON issue with aliases or not using aliases
[ "", "sql", "alias", "join", "" ]
``` table 1 _id sub_id 1 32 2 34 3 42 4 44 5 47 6 50 ``` . ``` table 2 _id sub_id 1 34 2 42 ``` # i want result ``` _id sub_id count 1 32 2 2 34 2 3 42 1 4 44 0 ...
Try this query ``` SELECT _id ,sub_id ,( SELECT count(*) FROM table2 t2 WHERE t2.sub_id >= t1.sub_id ) count FROM table1 t1 ```
This is what you want : ``` SELECT t1._id ,t1.sub_id ,count(t2._id) as count FROM table1 t1 left join table2 t2 on t2.sub_id >= t1.sub_id GROUP BY t1._id ,t1.sub_id ``` **Here is the [SQLfiddle demo](http://www.sqlfiddle.com/#!7/791ff/6)**
sql outer join count above rows
[ "", "sql", "database", "sqlite", "join", "" ]
I have multiple tables which have multiple number of columns and field names. I want to select \* data from these tables where there is a specific condition(then insert the data into a different database). For example, if I run below queries separately, each of them returns a different number of rows where number of co...
I think you're going wrong way, if you axport a union, than you will have problem importing that. Instead try to merge files, or export three tables separatly into one file, for example using tool **MYSQLDUMP** like this: ``` mysqldump -u root -pyour_password your_database table1 >> /tmp/mysql_dump.sql mysqldump -u ro...
You can use something like this: ``` Select ID as ID, '' as Name, '' as Something From table1 where id>=500; union all Select ID as ID, Name as Name, '' as Something from table2 where id>=200; union all Select ID as ID, '' as Name, Something as Something ...
Combine multiple select * queries for tables with a different number of columns/names for export into a different database
[ "", "mysql", "sql", "" ]
I have two tables, ``` ID NAME ------------------- 12 Jon Doe 4 Jane Doe 9 Sam Doe ``` AND ``` MemID Cat# DateChkOut DateDue DateRet 4 T 430.98 1956 15-Mar-2011 14-Jun-2011 31-May-2011 12 B 125.2 2013 15-Mar-2011 14-Jun-2011 4 T 430.98 1956 27-Dec-...
You need to use a `LEFT JOIN` in this case. Try the following: ``` SELECT M.Name FROM MembersTable M LEFT JOIN CheckoutTable C On C.MemId = M.ID WHERE C.MemId IS NULL ``` Edit: `LEFT JOIN` works in this situation because it joins the two tables on a common key - in this case the `MemId`. Since this is a `LEFT JOIN`...
``` SELECT name FROM member WHERE id NOT IN (SELECT MemID FROM checkout) ``` I think it should do the job
SELECT query on multiple table
[ "", "mysql", "sql", "database", "" ]
I have two tables. TableA contains EventID, Date, **Manager** TableB contains **Manager**, Department, Date Started, Date Ended. In TableB managers often switch departments so the seeing entries like Manager1, Tulsa, 1-1-2012, 6-1-2012 Manager1, Iowa City, 6-2-2012, 12-31-2012 Is to be expected. I want to as...
You need to join on an FK and use BETWEEN in the WHERE clause SELECT A.EventID, B.Department FROM TableA A INNER JOIN TableB B ON A.Manager = B.Manager WHERE A.Date BETWEEN B.DateStarted AND B.DateEnded
``` Select Max(EventID),Date, Manager From TableA Group By Date, Manager ```
Join 2 tables based on the date of an event happening in table 1, being between start and end dates of table 2
[ "", "sql", "sql-server", "" ]
In the vb script I have a select statement I am trying to pass a string value with an undetermined length to a SQL in operator the below code works but allows for SQL injection. I am looking for a way to use the ADO createParameter method. I believe the different ways I have tried are getting caught up in my data type...
Classic ASP does not have good support for this. You need to fall back to one of the alternatives discussed here: > <http://www.sommarskog.se/arrays-in-sql-2005.html> That article is kind of long, but in a good way: it's considered by many to be the standard work on this subject. It also just so happens that my pref...
What does your `addParameter()` function do? I don't see that anywhere in your code. You should be able to create and add your string param like so: ``` With dbCommand .Parameters.Append .CreateParameter(, vbString, , Len(studentid), studentid) End With ``` (Small hack here. `vbString` has the same value as `adB...
Pass a vbscript String list to a SQL "in"operator
[ "", "sql", "vbscript", "asp-classic", "" ]
I have an insert command with values are calculated based on currency value on another table. Sql code is something like ``` INSERT INTO table1 (column1,column2,column3,column4,column5,column6) VALUES ( value1 * (SELECT currency FROM currency_table WHERE date=date1), value2 * (SELECT currency FROM currency_table WHERE...
Insert is ok with what Guneli has provided. Syntactically, the query is incorrect. Use ``` INSERT INTO table1 (column1,column2,column3,column4,column5,column6) SELECT value1*currency1, value2*currency1, value3*currency1, value4*currency2, value5*currency2, value6*currency2 FROM (select (select currency from cur...
Try this for INSERT: ``` INSERT INTO table1 (column1,column2,column3) VALUES SELECT value1*currency, value2*currency, value3*currency FROM currency_table; ```
Using Same Value from Select Statement in an Insert Query
[ "", "sql", "sql-server", "optimization", "insert", "" ]
What would be the best database design for this: I have a list of products and a list of clients. Each product has assigned 9 different prices Each client has assigned one of those prices for every product. IT would be something like this: ``` PRODUCTS id name price1 price2 price3 price4 price5 price6 price7 price8 ...
Some information is missing. First, you need a product table ``` Product ------- Product ID Product Description ... ``` Next, you need a product price table ``` ProductPrice ------------ ProductPrice ID Product ID Price ``` Next, you have a client table ``` Client ------ Client ID Client Name ... ``` Finally, yo...
This makes no sense. Prices are examples of diachronic properties: meaning they represent a value *at a given time*. What you want is a price table with 2 dates in it. ``` Prices productID:long effectiveDate:Date endDate:Date ``` Then when you want the current price, you have two choices. The most common one i...
Database design for products with multiple prices
[ "", "sql", "database", "" ]
I have a query like the below showed. ``` select * from tbl a WHERE a.device_cat = (CASE (SELECT :VIEW1 FROM DUAL WHERE :VIEW1 IN (SELECT DISTINCT version ...
You cannot compare to null like this: ``` a.device_cat =null ``` Try this: ``` select * from tbl a WHERE nvl(a.device_cat, 0) = nvl((CASE (SELECT :VIEW1 FROM DUAL WHERE :VIEW1 IN (SELECT DIST...
You cannot compare `null` to `null` like that. It is like: ``` undefined = undefined ``` Which is not true... Something you don't know isn't something you don't know. At least, in SQL. You can use `coalesce` to circumvent this: ``` WHERE coalesce(a.device_cat, '###') = (CASE (SELECT coalesce(...
Why the case when doesn't work in oracle
[ "", "sql", "oracle", "" ]
Okay, so I have kind of a weird issue... the dates in the table have been entered in as string values `MMDDYYYY` and I'm trying to have the displayed as `MM/DD/YYYY` in a report and only select the most recent date pertaining to an ID, because some ID's may have multiple dates. Example of my table: ``` ID | MyDat...
This question is for almost a year ago, nut probably someone can find it useful. You need to `CONVERT` your string to `DATE` format and use a `ROW_NUMBER` function to window your result set. **Create table** ``` DECLARE @tbl TABLE(Id INT, myDate VARCHAR(8)) ``` **Sample data** ``` INSERT @tbl SELECT 1 , '0130201...
Using a CONVERT like the following code snippet will work on any SQL Server regardless of language and/or locale configuration. ``` DECLARE @OldDate varchar(8); SELECT @OldDate = '04252012'; SELECT CONVERT(datetime, substring(@OldDate,5,4) + '-' + substring(@OldDate,1,2) + '-' + substring(@OldDate,3,2) + 'T00:00:00'...
Convert varchar MMDDYYYY to MM/DD/YYYY datetime and select the most recent date only
[ "", "sql", "sql-server", "datetime", "varchar", "" ]
I have a revision table like this: ``` id revision_id event_id ------------------------ 1 1 1 2 2 1 3 1 2 4 2 2 5 3 2 ``` I want to get last revision\_id for each distinct event\_id . I want MYSQL query to do so. Can any one guide me??
``` SELECT event_id, max(revision_id) FROM mytable GROUP BY event_id ``` See in **[SQLFiddle](http://sqlfiddle.com/#!2/6f2e4/1)**.
``` SELECT MAX(revision_id) , event_id FROM TABLE_NAME GROUP BY event_id ```
How can I get last revision_id of particular event_id?
[ "", "mysql", "sql", "" ]
I have 3 tables: `Student`, `Address` and `StudentAddress`. `Student` stores all the students, address stores all the address details while `StudentAddress` resolves many to many relationship between `Student` and `Address`. This table stores details of student who have lived in more than one addresses. I am trying t...
I would prefer `join` since it gives your more possibilities to use the result for your second query. To help you narrowing down the actual result set, try something like this: ``` select a.MemberID , a.AddressID , COUNT(a.AddressID) as countAddress from MemberAddress a group by a.MemberID , a.Ad...
To filter them: ``` select a.MemberID,a.AddressID,COUNT(a.AddressID) as count from MemberAddress a group by a.MemberID HAVING COUNT(a.AddressID) > 3 ```
Use Join or Sub Query?
[ "", "mysql", "sql", "" ]
Imagine that I have three entities (`EntityA`, `EntityB`, `EntityC`) that can have some `images`. So there are two ways: 1. Make an `image` table for each entity. It means that `EntityA` has a `image` table named `AImages` and similarly for `EntityB` and `EntityC`. This method is more intelligent but has more table...
> Have an image table and another table name EntityType that goes between. This will require you to enforce the referential integrity manually, which is [trickier than it looks](https://stackoverflow.com/a/20873843/533120). So either: * for each 1:N relationship, have a separate "N" table for each "1" table (as you ...
The raght way is to store images in `varbinary(max)` columns in their respective tables, and not to separate them. SQL Server will take care of phisically storing them in an efficient, off-row, manner. Depending on which version of SQL Server is used and the size of the LOBs, you might consider `FILESTREAM` or `FILETA...
Which one is correct and optimized in sql?
[ "", "sql", "sql-server", "database-design", "relational-database", "query-optimization", "" ]
How does one create a custom aggregate in SQL Server 2012? I'm trying to get a median aggregate. Something like: ``` ;with cte as ( select top 50 percent val from tbl order by val desc ) select top 1 from cte ```
You should just use the built-in function, `percentile_cont()` or `percentil_disc()` (see [here](http://technet.microsoft.com/en-us/library/hh231473.aspx)), depending on how you define the median for an even number of records. I think the following does what you want: ``` select percentile_cont(0.5) within group (ord...
There is an interesting article that examines a number of different approaches to this problem, and also provides a performance analysis. It claims that percentile\_cont() is the worst-performing, while this is the best: ``` DECLARE @c BIGINT = (SELECT COUNT(*) FROM dbo.EvenRows); SELECT AVG(1.0 * val) FROM ( SEL...
Custom aggregate functions
[ "", "sql", "sql-server", "t-sql", "sql-server-2012", "" ]
I have searched similar problems here on stackoverflow but I could not understand how to make this work, what I'm trying to do... So, I want to get last 7 days transactions from database and get total sales amount and also include empty rows if there is no data for some day. What I have so far: <http://sqlfiddle.com/...
Simply put together a subquery with the dates you want and use `left outer join`: ``` select d.thedate, coalesce(SUM(amount), 0) AS amount from (select date('2014-04-25') as thedate union all select date('2014-04-24') union all select date('2014-04-23') union all select date('2014-04-22') union all ...
This is not easy. I took help from this thread [generate days from date range](https://stackoverflow.com/questions/2157282/generate-days-from-date-range) and combined it with your query. So the idea was to get the list of dates from last 7 days then left join these dates with a static amount 0 to the query you have an...
MySql Single Table, Select last 7 days and include empty rows
[ "", "mysql", "sql", "" ]
I appreciate any help. I am creating a database query and I would like to add something. I created two tables(users&videos) and I would like to insert video\_id into users table but however I would like one user to have multiple videos. For example, user\_id 1 should have all three videos. Any help? `create table user...
I think in that case, you should normalize your table users, remove `video_id` from here and create one table to have `users to video mapping`, something like this: ``` create table user_videoes ( user_id int, video_id int); ``` By this approach, one user can have multiple videos and one video can belong to multiple ...
If a video can only belong to one user then you should do it the other way around, ie. the user\_id field is in the video table. That way one user can have many videos.
SQL query to add multiple values into an attribute
[ "", "mysql", "sql", "" ]
I have a table `A` with two columns that I want to append to another table `B`, how can I do that? They have the exact same rows. Software is `SQL Server 2012`. EDIT (attempted code from comment): ``` INSERT INTO B_table([Column 0], [Column 1]) SELECT [Column 0], [Column 1] FROM [dbo].[A] ; ```
The basic form is: ``` insert into tableB(col1, col2) select col1, col2 from tableA; ``` This may not work if, for instance, you have a unique constraint on the columns and the `insert` violates this constraint. This assumes that you actually want to add the rows to the table. If you just want to see the res...
Try this: ``` INSERT INTO tbl1 SELECT * FROM tbl2; ```
Append table to an existing one: SQL Server
[ "", "sql", "sql-server", "sql-server-2012", "" ]
I'm using EXISTS AND NOT EXISTS IN THE same query, but not getting any results. I'm looking for results where there is a particular position and sub position, but want to exclude items where that particular position exists, but the subposition is null. I'm a newbie, so I'm probably missing something here. Here is my qu...
`EXCEPT` is an alternative to `EXISTS` and `NOT EXISTS` in the same query: ``` SELECT * FROM Test T WHERE T.EventId IN ( SELECT EventId FROM Test T WHERE T.Position = 'ABC' AND T.SubPosition = 'DEF' EXCEPT SELECT EventId FROM Test T WHERE T.Position = 'ABC' AND T.SubPosition IS NULL ) ``` `EXC...
First, your English language description is unclear, and does not match the SQL. If you are looking ".. for results where there is a particular position and sub position, ..." Then you would simply write ``` SELECT * FROM dbo.table a Where Position = 'ABC' AND SubPosition = 'DEF' ``` and obviously, none of those...
MS SQL On Using WHERE EXISTS and WHERE NOT EXISTS
[ "", "sql", "sql-server", "" ]
How do I select rows in the past starting from yesterday in Oracle DB where a field like `created_date` is a `timestamp(6)`? I don't want to compare time, just date.
From the [Oracle documentation on SELECT](http://docs.oracle.com/cd/B19306_01/server.102/b14200/statements_10002.htm#i2105152) : ``` SELECT * FROM orders WHERE created_date < TO_DATE('2014-04-28', 'YYYY-MM-DD'); ``` I can pass this date format from my application, worked like a charm.
If you want exactly one day prior to the current time: ``` select * from table t where created_date < sysdate - 1; ``` If you want times before today: ``` select * from table t where created_date <= trunc(sysdate); ```
Select rows where day is less than today
[ "", "sql", "oracle", "" ]
I have to two table ``` table 1 table 2 id a b c id a 1 2 3 a 1 r 2 4 5 b 4 d 3 6 7 c 5 s 4 8 9 d 5 1 2 e 6 2 3 f ``` I want the table2 override table 1. below is the result I want ***I want to create a view table*** ``` table override id a b c 1 r 3 a 2 4 5 b 3 6 7 c...
``` UPDATE table1 INNER JOIN table2 ON table1.id=table2.id SET table1.a=table2.a ``` > if You want view try thiz one : ``` select t1.id,ifnull(t2.a,t1.a),t1.b from table_1 as t1 left join table_2 as t2 on t2.id=t1.id ``` **Creating View :** `CREATE VIEW tbl_vw AS SELECT t1.id,COALESCE(t2.a,t1.a),b,c FROM table_1 a...
Try this ``` UPDATE table1 t1 JOIN table2 ON t1.id = t2.id SET t1.a = t2.a ``` **Change for View:** ``` CREATE VIEW v AS SELECT t1.id,COALESCE(t2.a,t1.a),b,c FROM t1 ``` LEFT JOIN t2 ON t1.id = t2.id ; [SQL FIDDLE](http://sqlfiddle.com/#!2/d20d7/1)
How can I make one smaller table that overrides another bigger table?
[ "", "mysql", "sql", "" ]
I wanted to use `MOD` function in `SQL Server 2008R2` and followed this [link](http://technet.microsoft.com/en-us/library/ee634767(v=sql.105).aspx) but still got the message: > 'MOD' is not a recognized built-in function name. ``` DECLARE @m INT SET @m = MOD(321,11) SELECT @m ``` Error: > Msg 195, Level 15, State 1...
The `MOD` keyword only exists in the `DAX` language (tabular dimensional queries), not `TSQL` Use `%` instead. Ref: [Modulo](https://learn.microsoft.com/en-us/sql/t-sql/language-elements/modulo-transact-sql?view=sql-server-ver15)
In TSQL, the modulo is done with a percent sign. SELECT 38 % 5 would give you the modulo 3
'MOD' is not a recognized built-in function name
[ "", "sql", "sql-server-2008", "t-sql", "sql-server-2008-r2", "modulo", "" ]
Following command is used to insert data from one table into another. ``` insert into school_record (phone_id) select phone_id from students where name="abc" order by phone_id asc; ``` But what if I want to insert all the phone\_id values for the names "abc", "def", "ghi" and so on... That is how to insert d...
Use IN() - in brackets list all names which you need to insert ``` insert into school_record (phone_id) select phone_id from students where name in ('abc', 'def', 'ghi', ...) ; ``` Or if you need to insert all ``` insert into school_record (phone_id) select phone_id from students ; ```
If you want all the phone\_ids of the students table you can simply do: ``` insert into school_record (phone_id) select phone_id from students order by phone_id asc; ```
How do we insert "data from more than one records", from one table to another?
[ "", "mysql", "sql", "" ]
I have a table with 56 rows. Adding new rows starts from ID 59. What can I do to continue with ID 57?
This happens when you delete a column from the table or change the identity to be higher number. It is possible to reset the identity, but unless you have a very good reason to do that (good reason may be deleting most of the table contents), I won't recommend doing that. Some details of how to reseed the identity ca...
This is expected behaviour of `IDENTITY` columns. If you want consecutive numbers, you shouldn't be using them, because the identity value will increase every time you insert a new row, but will *not* decrease if you delete the last row, nor will it decrease if you begin a transaction, insert a new row, and then roll b...
Identity column skipping some values when adding a new row
[ "", "sql", "sql-server", "ssms", "" ]
This is an example of how my source xml looks ``` <Catalog xmlns="http://schemas.example.com/stuff/stuff"> <String Key="Name" Tag="22a41320-bb66-41a9-8806-760d13679c6c">Document Title 1</String> <String Key="Name" Tag="023463cf-9237-45b6-ac3f-621b9b09f609">Title for document 2</String> </Catalog> ``` I plan to lo...
I tried various methods to get around this * using with xmlnamespaces: no change * using explicitly defined namespaces: no change * using the same namespace as the parent: results in the default namespace being inserted into the Document node * deleting the empty namespace with modify/delete: would not remove the xmln...
Instead of looping and using `modify` with `INSERT` and `DELETE`, why just not replace the desire nodes: ``` declare @temp xml, @newNode xml; set @temp = cast( '<Catalog xmlns="http://schemas.example.com/stuff/stuff"> <String Key="Name" Tag="22a41320-bb66-41a9-8806-760d13679c6c">Document Title 1</String> <String ...
How to insert xml node in Sql Server without inserting empty namespace?
[ "", "sql", "sql-server", "xml", "xpath", "xml-dml", "" ]
I am trying to query the last time a file was imported from a SQL table "import", given a month string integer (Jan is '01', Feb is '02', March is '03'..). I have pasted my solution below but I was wondering if there is a more elegant way of doing so. ``` SELECT DISTINCT months.month_string, MAX(import.process_date) ...
I don't know if you will find this more "elegant", but here is a better way to write the query: ``` SELECT months.month_string, MAX(import.process_date) FROM (select '01' as month_string from dual union all select '02' as month_string from dual union all select '03' as month_string from dual union all ...
How about ``` WITH SUMMARY_DATA AS (SELECT CASE WHEN PROCESS_MONTH IN ('01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12') THEN PROCESS_MONTH ELSE NULL END AS SUMMARY_MONTH, PROCESS_DATE ...
SQL Query from list of strings
[ "", "sql", "oracle", "database-design", "" ]
I am having Two Sql Queries as Follows: 1st Query ``` SELECT TC.TCName, sum(BS.BLDOS) as BLDOS, sum(BS.CollectedAmount) as CollectedAmount, (0.35*sum(BS.BLDOS)) as TargetAmount FROM [Customer] C INNER JOIN [dbo].[BillingStatus] BS ON BS.CustomerID = C.CustomerID INNER JOIN [dbo].[TCDetails] TC ON TC.CustomerID = ...
Try this ``` SELECT * FROM ( SELECT TC.TCName, sum(BS.BLDOS) as BLDOS, sum(BS.CollectedAmount) as CollectedAmount, (0.35*sum(BS.BLDOS)) as TargetAmount FROM [Customer] C INNER JOIN [dbo].[BillingStatus] BS ON BS.CustomerID = C.CustomerID INNER JOIN [dbo].[TCDetails] TC ON TC.CustomerID = BS.CustomerID WHER...
In both queries you use TCDetails and group by TCName. You don't have to do this twice only to count non-null call dates. COUNT(CallDate) does that for you. I also removed the IN clause which doesn't add anthing to your query. So the query is simply: ``` SELECT TC.TCName, sum(BS.BLDOS) as BLDOS, sum(BS.Collec...
Merging two tables into one both the table having different where clause
[ "", "sql", "sql-server-2008", "" ]
I have created a calendar table that contains all the calendar dates of a year, incl. the corresponding quarter / week / month / day etc. information. The following Select gives me a specific date, here the 17th of March. How can I extend the below to check if this falls on a Saturday or Sunday (`weekDayCal = 7 or 1`)...
Assuming you have a `day_of_calendar` style `id` field, where every date is sequentially in order, then this works... ``` SELECT * FROM Calendar WHERE id = (SELECT id + CASE weekDayCal WHEN 7 THEN 2 WHEN 1 THEN 1 ELSE 0 END FROM Calendar WHERE (yearCal = 2014) AND (monthCal = 3) AND (da...
This fetches rows who fall on sunaday or saturday ``` SELECT * FROM Calender WHERE DATEPART(dw, CAST( CAST(monthCal as VARCHAR(2))+ '-'+ CAST(dayCal as VARCHAR(2))+'-'+ CAST(yearCal as VARCHAR(4)) AS DATETIME ...
SQL Server: check if certain date in calendar table falls on a weekend
[ "", "sql", "sql-server", "date", "stored-procedures", "calendar", "" ]
I have a table with the following data (paypal transactions): ``` txn_type | date | subscription_id ----------------+----------------------------+--------------------- subscr_signup | 2014-01-01 07:53:20 | S-XXX01 subscr_signup | 2014-01-05 10:37:26 | S-XXX02 subscr_si...
[SQL Fiddle](http://sqlfiddle.com/#!15/c862e/2). Subscription length for each subscription: ``` select subscription_id, coalesce(t2.date, current_timestamp) - t1.date as subscription_length from ( select * from t where txn_type = 'subscr_signup' ) t1 left join ( ...
I used a couple of common table expressions; you can take the pieces apart pretty easily to see what they do. One of the reasons this SQL is complicated is because you're storing column names as data. (subscr\_signup and subscr\_eot are actually column names, not data.) This is a SQL anti-pattern; expect it to cause y...
Get average interval between pairs of rows in a table
[ "", "sql", "postgresql", "aggregate-functions", "psql", "" ]
Here is the query that I have. In my Table User, the schemas is ``` CREATE TABLE [dbo].[User]( [UserId] [int] IDENTITY(1,1) NOT NULL, [UserFirstName] [nchar](33) NOT NULL, [UserSurname] [nchar](33) NOT NULL, [UserDob] [date] NULL, CONSTRAINT [PK_User] PRIMARY KEY CLUSTERED ...
Something like this? Use SCOPE\_IDENTITY not IDENTITY. ``` DECLARE @NewID int INSERT INTO User ([UserFirstName], [UserSurname], [UserDob]) Values ('Bob', 'Smith', '1979-01-01') Select @NewID = SCOPE_IDENTITY() INSERT INTO OtherTable ([UserId]) Values (@NewID) ```
If you are looking for bulk insertions suggest to use `OUTPUT INSERTED` ``` CREATE TABLE #Ids ( Id INT ) INSERT INTO [User] ([UserFirstName], [UserSurname], [UserDob]) OUTPUT INSERTED.UserId INTO #Ids VALUES ('Bob', 'Smith', '1979-01-01'), ('john', 'will', '1979-01-01'), ('jerry', 'david', '1979-01-01'...
Return Auto Increment value after inserting a record on a table
[ "", "sql", "sql-server", "sql-server-2012", "" ]
I have a **"messages table"** , and i want only to retrieve the **"user ID"** with his last message. I tried to add "2 sql statements" inside each other , But it keeps on looping without stopping, ``` sqlite3_stmt *statement; NSMutableArray * messages = [[NSMutableArray alloc]init]; const char *dbpath = [_databas...
There are a few issues: 1. You have only one `sqlite3_stmt` variable for your two nested queries. You want a separate `sqlite3_stmt` for each. 2. You are calling `sqlite3_reset`. That is only used when binding new values to `?` placeholders in your prepared statement, which is not applicable here. Worse, you're callin...
This is the query to get the last message with a given `fromID`: `SELECT * FROM chatting WHERE fromID=9999 ORDER BY id DESC LIMIT 1`
How to get the last message by distinct userID using SQlite and iOS?
[ "", "ios", "sql", "sqlite", "xcode5", "" ]
Having this two table DEPARTMENT ``` //DEPARTMENT D# DNAME ------------------- 1 RESEARCH 2 IT 3 SCIENCE ``` PROJECT ``` //PROJECT P# D# BUDGET ------------------------- 1001 1 22500 1002 1 22500 1003 3 50000 ``` When i execute t...
**All column names in SELECT list must appear in GROUP BY clause unless name is used only in an aggregate function.** Change query to: ``` SELECT d.D#,DNAME,sum(budget) as "TOTAL BUDGETS" FROM DEPARTMENT d,PROJECT p WHERE d.D# = p.D# GROUP BY d.D#, DNAME; ``` --- Update for the comment: ``` SELECT d.D#, d.DN...
``` SELECT d.D#,max(DNAME),sum(budget) as "TOTAL BUDGETS" FROM DEPARTMENT d,PROJECT p WHERE d.D# = p.D# GROUP BY d.D#; ``` You should either include the field in `GROUP BY` section or use aggregate function (`MAX` or `MIN` is ok for the case)
SUM with group by return error
[ "", "sql", "oracle", "sqlplus", "" ]
I am using SQL server 2005. I have a variable @var that can take values 0, 1, or NULL. I care about it being 1 or not, 0 and NULL are the same for me. But when I set it to be not 1, I lose the NULL values: ``` DECLARE @var INT SET @var = NULL IF @var <> 1 PRINT 'not 1' ELSE PRINT 'equals 1' ``` The outp...
You could also use `coalesce` for this: ``` if coalesce(@var, 0) <> 1 PRINT 'not 1' ELSE PRINT 'equals 1' ```
``` IF @var = 1 PRINT 'equals 1' ELSE PRINT 'not 1' ``` or ``` IF @var <> 1 or @var is null PRINT 'not 1' ELSE PRINT 'equals 1' ``` since comparing to `null` results in *unknown* which is not *true*. Use the `IS` operator for `null` values.
SQL Conditional loses NULL values
[ "", "sql", "sql-server", "null", "conditional-statements", "" ]
``` class Room < ActiveRecord::Base belongs_to :hotel belongs_to :layout has_many :visits validates :number, presence: true validates :rate, presence: true #validates :smoking, presence: true def self.occupied_rooms(from_date, to_date) #24-26 self.joins(:visits).where('date >= ? and date <= ?', from...
There's a very nice thing that got introduced in Rails 4 called a `WhereChain`. You can use it like this: ``` self.where.not(id: Room.occupied_rooms(from_date, to_date).select(:id)) ``` Though I'm pretty sure it can be even simpler with: ``` self.where.not(id: Room.occupied_rooms(from_date, to_date)) ```
You need to do: ``` self.where('rooms.id not in (?)', Room.occupied_rooms(from_date, to_date).select(:id).to_a.join(',')) ```
In Rails, how can you use a .where('rooms.id not in (?), ____), when ____ doesn't return anything?
[ "", "sql", "ruby-on-rails", "activerecord", "null", "" ]
I want to delete all values apart from the top x value but I'm not too sure what I'm doing wrong. My query: ``` DELETE FROM dbo.cake where dbo.cake.pie not in (select top 500 * from dbo.cake where createdDate >= '2007-01-01' and createdDate < '2008-01-01') ``` The error I get is: ``` Msg 116, Level 16, State 1, ...
Change to ``` DELETE FROM dbo.cake where dbo.cake.pie not in (select top 500 pie from dbo.cake where createdDate >= '2007-01-01' and createdDate < '2008-01-01') ```
Try putting the field in the subquery ``` DELETE FROM dbo.cake where dbo.cake.pie not in (select top 500 pie from dbo.cake where createdDate >= '2007-01-01' and createdDate < '2008-01-01') ```
SQL Delete all but top x
[ "", "sql", "sql-server", "" ]
I am trying to query my postgresql db to return results where a date is in certain month and year. In other words I would like all the values for a month-year. The only way i've been able to do it so far is like this: ``` SELECT user_id FROM user_logs WHERE login_date BETWEEN '2014-02-01' AND '2014-02-28' ``` Prob...
With dates (and times) many things become simpler if you use `>= start AND < end`. For example: ``` SELECT user_id FROM user_logs WHERE login_date >= '2014-02-01' AND login_date < '2014-03-01' ``` In this case you still need to calculate the start date of the month you need, but that should be straight ...
From PostreSQL 9.2 [Range Types](https://www.postgresql.org/docs/9.2/static/rangetypes.html) are supported. So you can write this like: ``` SELECT user_id FROM user_logs WHERE '[2014-02-01, 2014-03-01]'::daterange @> login_date ``` this should be more efficient than the string comparison
Postgresql query between date ranges
[ "", "sql", "postgresql", "date", "intervals", "between", "" ]